From 868e865536033049f34471a157b51bcf6c3cf518 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:15 -0800 Subject: [PATCH 1/6] fix: every YAML file is read by YAML 1.2.2, a setting of the host by one rule, and an upload by the pack's own reader The configuration reader: a plain scalar is resolved by the core schema of YAML 1.2.2 in both packs (the maintainer's ruling): true and false are the booleans, 010 is 10, and yes, on, 16_000, 1:30, 0b101, a date and the merge key are text or an ordinary key. It reads application.yml, rest.yaml, app-log-context.yaml and the MCP binding's file. As text a boolean is true or false and a float keeps its point. A key with no value and one its references leave empty take the default; a reference sees an override; a reference loop is logged and has no value. Settings of the host follow the round's rule and stop the start by name: rest.automation, rest.server.port, rest.upload.max.bytes, event.stream.keep.alive, an entry's timeout, otel.forwarding, app.log.context. REST automation and the host: one upload reader in both packs, pinned by 76 shared cases over the reader and over HTTP, with filename* and name* as RFC 5987 writes them; the client returns an edge's JSON error as the failure it carries; a reply the wire codec refuses is the engines' 500; a refusal while the request is read is traced; a name every object carries (constructor, __proto__) is read as the caller sent it; a timer is held to 2147483647 ms. The awaits that run in order on purpose carry their reason on the line (the MCP binding, the demo application, the actuator, the bus, the forwarder). The guides say how a file is read and recommend YAML 1.2.2 to whoever writes one. Co-Authored-By: Claude Fable 5.2 --- docs/guides/ai-agent-guide.md | 5 + docs/guides/config-logging-actuators.md | 3 +- docs/guides/configuration-reference.md | 99 +- docs/guides/function-patterns.md | 5 +- docs/guides/http-surface-reference.md | 12 +- docs/guides/rest-automation.md | 48 +- docs/guides/streaming.md | 3 +- docs/llms.txt | 2 +- examples/demo-app/demo-app.mjs | 2 +- extensions/mcp-binding/README.md | 3 + extensions/mcp-binding/mcp-binding.mjs | 25 +- src/actuator.ts | 2 +- src/async-http-request.ts | 45 +- src/bus.ts | 9 +- src/client.ts | 12 +- src/config.ts | 419 +++- src/envelope.ts | 23 +- src/event-stream.ts | 33 +- src/index.ts | 2 +- src/log-context.ts | 39 +- src/otel/export.ts | 6 +- src/otel/index.ts | 17 +- src/rest-automation.ts | 229 +- src/rest-routing.ts | 454 +++- src/server.ts | 110 +- test/bus.test.ts | 25 + test/client.test.ts | 71 +- test/config.test.ts | 260 ++- test/log-context.test.ts | 71 +- test/mcp-binding.test.mjs | 13 + test/otel-forwarder.test.ts | 33 +- test/rest-automation.test.ts | 409 +++- test/server.test.ts | 193 +- test/vectors/config-vectors.json | 2409 +++++++++++++++++++++ test/vectors/rest-automation-vectors.json | 1778 +++++++++++++-- 35 files changed, 6333 insertions(+), 536 deletions(-) create mode 100644 test/vectors/config-vectors.json diff --git a/docs/guides/ai-agent-guide.md b/docs/guides/ai-agent-guide.md index 51bcc97f..5d79b4a3 100644 --- a/docs/guides/ai-agent-guide.md +++ b/docs/guides/ai-agent-guide.md @@ -22,6 +22,11 @@ authored on the engine — use the 3. Function is stateless. State belongs to the calling flow/graph. 4. Orchestration-shaped logic (sequencing, retries, branching) → STOP; author an Event Script flow or MiniGraph graph on the engine instead. +5. Every YAML file (`application.yml`, `rest.yaml`) is YAML 1.2.2: write `true`/`false`, plain + decimal numbers, `0x` for hex, and quotes around any text that looks like a boolean, a number, + a date or null. Never `yes`/`no`/`on`/`off`, `010`, `0o10`, `0b101`, `1:30`, `16_000`, an + unquoted date or the merge key `<<` — the Java engine reads those another way + ([the rule](configuration-reference.md#how-a-yaml-file-is-read)). ## The contract diff --git a/docs/guides/config-logging-actuators.md b/docs/guides/config-logging-actuators.md index 12766e97..44fb1eb2 100644 --- a/docs/guides/config-logging-actuators.md +++ b/docs/guides/config-logging-actuators.md @@ -82,7 +82,8 @@ otel.service.name: 'my-node-functions' ``` With `otel.forwarding=true` (the switch is the only thing that turns it on — `false` by -default, and `-Dotel.forwarding=true` at run time is enough), the host also hands each +default, `-Dotel.forwarding=true` at run time is enough, and a value that is neither `true` +nor `false` stops the start by name), the host also hands each dataset to the engines' extension route `distributed.trace.forwarder`, where the built-in forwarder registers itself at start-up (private, two workers; an application that registers its own function on that route wins). Each dataset becomes **one OpenTelemetry span carrying diff --git a/docs/guides/configuration-reference.md b/docs/guides/configuration-reference.md index 9ae4ee99..5ed8e988 100644 --- a/docs/guides/configuration-reference.md +++ b/docs/guides/configuration-reference.md @@ -16,32 +16,117 @@ keywords: [configuration, reference, keys, substitution, overrides] 2. The configuration file: `resources/application.yml` | `.yaml` | `.properties` next to the application file (the file `mercury-serve` is given), never in the working directory; or `--config `. -3. `${ENV_VAR:default}` substitution inside values: environment first, then a base - configuration key of that name, then the default. +3. `${ENV_VAR:default}` substitution inside values: the environment variable first, then the + configuration key of that name — a `-D` override of it before the file's value, as a key is + read — then the default. A reference that leads back to a key being resolved is logged + (`Config loop for 'key' detected`, as the engines log it) and has no value, so its default + stands. A value its references leave empty is no value either, as in the Java engine: with + `llm.effort: '${LLM_EFFORT:}'` and the variable unset, the key reads as its default — the + idiom for an optional setting — while an empty text written as one (`key: ''`) stays one. + +## How a YAML file is read + +Every YAML file of the pack — `application.yml`, `rest.yaml`, `app-log-context.yaml`, an +extension's own file — is read by **YAML 1.2.2**, the same way by the Python pack and the Node.js +pack. A scalar written without quotes is resolved by the core schema of the +specification (section 10.3.2), its rows tried in this order: + +| Written | Read as | +|---------|---------| +| nothing, `~`, `null`, `Null`, `NULL` | no value: the key reads as a key that is not there, so its default applies | +| `true`, `True`, `TRUE`, `false`, `False`, `FALSE` | a boolean | +| `[-+]?[0-9]+` — `16000`, `-5`, `010` | an integer in base 10, exact at any size: `010` is 10 | +| `0o[0-7]+` — `0o17` | an integer in base 8 | +| `0x[0-9a-fA-F]+` — `0x1F` | an integer in base 16 | +| `[-+]?[0-9]+(\.[0-9]*)?([eE][-+]?[0-9]+)?` with a point or an exponent, or `[-+]?\.[0-9]+([eE][-+]?[0-9]+)?` — `1.5`, `16000.0`, `1e3`, `.5` | a float | +| `.inf`, `.Inf`, `.INF`, also with a sign; `.nan`, `.NaN`, `.NAN` | a float | +| anything else, and anything in quotes | text | + +So `yes`, `no`, `on`, `off`, `y` and `n`, a number with an underscore (`16_000`), in base 2 +(`0b101`) or in base 60 (`1:30`), `-0x10`, a date (`2026-11-30`), `=` and `<<` are text, and `<<` +as a key is a key like any other, not the merge key. A switch or a flag written `yes` is refused by +name (`rest.automation must be true or false`), never read as on and never as off. Under an +explicit tag a scalar is valid when the tag is one of the core schema's (`!!str`, `!!int`, +`!!float`, `!!bool`, `!!null`) and its content one of that tag's rows; a file with any other tag +(`!!binary`, `!!timestamp`, `!!set`) does not load. + +### Write YAML 1.2.2, and none of the additional syntax of YAML 1.1 + +This is the recommendation for whoever writes a file, a developer or an AI assistant. The Java +engine's reader (SnakeYAML) reads YAML 1.1 and still accepts the older syntax, so a file that uses +it reads one way in the Java engine and another way in the packs. The Rust engine reads YAML 1.2 as +well; its library departs from the core schema in three spellings, which the table shows: + +| Do not write | The Java engine reads | The Rust engine reads | The packs read | Write | +|--------------|-----------------------|-----------------------|----------------|-------| +| `yes`, `no`, `on`, `off` | a boolean | text | text | `true`, `false` | +| `010`, `08` | 8 (base 8), text | text | 10, 8 | `10`, `8` — or `'010'` when it is text | +| `0o10` | text | 8 | 8 | `8` | +| `0b101` | 5 | 5 | text | `5` | +| `-0x10` | -16 | -16 | text | `-16` | +| `1:30` | 90 (base 60) | text | text | `90` — or `'1:30'` when it is text | +| `16_000` | 16000 | text | text | `16000` | +| `2026-11-30` | a date, written in the time zone of its JVM | text | text | `'2026-11-30'` | +| `<<: *base` | the merge key | a key named `<<` | a key named `<<` | the keys themselves | + +`yes`/`no`/`on`/`off`, `0b101`, `1:30`, `16_000` and the merge key are syntax of YAML 1.1 only. A +number with a leading zero (`010`, `08`), `0o10` and an unquoted date are valid YAML 1.2.2 and are +to be avoided all the same, because the Java engine reads them another way and the Rust engine keeps a +number with a leading zero as text. `y` and `n`, booleans +in YAML 1.1 itself, are text in every runtime. The forms every runtime reads alike: `true` and `false`; a plain decimal number without a leading zero, an underscore or a +colon (`16000`, `-5`, `1.5`, `1e3`); `0x` for base 16 (`0x1F`); and quotes around any text that +could be read as a boolean, a number, a date or no value (`'true'`, `'010'`, `'1e3'`, +`'2026-11-30'`, `'null'`). + +### The text of a value + +As text — what `getProperty` returns, and what a reference inside a longer text is replaced by — a +boolean is `true` or `false` and a float keeps its point (`1.0`, never `1`), so +`info.app.version: 1.0` reads `1.0` in both packs; a float is written as Python writes one, which +is the Java engine's text too between 0.001 and 10,000,000. A mapping key YAML read as something +other than text (`True:`, `8080:`) is the text of that value (`true`, `8080`). A tab is read as two +spaces, as the Java engine reads a file, so one indented with tabs loads. A file whose document is +not a mapping has no keys, and the last of two equal keys stands. + +## A number, a duration and a switch + +The settings of the host read these by one rule, the same in both packs; a value that is none of +them stops the start by name instead of being read as off or as a default: + +- **a whole number** — a number with a whole value (`16000`, `16000.0`), or text of the digits + `0`-`9` with white space around them at most, up to 9007199254740991. A sign, an underscore, a + point or an exponent in text and a digit of another script are refused + (`rest.upload.max.bytes must be a whole number >= 0`); +- **a duration** — such a number, in seconds, or the number and, right after it, one of `ms`, `s`, + `m`, `h`, `d`: `30`, `30s`, `500ms`, `2m` + (`event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none`); +- **a switch** — the boolean `true` or `false`, or that text in any letter case; no value and an + empty one are the default (`rest.automation must be true or false`). ## Well-known keys (shared with the engines) | Key | Meaning | Default | |-----|---------|---------| | `application.name` | application identity in logs, `/info` and `/health` | `application` | -| `rest.server.port` | Event API + actuator port | `8085` | +| `rest.server.port` | Event API + actuator port: a whole number up to 65535, `0` for one the system picks | `8085` | | `log.format` | `text`, `json` (pretty-printed) or `compact` (single-line JSONL) | `text` | | `log.level` | log level; the `LOG_LEVEL` environment variable wins | `INFO` | +| `app.log.context` | the application log context: a `context` block on every structured log line inside a traced request ([guide](function-patterns.md#trace-context-and-span-lineage)); a switch — `false` opts out, any value but `true` or `false` stops the start | `true` | | `info.app.version` | version reported by `/info` | package version | | `info.app.description` | description reported by `/info` | `application.name` | | `show.env.variables` | opt-in list of environment variables shown by `/env` | (empty) | | `show.application.properties` | opt-in list of configuration keys shown by `/env` | (empty) | | `mandatory.health.dependencies` | routes of health check functions that decide `/health` | (empty) | | `optional.health.dependencies` | health check routes reported but never affecting status | (empty) | -| `rest.automation` | REST automation on: the entries of `rest.yaml` served in front of the functions ([guide](rest-automation.md)) | `false` | +| `rest.automation` | REST automation on: the entries of `rest.yaml` served in front of the functions ([guide](rest-automation.md)); a switch — any value but `true` or `false` stops the start | `false` | | `yaml.rest.automation` | the one location of `rest.yaml`: `classpath:` the resources folder, `file:` an absolute path, a relative path under the application file's folder | `classpath:/rest.yaml` | -| `rest.upload.max.bytes` | the bound on one upload: its files and its text fields together, counted in bytes (413 beyond it) | `16777216` | +| `rest.upload.max.bytes` | the bound on one upload: its files and its text fields together, counted in bytes (413 beyond it); a whole number | `16777216` | | `http.trace.id.header` | the trace-id header a traced entry reads when no W3C `traceparent` arrives (`trace.id.header` overrides it per entry) | `X-Trace-Id` | | `http.correlation.id.header` | the business correlation-id header, always ensured and echoed (`correlation.id.header` per entry) | `X-Correlation-Id` | | `http.traceparent.header` | a custom name for the W3C `traceparent` header, read only when the standard one is absent (`traceparent.header` per entry) | `traceparent` | -| `event.stream.keep.alive` | the keep-alive comment interval of a Server-Sent Events reply (`/api/event` and streaming entries); `0` disables | `30s` | +| `event.stream.keep.alive` | the keep-alive comment interval of a Server-Sent Events reply (`/api/event` and streaming entries): a duration up to 2147483647 ms (about 24.8 days, the longest a timer of the Node.js pack holds); `0` disables | `30s` | | `static.html.folder` | the folder of static web content the host serves for the paths nothing else claims — relative to the application file's folder ([guide](config-logging-actuators.md#static-content-the-engines-public-folder)) | `resources/public` | -| `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)) | `false` | +| `otel.forwarding` | the OpenTelemetry forwarder's master switch ([guide](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in)); a switch — any value but `true` or `false` stops the start | `false` | | `otel.exporter.otlp.endpoint` | the OTLP/HTTP traces URL including the signal path | `http://localhost:4318/v1/traces` | | `otel.exporter.otlp.headers` | request headers, `k=v` or `k: v`, comma-separated (re-read per export) | (none) | | `otel.exporter.otlp.timeout` | per-export timeout in milliseconds, connect included | `10000` | diff --git a/docs/guides/function-patterns.md b/docs/guides/function-patterns.md index 4d3b53ae..154a4e61 100644 --- a/docs/guides/function-patterns.md +++ b/docs/guides/function-patterns.md @@ -112,8 +112,9 @@ engines' app-log-context feature, on by default) - the standard trace context `parentSpanId`, `service`, `timestamp`) - so application logs and the distributed-trace records correlate in one aggregation. Customize with your own `resources/app-log-context.yaml` (`context:` section mapping output keys -to reserved `$tokens` or constants, `${ENV:default}` supported), opt out with -`app.log.context=false`, and add per-request key-values from a handler with +to reserved `$tokens` or constants, `${ENV:default}` supported; read as every YAML +file of the pack is), opt out with `app.log.context=false` (a switch: any value but +`true` or `false` stops the start), and add per-request key-values from a handler with `updateContext('tenant', 'acme')` (a logging-only sink; reserved keys are guarded; `null` removes). diff --git a/docs/guides/http-surface-reference.md b/docs/guides/http-surface-reference.md index b63e8919..25c4a05e 100644 --- a/docs/guides/http-surface-reference.md +++ b/docs/guides/http-surface-reference.md @@ -17,11 +17,11 @@ Mirrors the engines' `event.api.service`: | Aspect | Behavior | |--------|----------| | Request body | event envelope bytes ([standard wire format](https://accenture.github.io/mercury-composable/guides/event-envelope-wire-format/)) | -| `x-ttl` header | execution bound in ms (floor 1000) | +| `x-ttl` header | execution bound in ms (floor 1000; above 2147483647, the longest delay a timer holds here, the wait is that long); a value that is no whole number counts as none | | `x-async: true` | drop-n-forget → HTTP 202 with ack envelope `{type: async, delivered: true, time}` | | Reply | always envelope bytes, `content-type: application/octet-stream` | | Handler outcome | rides **HTTP 200** with the status inside the envelope (including AppException and unexpected errors) | -| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`), 413 a body over the 16 MiB the host reads into memory (`Request body exceeds 16777216 bytes`) | +| Transport failures | set the HTTP status too: 400 undecodable / missing route field, 403 private target, 404 unknown route (`Route X not found`), 408 timeout (`Timeout for N ms`), 413 a body over the 16 MiB the host reads into memory (`Request body exceeds 16777216 bytes`), 500 a reply the wire codec refuses (`Reply cannot be rendered`; in band, as the terminal frame, once a stream has started). Behind a `rest.yaml` entry the edge's own refusals (401, 413) are the engines' JSON error body, which the pack's client and the engines' read as the failure it carries | | Header hygiene | inbound `x-event-api` and `my_*` removed; the `my_cid` tag becomes the read-only `my_correlation_id` header (local bus deliveries inject the same view). Outbound, the client stamps the current context's business correlation-id back onto the event as the `my_cid` tag — the engines' PostOffice parity, so the business correlation-id continues across every hop | | `accept: text/event-stream` | streaming-capable call to an interceptor target: a streamed reply rides the same call as SSE in the envelope-mode dialect; a single-shot reply stays byte-identical; a streaming reply to a NON-accepting caller → 406 `Streaming function requires a caller that accepts text/event-stream`. See [Event Streaming](streaming.md) | @@ -57,10 +57,10 @@ first, in the engines' grammar; `POST /api/event` and the actuators are the defa | Matching | the engines' precedence — the most specific route wins, `{param}` and a trailing `*`; a known path under another method → 405 `Method not allowed`; an unknown path → 404 `Resource not found`; `OPTIONS` → 204 with the entry's CORS `options` lines, 405 without a CORS block | | Request to the function | the whole request as the `AsyncHttpRequest` map — method, url, headers (lowercased, after the request transform), path and query parameters (a form's fields among them), the body parsed by its content type (JSON → map or list, text types → text, else bytes), cookies, the `session` map an authentication function left; `x-ttl` carries the entry's timeout in ms | | Reply | a returned value is the body; a returned `EventEnvelope` sets the status and headers (`set-cookie` values split on `\|`); the content type is the function's or negotiated from `Accept` (`text/html` wraps a map in the HTML shell; no `Accept` → no content type); a map or list is pretty-printed JSON with `null` entries omitted | -| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes`; 413 `Request body exceeds 16777216 bytes` for a body over the 16 MiB the host reads into memory; 500 `Reply cannot be rendered` for a reply the serializer refuses | -| Correlation and tracing | `X-Correlation-Id` (or `http.correlation.id.header`) always ensured and echoed, delivered as `my_correlation_id`; with `tracing: true` a W3C `traceparent`, else `X-Trace-Id` (`http.trace.id.header`), else a fresh id, and the `http.request` record plus the function's round-trip record | -| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` overrides it; a keep-alive that cannot be written ends the stream; a segment the serializer refuses fails it in band with 500 `Reply cannot be rendered` | -| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; the files and the text fields together, counted in bytes, within `rest.upload.max.bytes` (16 MiB); a part that is multipart itself → 400 `Upload takes text fields and files, not a nested multipart part` | +| Errors | the engines' body below with `content-type: application/json`: an `AppException` from the function or the authentication function (anything but `true` from the latter → 401 `Unauthorized`); 408 `Timeout for N ms` at the entry's timeout (1 s–5 min, 30 s default; an inbound `x-ttl` that is a whole number wins); 503 `Service X not reachable` for an unregistered function; 413 `Upload exceeds N bytes` and the 400s of an upload a form does not send; 413 `Request body exceeds 16777216 bytes` for a body over the 16 MiB the host reads into memory; 500 `Reply cannot be rendered` for a reply the serializer refuses | +| Correlation and tracing | `X-Correlation-Id` (or `http.correlation.id.header`) always ensured and echoed, delivered as `my_correlation_id`; with `tracing: true` a W3C `traceparent`, else `X-Trace-Id` (`http.trace.id.header`), else a fresh id, and the `http.request` record plus the function's round-trip record; a refusal while the body is read (400, 413) leaves the `http.request` record too | +| `stream: true` | an interceptor's segments rendered progressively: Server-Sent Events (`event:`/`data:` frames, `event: done` at the end, `event: error` in band, `: ping` keep-alives every `event.stream.keep.alive`) for a `text/event-stream` head or `Accept`, chunked text or JSON lines otherwise; the entry's timeout is the idle allowance, the head's `x-ttl` (a whole number of seconds) overrides it; a keep-alive that cannot be written ends the stream; a segment the serializer refuses fails it in band with 500 `Reply cannot be rendered` | +| `upload: true` | a `POST` entry's `multipart/form-data` files in the request map (`filename`, `file_type`, `file_length`, `upload`, `size`, bytes in `contents`), the form's text fields as query parameters, no body; the files and the text fields together, counted in bytes, within `rest.upload.max.bytes` (16 MiB). Read as a browser's form sends it, the same in both packs: a part is `form-data` with a `name` and, for a file, a `filename` (an empty one included), either also in the extended form `name*` / `filename*` (RFC 5987: UTF-8 or ISO-8859-1, percent-encoded), which wins; a file's type is its `Content-Type` as written or `application/octet-stream`, its bytes as they arrived; a text field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares. Anything else → 400 by name: a part that is multipart itself (`Upload takes text fields and files, not a nested multipart part`), a part without a name, a `name*` or `filename*` that is malformed, in another charset or not the text it declares, a `Content-Transfer-Encoding` other than `7bit`, `8bit`, `binary`, a `Content-Encoding`, another charset, a field that is not the text it declares, a body not delimited as declared (`Invalid multipart body - ...`) | | Precedence | a `rest.yaml` entry, then an extension's mounted routes (`Platform.addRoutes`), then the static folder (under the `static-content` block's `no-cache-pages` and `filter`), then the error signature below | ## Static content diff --git a/docs/guides/rest-automation.md b/docs/guides/rest-automation.md index 9fd090b7..944d9761 100644 --- a/docs/guides/rest-automation.md +++ b/docs/guides/rest-automation.md @@ -73,11 +73,19 @@ headers: - "Cache-Control: no-cache, no-store" ``` -`${key:default}` in any value resolves against the configuration, as in the engines. A flag — -`tracing`, `stream`, `upload` — is `true` or `false`, read as the Java engine reads it: the +`${key:default}` in any value resolves against the configuration, as in the engines: the +environment variable of that name, then the configuration key — a `-Dkey=value` override of it +before the file's value — then the default. The file itself is read as `application.yml` is, by +YAML 1.2.2 ([the rule](configuration-reference.md#how-a-yaml-file-is-read)): a boolean is `true` +or `false`, `yes` and `on` are text, `1e3` is a number, `1_0` and `1:30` are text, a date is the +text as written. A flag — `tracing`, `stream`, `upload` — is `true` or `false`: the boolean, or the text in any letter case, which is what a reference such as `${TRACING:true}` -resolves to. Left out or empty it is off; any other value fails the start by name -(`rest[0] 'tracing' must be true or false`) rather than leave the flag off without a word. At the end +resolves to and what the Java engine takes too. Left out or empty it is off; any other value fails the start by name +(`rest[0] 'tracing' must be true or false`) rather than leave the flag off without a word. A +`timeout` is a whole number of seconds, or such a number and, right after it, one of `ms`, `s`, +`m`, `h`, `d` (`30s`, `2m`, `1500ms`); a value that is neither fails the start by name too +(`rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)`), where +the Java engine reads it as one second without a word. At the end of the boot the host announces every live entry — `REST [GET] /api/hello/{name} -> hello.rest` — and skips, with a warning, an entry whose function is not registered: never a live URL without a function behind it. @@ -145,12 +153,15 @@ unchanged — a flow binding apart — and behaves the same: the trace-id header (`http.trace.id.header`, `X-Trace-Id`), else a fresh id, and leaves the `http.request` record and the function's round-trip record the engines leave, so the [OpenTelemetry forwarder](config-logging-actuators.md#distributed-tracing-the-opentelemetry-forwarder-opt-in) - exports the request as a SERVER span with the function beneath it. An entry may rename its + exports the request as a SERVER span with the function beneath it. A request the edge refuses + while it reads the body — a malformed upload, a body over a limit — leaves the `http.request` + record too, with the status and the message, as the engines record a traced request once its + trace is resolved. An entry may rename its headers for a legacy caller with `trace.id.header`, `correlation.id.header` and `traceparent.header`. - **Timeout** — the entry's `timeout` (1 s to 5 min, 30 s by default; the `/api/event` default entry keeps the engines' 60 s) rides the request as `x-ttl` in milliseconds and answers 408 - `Timeout for N ms` when it expires; an inbound `x-ttl` wins. + `Timeout for N ms` when it expires; an inbound `x-ttl` that is a whole number wins. - **Headers** — the entry's `headers` block drops, keeps or adds request and response headers (`keep` takes precedence over `drop`, the Java rule); its `cors` block's `headers` lines ride every response. @@ -255,8 +266,26 @@ read with `request.files()` as `UploadedFile { name, contentType, size, tag, con text fields become query parameters and the body stays absent, as in the Java engine. The files and the text fields of one upload together, counted in bytes, may not exceed `rest.upload.max.bytes` (16 MiB by default) — 413 `Upload exceeds N bytes` the moment they do, before anything is -delivered. A malformed body is 400, and so is a part that is multipart itself: -`Upload takes text fields and files, not a nested multipart part`. +delivered. + +The body is read by the pack's own reader, the same in the Python and the Node.js pack, as a +browser's form sends one: parts delimited by the boundary the content type declares, each +`Content-Disposition: form-data` with a `name` and, for a file, a `filename` — a file input left +empty arrives as a file with an empty name and no bytes. A name or a filename may also come in the +extended form a client writes for one that is not ASCII (`filename*=UTF-8''caf%C3%A9.txt`, RFC +5987: UTF-8 or ISO-8859-1, the bytes percent-encoded), which wins over the plain parameter of its +name. A file's type is its `Content-Type` as +written, `application/octet-stream` without one, and its bytes are the bytes that arrived. A text +field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares, and a field named `_charset_` is +a field like any other. What a form does not send is a 400 that names it: a part that is multipart +itself (`Upload takes text fields and files, not a nested multipart part`), a part without a name, +an extended parameter that is malformed, in another charset or not the text it declares +(`Upload takes a part's filename* in UTF-8 or ISO-8859-1, not in 'Windows-1252'`), a +`Content-Transfer-Encoding` other than `7bit`, `8bit` or +`binary` and any `Content-Encoding` (`Upload takes the bytes of a part as they are, not a +Content-Encoding of 'gzip'`), a field in another charset or one that is not the text it declares +(`Upload text field 'note' is not UTF-8`), and a body that is not delimited as declared +(`Invalid multipart body - the closing delimiter is missing`). A non-multipart body on such an entry, and a multipart body on an entry without the flag, dispatch as any other body. The LLM helper's `llm.upload` — documents saved into the attachments root for a model to read — is the shipped example. @@ -268,7 +297,8 @@ A `GET` or `HEAD` no entry claims is served from the `static-content` block of `rest.yaml`: the `no-cache-pages` (default `/` and `/index.html`) are served `Cache-Control: no-cache, no-store`, and the `filter` function sees every matching static request first — its reply headers ride the response, a status other than 200 (a 302 to a sign-in -page) passes through, and a filter that fails lets the file be served. +page) passes through, and a filter that fails lets the file be served. A reply of its own that +cannot be rendered is answered as any other: 500 `Reply cannot be rendered`. ```yaml static-content: diff --git a/docs/guides/streaming.md b/docs/guides/streaming.md index 56104417..6d860966 100644 --- a/docs/guides/streaming.md +++ b/docs/guides/streaming.md @@ -65,7 +65,8 @@ byte-identical to a normal RPC reply; idle expiry fails the stream in-band with standard 408 error body. The `x-ttl` request header (ms) is the idle allowance between segments — your `first(..., ttlSeconds)` can extend it for the whole stream. While the producer is quiet, the host emits `: ping` keep-alive comments -(`event.stream.keep.alive`, the engines' config key — default 30s, `0` disables). +(`event.stream.keep.alive`, the engines' config key — default 30s, `0` disables; a whole number +of seconds or a duration such as `500ms` or `2m`, and a value that is neither stops the start). ## Consume a stream diff --git a/docs/llms.txt b/docs/llms.txt index 8d38db27..c03b0363 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -29,6 +29,6 @@ - [Join a Knowledge Graph](https://accenture.github.io/mercury-nodejs/guides/join-knowledge-graph/): graph.task to a declarative target (engines >= v4.11.11), deadlines, the error.* contract. ## Reference -- [Configuration Reference](https://accenture.github.io/mercury-nodejs/guides/configuration-reference/): every well-known key, resolution order, substitution syntax. +- [Configuration Reference](https://accenture.github.io/mercury-nodejs/guides/configuration-reference/): every well-known key, resolution order, substitution syntax, and how a YAML file is read: YAML 1.2.2 — write `true`/`false`, plain decimal numbers and quoted text; never the additional syntax of YAML 1.1 (`yes`/`no`/`on`/`off`, `010`, `0b101`, `1:30`, `16_000`, an unquoted date, the merge key `<<`), which the Java engine reads another way. - [HTTP Surface Reference](https://accenture.github.io/mercury-nodejs/guides/http-surface-reference/): /api/event protocol, actuator shapes, the REST automation entries' behaviour (matching, errors, streaming, upload, precedence), error signature, content types. - [Release Notes](https://github.com/Accenture/mercury-nodejs/blob/main/CHANGELOG.md) diff --git a/examples/demo-app/demo-app.mjs b/examples/demo-app/demo-app.mjs index 0897aadb..bef0a11c 100644 --- a/examples/demo-app/demo-app.mjs +++ b/examples/demo-app/demo-app.mjs @@ -75,7 +75,7 @@ preload('hello.tokens', { instances: 10, interceptor: true }, async (headers, ev out.first(200, 'text/event-stream'); out.write('The following messages are rendered slowly to demonstrate streaming:'); for (let n = 1; n <= count; n++) { - await new Promise((resolve) => setTimeout(resolve, delay)); + await new Promise((resolve) => setTimeout(resolve, delay)); // NOSONAR - sequential: the pause between two messages is the demonstration out.write(`test message ${n} (node.js)`); } // the trailing metadata echoes the distributed trace id and the business diff --git a/extensions/mcp-binding/README.md b/extensions/mcp-binding/README.md index d98d7f5b..d3b638ca 100644 --- a/extensions/mcp-binding/README.md +++ b/extensions/mcp-binding/README.md @@ -63,6 +63,9 @@ Event-over-HTTP entry on the engine. ## The server file `mcp.servers` names the file (default `mcp-servers.yml` in the resources folder; a relative path is read from there). +The file is read as every YAML file of the pack is, by YAML 1.2.2 (`yes` and `on` are text, `010` is ten), and a value +written without quotes that is a boolean or a number reaches the server as the text a setting reads (`true`, `1.0`), +the same from both packs; quote a value that must stay as written. It holds what is environment-specific, never the tools: ```yaml diff --git a/extensions/mcp-binding/mcp-binding.mjs b/extensions/mcp-binding/mcp-binding.mjs index d92e54d6..440b0a51 100644 --- a/extensions/mcp-binding/mcp-binding.mjs +++ b/extensions/mcp-binding/mcp-binding.mjs @@ -41,11 +41,12 @@ import { createHash } from 'node:crypto'; import { existsSync, readFileSync, statSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import YAML from 'yaml'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js'; import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { AppException, appConfig, getLogger, loadConfig, platform, preload, VERSION } from 'mercury-composable'; +import { + AppException, appConfig, getLogger, loadConfig, parseYamlAsText, platform, preload, VERSION +} from 'mercury-composable'; const defaultLog = getLogger('mcp-binding'); @@ -179,8 +180,12 @@ export function toolAsPlain(tool) { // --- configuration: the servers ---------------------------------------------------------- +/** + * `${VAR}` and `${VAR:default}` placeholders from the environment or the configuration, the pack's + * rule for every setting, as the text a setting reads; the resolved value is never logged. + */ function resolveValue(value) { - return typeof value === 'string' ? appConfig().resolveText(value) : value; + return typeof value === 'string' ? appConfig().resolveProperty(value) : value; } function stringMap(server, key, value) { @@ -273,7 +278,9 @@ export function loadServers(path, log = defaultLog) { if (!existsSync(file) || !statSync(file).isFile()) { throw new BindingError(`MCP server file not found - ${file} (mcp.servers names it)`); } - const data = YAML.parse(readFileSync(file, 'utf8')) ?? {}; + // read as every YAML file of the pack is, each value as the text a setting reads (true, 1.0), + // the same in the Python twin + const data = parseYamlAsText(readFileSync(file, 'utf8')) ?? {}; let servers = isMap(data) ? data.servers : undefined; if (servers === undefined || servers === null) servers = {}; if (!isMap(servers)) { @@ -438,7 +445,7 @@ export function createBinding({ async function shutdown() { for (const server of servers.values()) { - await server.close(); + await server.close(); // NOSONAR - sequential: the servers close one at a time } servers.clear(); } @@ -463,7 +470,7 @@ export function createBinding({ continue; } const server = new Server(spec, bindings, connect, log); - await server.start(); + await server.start(); // NOSONAR - sequential: the first server that cannot start stops the boot, by its name servers.set(spec.name, server); for (const { binding } of server.bound) { log.info(`MCP server ${spec.name}: tool ${binding.tool} bound`); @@ -518,12 +525,12 @@ export function createBinding({ return 1; } for (const spec of wanted) { - const client = await connect(spec); + const client = await connect(spec); // NOSONAR - sequential: one server at a time, in the order they were asked for let offered; try { - offered = await listTools(client); + offered = await listTools(client); // NOSONAR - sequential: one server at a time } finally { - await client.close().catch(() => undefined); + await client.close().catch(() => undefined); // NOSONAR - sequential: a client closes before the next server is opened } const bindings = new Map(declaredFor(spec.name).map((d) => [d.tool, d])); out(`# MCP server ${spec.name} (${spec.transport}) offers ${offered.length} tool(s)`); diff --git a/src/actuator.ts b/src/actuator.ts index d244e0a7..ac2fee09 100644 --- a/src/actuator.ts +++ b/src/actuator.ts @@ -295,7 +295,7 @@ export class Actuator { for (const route of services) { const entry: Record = { route, required }; dependency.push(entry); - if (!await this.checkService(route, entry)) { + if (!await this.checkService(route, entry)) { // NOSONAR - sequential: the dependencies are probed in the order /health lists them allUp = false; } } diff --git a/src/async-http-request.ts b/src/async-http-request.ts index 7cc72d19..35bcb716 100644 --- a/src/async-http-request.ts +++ b/src/async-http-request.ts @@ -25,7 +25,8 @@ * (`new EventEnvelope().setStatus(201).setHeader('Location', url).setBody(result)`); an error is a * thrown `AppException(status, message)`. */ -import { asText } from './envelope.js'; +import { wholeNumber } from './config.js'; +import { asText, own, put } from './envelope.js'; import { isMapping, QueryValues } from './rest-routing.js'; /** @@ -56,7 +57,7 @@ function textMap(value: unknown): Record { const result: Record = {}; if (isMapping(value)) { for (const [key, item] of Object.entries(value)) { - result[key] = asText(item); + put(result, key, asText(item)); } } return result; @@ -66,7 +67,7 @@ function textMap(value: unknown): Record { function copyQuery(values: QueryValues): QueryValues { const result: QueryValues = {}; for (const [key, value] of Object.entries(values)) { - result[key] = Array.isArray(value) ? [...value] : value; + put(result, key, Array.isArray(value) ? [...value] : value); } return result; } @@ -79,7 +80,7 @@ export class AsyncHttpRequest { private _headers: Record = {}; private _body: unknown = undefined; private _hasBody = false; - private _query: QueryValues = {}; + private readonly _query: QueryValues = {}; private _path: Record = {}; private _cookies: Record = {}; private _session: Record = {}; @@ -120,7 +121,7 @@ export class AsyncHttpRequest { const query = parameters.query; if (isMapping(query)) { for (const [key, value] of Object.entries(query)) { - this._query[key] = Array.isArray(value) ? value.map((v) => asText(v)) : asText(value); + put(this._query, key, Array.isArray(value) ? value.map((v) => asText(v)) : asText(value)); } } this._path = textMap(parameters.path); @@ -239,7 +240,7 @@ export class AsyncHttpRequest { } pathParameter(name: string): string | undefined { - return this._path[name]; + return own(this._path, name); } get queryParametersMap(): QueryValues { @@ -248,7 +249,7 @@ export class AsyncHttpRequest { /** The first value of a query parameter. */ queryParameter(name: string): string | undefined { - const value = this._query[name]; + const value = own(this._query, name); if (Array.isArray(value)) { return value.length ? value[0] : undefined; } @@ -257,7 +258,7 @@ export class AsyncHttpRequest { /** Every value of a repeated query parameter. */ queryParameters(name: string): string[] { - const value = this._query[name]; + const value = own(this._query, name); if (value === undefined) { return []; } @@ -269,7 +270,7 @@ export class AsyncHttpRequest { } cookie(name: string): string | undefined { - return this._cookies[name]; + return own(this._cookies, name); } get session(): Record { @@ -277,7 +278,7 @@ export class AsyncHttpRequest { } sessionInfo(name: string): string | undefined { - return this._session[name]; + return own(this._session, name); } get remoteIp(): string | undefined { @@ -288,16 +289,10 @@ export class AsyncHttpRequest { return Boolean(this._https); } - /** The entry's timeout in seconds; a caller-sent `x-ttl` (milliseconds) wins. */ + /** The entry's timeout in seconds; a caller-sent `x-ttl` (milliseconds) wins when it is a whole number. */ get timeoutSeconds(): number | undefined { - const ttl = this.header('x-ttl'); - if (ttl !== undefined) { - const trimmed = ttl.trim(); - if (/^[+-]?\d+$/.test(trimmed)) { - return Math.max(1, Math.floor(Number.parseInt(trimmed, 10) / 1000)); - } - } - return this._timeout; + const ttl = wholeNumber(this.header('x-ttl')); + return ttl === undefined ? this._timeout : Math.max(1, Math.floor(ttl / 1000)); } get queryString(): string | undefined { @@ -368,10 +363,10 @@ export class AsyncHttpRequest { const kept: Record = {}; for (const [key, item] of Object.entries(this._headers)) { if (key.toLowerCase() !== lowered) { - kept[key] = item; + put(kept, key, item); } } - kept[name] = value; + put(kept, name, value); this._headers = kept; return this; } @@ -383,22 +378,22 @@ export class AsyncHttpRequest { } setQueryParameter(name: string, value: string | string[]): this { - this._query[name] = Array.isArray(value) ? [...value] : value; + put(this._query, name, Array.isArray(value) ? [...value] : value); return this; } setPathParameter(name: string, value: string): this { - this._path[name] = value; + put(this._path, name, value); return this; } setCookie(name: string, value: string): this { - this._cookies[name] = value; + put(this._cookies, name, value); return this; } setSessionInfo(name: string, value: string): this { - this._session[name] = value; + put(this._session, name, value); return this; } diff --git a/src/bus.ts b/src/bus.ts index 4ae89dae..963e8367 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -32,6 +32,7 @@ * The bus is internal: application code uses preload() and PostOffice, never * this module - the same way engine developers never touch the engine bus. */ +import { timerMs } from './config.js'; import { EventEnvelope, isoUtc } from './envelope.js'; import { AppException } from './exceptions.js'; import { getLogger } from './log.js'; @@ -239,7 +240,7 @@ export class Mailbox { export async function raceMs(pending: Promise, timeoutMs: number): Promise { let timer: NodeJS.Timeout | undefined; const expiry = new Promise((resolve) => { - timer = setTimeout(() => resolve(null), Math.max(1, timeoutMs)); + timer = setTimeout(() => resolve(null), timerMs(Math.max(1, timeoutMs))); }); try { return await Promise.race([pending, expiry]); @@ -326,7 +327,7 @@ export class EventBus { delivery.settled = true; reject(new DeliveryTimeout(ttlMs)); } - }, Math.max(100, ttlMs)); + }, timerMs(Math.max(100, ttlMs))); // deliberately referenced: an in-flight RPC is pending work and holds the // process open (at most until its deadline); an idle bus holds nothing delivery.resolve = (reply) => { @@ -376,8 +377,8 @@ export class EventBus { continue; } const reply = delivery.service.interceptor - ? await this.executeInterceptor(delivery) - : await this.execute(delivery); + ? await this.executeInterceptor(delivery) // NOSONAR - sequential: a worker runs one delivery at a time + : await this.execute(delivery); // NOSONAR - sequential: a worker runs one delivery at a time if (delivery.resolve) { if (!delivery.settled) { delivery.settled = true; diff --git a/src/client.ts b/src/client.ts index 92e4544e..b440b7ee 100644 --- a/src/client.ts +++ b/src/client.ts @@ -12,6 +12,7 @@ * back as a normal envelope with status >= 400 — inspect reply.getStatus(). */ import { asyncAck, DeliveryTimeout, raceMs, roundTripRecord } from './bus.js'; +import { timerMs } from './config.js'; import { EventEnvelope, isoUtc } from './envelope.js'; import { DATA, @@ -193,12 +194,18 @@ export class PostOffice { method: 'POST', headers: this.httpHeaders(timeoutMs, isAsync, event), body: event.toBytes(), - signal: AbortSignal.timeout(Math.max(100, timeoutMs) + 100) + signal: AbortSignal.timeout(timerMs(Math.max(100, timeoutMs) + 100)) }); const payload = new Uint8Array(await response.arrayBuffer()); try { return EventEnvelope.fromBytes(payload); } catch (e) { + // an edge-level REST error - the peer's /api/event sits behind an entry that answered for + // it - is the failure it carries, as the engines' client reads it + const failure = restErrorReply(payload, response.status); + if (failure) { + return failure; + } throw new AppException(response.status, `Invalid event-over-http response - ${(e as Error).message}`); } @@ -481,7 +488,8 @@ function restErrorReply(payload: Uint8Array, httpStatus: number): EventEnvelope return null; } try { - const data: unknown = JSON.parse(Buffer.from(payload).toString('utf-8')); + // UTF-8 or nothing, as the Python twin reads the body + const data: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(payload)); if (data && typeof data === 'object' && !Array.isArray(data)) { const record = data as Record; if (record['type'] === 'error' && typeof record['message'] === 'string') { diff --git a/src/config.ts b/src/config.ts index ab748618..12f186be 100644 --- a/src/config.ts +++ b/src/config.ts @@ -11,7 +11,15 @@ * overrides checked first on every read — the same syntax as the Java * engine's JVM system properties and the Rust port's -D arguments (the * f:setConfig analog); `${ENV_VAR:default}` substitution resolves the - * environment first, then a base configuration key, then the default. + * environment first, then a configuration key of that name (a -D override of + * it before the file's value, as a key is read), then the default; a value its + * references leave empty is no value - the key reads as its default. + * + * A YAML file is read by one rule (`parseYaml`: the core schema of YAML 1.2.2; + * the Rust engine reads YAML 1.2 too, the Java engine's reader also takes the + * older spellings of YAML 1.1), and a number, a duration and a switch by one + * rule (`wholeNumber`, `durationMs`, `switchValue`) - the Python twin reads the + * same file and the same values the same way. * * Well-known keys shared with the engines: application.name, * rest.server.port (default 8085), log.format (text | json pretty-printed | @@ -21,12 +29,20 @@ import * as fs from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import YAML from 'yaml'; +import type { ScalarTag, Tags } from 'yaml'; import { asText } from './envelope.js'; +import { getLogger } from './log.js'; const REF = /\$\{([^}]+)\}/g; const WHOLE_REF = /^\$\{([^}]+)\}$/; +// whether a text holds a reference at all +const HAS_REF = /\$\{[^}]+\}/; + +// what a key reads as when neither an override nor the file carries it +const MISSING: unique symbol = Symbol('missing'); + export const DEFAULT_CANDIDATES = [ 'resources/application.yml', 'resources/application.yaml', @@ -35,6 +51,51 @@ export const DEFAULT_CANDIDATES = [ export const RESOURCES_FOLDER = 'resources'; +// --- how a YAML file is read: the same in both packs ---------------------------------------- +// Every YAML file of a pack - the configuration file, rest.yaml, a companion file - is read by +// YAML 1.2.2: a plain scalar is resolved by the core schema (section 10.3.2 of the specification), +// its rows tried in the order they stand in below, and what none of them matches is text. The +// Python twin reads by the same rule, and the Rust engine reads YAML 1.2 as well; the Java engine's +// reader reads YAML 1.1. So yes, +// no, on and off are text, as are a number with an underscore (16_000), in base 2 (0b101) or in +// base 60 (1:30), a date and the lone =; 010 is ten and 0o10 is eight; and << is a key like any +// other, never the merge key. The schema is the library's own, with this reader's rows for an +// integer and a float, for exactness: an integer whole at any size, a float that keeps its point +// as text. A scalar under an explicit tag is valid when the core schema has the tag and the +// content is one of the tag's rows (section 3.3.3); a document with any other tag does not load. +const INT_TAG = 'tag:yaml.org,2002:int'; +const FLOAT_TAG = 'tag:yaml.org,2002:float'; +// the rows of the library's schema this reader replaces with its own +const OWN: ReadonlySet = new Set([INT_TAG, FLOAT_TAG]); +// \d is the digits 0 to 9 and no other here +const INT_BASE_10 = /^[-+]?\d+$/; +const INT_BASE_8 = /^0o[0-7]+$/; +const INT_BASE_16 = /^0x[0-9a-fA-F]+$/; +const EXPONENT = String.raw`(?:[eE][-+]?\d+)?`; +const FLOAT_NUMBER = new RegExp(String.raw`^[-+]?(?:\.\d+|\d+(?:\.\d*)?)${EXPONENT}$`); +const FLOAT_INFINITY = /^[-+]?(?:\.inf|\.Inf|\.INF)$/; +const FLOAT_NAN = /^(?:\.nan|\.NaN|\.NAN)$/; + +// --- how a number, a duration and a switch are read: the same in both packs ----------------- +/** + * The largest whole number both packs hold exactly (2**53 - 1): above it this pack's numbers + * round, and the twins would read two different numbers from one value. + */ +export const MAX_WHOLE = Number.MAX_SAFE_INTEGER; +/** + * The longest delay a timer holds here, in milliseconds (2**31 - 1, about 24.8 days): with a longer + * one `setTimeout` fires at once and `AbortSignal.timeout` fails. A setting that sets a timer is + * refused above it, in both packs. + */ +export const MAX_TIMER_MS = 2147483647; +// the white space ignored around a number: the characters JavaScript's trim() and Python's +// str.strip() both take for white space, so neither pack accepts a character the other refuses +const SPACE = String.raw`[\t-\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]`; +// the digits 0 to 9 and no other: \d here, where the Python twin asks for them by flag +const WHOLE = new RegExp(String.raw`^${SPACE}*(\d+)${SPACE}*$`); +const DURATION = new RegExp(String.raw`^${SPACE}*(\d+)(ms|s|m|h|d)?${SPACE}*$`); +const UNIT_MS: Readonly> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }; + /** * The folder of the script Node ran (`node app.mjs`) - where a direct run finds * its resources folder; undefined when there is no script (`node -e`, a REPL). @@ -61,13 +122,256 @@ export function parseDArgs(argv: string[]): Map { return overrides; } +/** + * A float of a YAML file. JavaScript has one number type, so a float with a whole value is kept + * apart from an integer here: as text it keeps its point (`1.0`, never `1`), as the engine and the + * Python twin write it. A reader of the typed value gets the number. + */ +class YamlFloat { + constructor(readonly value: number) {} +} + +/** An integer of a YAML file, exactly: a number up to MAX_WHOLE, a BigInt beyond it. */ +function yamlInt(source: string): number | bigint { + // BigInt reads the three forms as the schema writes them: a signed decimal, 0o and 0x + const value = BigInt(source); + const number = Number(value); + return Number.isSafeInteger(number) ? number : value; +} + +/** A row of the core schema for an integer: the scalars `form` matches. */ +const intRow = (form: RegExp): ScalarTag => ({ + identify: (found) => typeof found === 'bigint' || Number.isInteger(found), default: true, tag: INT_TAG, + test: form, resolve: yamlInt +}); + +/** A row of the core schema for a float: the scalars `form` matches, as the number `read` makes of one. */ +const floatRow = (form: RegExp, read: (source: string) => number): ScalarTag => ({ + identify: (found) => found instanceof YamlFloat, default: true, tag: FLOAT_TAG, test: form, + resolve: (source) => new YamlFloat(read(source)) +}); + +// in the specification's order: an integer is tried before a float, whose form takes one too +const SCALAR_ROWS: ScalarTag[] = [ + intRow(INT_BASE_10), + intRow(INT_BASE_8), + intRow(INT_BASE_16), + floatRow(FLOAT_NUMBER, Number), + floatRow(FLOAT_INFINITY, (source) => (source.startsWith('-') ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY)), + floatRow(FLOAT_NAN, () => Number.NaN) +]; + +/** The library's core schema with this reader's rows for an integer and a float in place of its own. */ +function scalarTags(tags: Tags): Tags { + return [...tags.filter((tag) => typeof tag === 'string' || !OWN.has(tag.tag)), ...SCALAR_ROWS]; +} + +/** + * A YAML text as its document tree: a mapping a `Map` with its keys as YAML read them, a float a + * `YamlFloat`; null for an empty document. A tab is read as two spaces, as the Java engine reads a + * file, so one indented with tabs loads here too. A text the reader cannot read is the error + * thrown - a syntax error, a second document, a tag it does not know. + */ +function readYaml(yamlText: string): unknown { + // the core schema by name, so a %YAML 1.1 directive in the text does not bring the older one + // back; no merge key and no tag beyond the schema's own; duplicate keys tolerated, the last + // winning, as the engines read a file. The library's warnings are not logged: the only one a + // document leaves - a tag the schema does not have - is thrown below + const document = YAML.parseDocument(yamlText.replaceAll('\t', ' '), { + schema: 'core', merge: false, resolveKnownTags: false, uniqueKeys: false, logLevel: 'error', + customTags: scalarTags + }); + const fault = document.errors[0] ?? document.warnings[0]; + if (fault !== undefined) { + throw fault; + } + return document.toJS({ mapAsMap: true }); +} + +/** A float as Python writes one (`repr`) - the shortest digits that read back as the same number. */ +function floatText(value: number): string { + if (Number.isNaN(value)) { + return 'nan'; + } + if (!Number.isFinite(value)) { + return value > 0 ? 'inf' : '-inf'; + } + const sign = value < 0 || Object.is(value, -0) ? '-' : ''; + const [mantissa, power] = Math.abs(value).toExponential().split('e'); + const digits = mantissa.replace('.', ''); + const exponent = Number(power); + if (exponent < -4 || exponent >= 16) { + const fraction = digits.length > 1 ? `.${digits.slice(1)}` : ''; + return `${sign}${digits[0]}${fraction}e${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`; + } + if (exponent < 0) { + return `${sign}0.${'0'.repeat(-exponent - 1)}${digits}`; + } + const whole = digits.slice(0, exponent + 1).padEnd(exponent + 1, '0'); + return `${sign}${whole}.${digits.slice(exponent + 1) || '0'}`; +} + +/** + * A value as the text a setting reads - what `getProperty` returns, and what a `${...}` reference + * inside a longer text is replaced by: a float of the file with its point, as the Python twin + * writes one, anything else as `asText` writes it. + */ +function propertyText(value: unknown): string { + return value instanceof YamlFloat ? floatText(value.value) : asText(value); +} + +/** + * A mapping key as a part of a dotted key: one YAML read as a boolean, a number or null (`True:`, + * `8080:`, `~:`) is the text of that value. A key that is a list or a mapping fails the load, as + * it does in the Python twin. + */ +function keyText(key: unknown): string { + if (key === null) { + return 'null'; + } + if (typeof key === 'object' && !(key instanceof YamlFloat)) { + throw new TypeError('A YAML mapping key must be a scalar, not a list or a mapping'); + } + return propertyText(key); +} + +/** A value as a reader of the typed value gets it: a float of the file is its number. */ +const unwrap = (value: unknown): unknown => (value instanceof YamlFloat ? value.value : value); + +/** A scalar as the text a setting reads; one without a value stays null. */ +const scalarText = (value: unknown): unknown => (value === null ? null : propertyText(value)); + +/** + * A document tree as plain JavaScript: a mapping an object keyed by text, a scalar what `scalar` + * makes of it - by default its value, a float a number. + */ +function plain(node: unknown, scalar: (value: unknown) => unknown = unwrap): unknown { + if (Array.isArray(node)) { + return node.map((item) => plain(item, scalar)); + } + if (node instanceof Map) { + const out: Record = {}; + for (const [key, value] of node) { + // defined, not assigned: a key named __proto__ is a key like any other + Object.defineProperty(out, keyText(key), { + value: plain(value, scalar), writable: true, enumerable: true, configurable: true + }); + } + return out; + } + return scalar(node); +} + +/** + * A YAML text as both packs read it - the configuration file, `rest.yaml`, a companion file - as + * plain JavaScript values; null for an empty document. + */ +export function parseYaml(yamlText: string): unknown { + return plain(readYaml(yamlText)); +} + +/** + * A YAML text as `parseYaml` reads it, with every scalar that is not text as the text a setting + * reads - a boolean `true` or `false`, an integer its digits, a float with its point (`1.0`, which + * as a number here would lose it) - and a scalar without a value null. For a companion file whose + * values are text to its reader: `app-log-context.yaml`, the MCP binding's server file. + */ +export function parseYamlAsText(yamlText: string): unknown { + return plain(readYaml(yamlText), scalarText); +} + +/** + * What a number is read from: a string as written, or the digits of a number with a whole value - + * an integer, which is all this pack sees of a float such as 16000.0. Undefined for anything else: + * a boolean, a fraction, a number beyond MAX_WHOLE. + */ +function numberText(value: unknown): string | undefined { + if (typeof value === 'string') { + return value; + } + return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : undefined; +} + +/** The whole number a run of ASCII digits spells, or undefined above MAX_WHOLE. */ +function digitsOf(digits: string | undefined): number | undefined { + const number = digits === undefined ? Number.NaN : Number(digits); + return Number.isSafeInteger(number) ? number : undefined; +} + +/** + * The whole number a value spells - a number with a whole value, or ASCII digits with white space + * around them at most - up to MAX_WHOLE; undefined when it spells none: a sign, an underscore, a + * point or an exponent in text, a digit of another script, a boolean. + */ +export function wholeNumber(value: unknown): number | undefined { + return digitsOf(WHOLE.exec(numberText(value) ?? '')?.[1]); +} + +/** + * Milliseconds from a whole number of seconds, or from such a number and, right after it, one of + * `ms`, `s`, `m`, `h`, `d` - up to MAX_WHOLE milliseconds; undefined when the value is neither. + */ +export function durationMs(value: unknown): number | undefined { + const match = DURATION.exec(numberText(value) ?? ''); + const count = digitsOf(match?.[1]); + if (count === undefined) { + return undefined; + } + const ms = count * UNIT_MS[match?.[2] ?? 's']; + return Number.isSafeInteger(ms) ? ms : undefined; +} + +/** + * A timer's delay, capped at the longest one a timer holds: a delay that comes from outside - a + * caller's `x-ttl`, a stream's idle allowance - waits that long instead of not at all. + */ +export function timerMs(ms: number): number { + return Math.min(ms, MAX_TIMER_MS); +} + +/** + * What a switch is set to: the boolean, or the text `true` or `false` in any letter case; no value + * and an empty one are the default. Undefined for any other value - it is never read as off. + */ +export function switchValue(value: unknown, defaultValue: boolean): boolean | undefined { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + if (typeof value === 'boolean') { + return value; + } + const lowered = typeof value === 'string' ? value.toLowerCase() : ''; + return lowered === 'true' || lowered === 'false' ? lowered === 'true' : undefined; +} + +let reporting = false; + +/** + * Log a reference that leads back to a key being resolved, as the engine logs it. The logger reads + * its own settings here: a loop in one of those is met again while the line is written, and is + * logged once. + */ +function reportLoop(name: string): void { + if (reporting) { + return; + } + reporting = true; + try { + getLogger('mercury.config').warn(`Config loop for '${name}' detected`); + } finally { + reporting = false; + } +} + +/** The leaves of a document tree under their dotted keys; a float stays a `YamlFloat`, for its text. */ function flatten(prefix: string, node: unknown, out: Map): void { - if (node !== null && typeof node === 'object' && !Array.isArray(node)) { - for (const [k, v] of Object.entries(node as Record)) { - flatten(prefix ? `${prefix}.${k}` : k, v, out); + if (node instanceof Map) { + for (const [k, v] of node) { + const key = keyText(k); + flatten(prefix ? `${prefix}.${key}` : key, v, out); } } else { - out.set(prefix, node); + out.set(prefix, node instanceof YamlFloat ? node : plain(node)); } } @@ -140,9 +444,10 @@ export class AppConfig { private load(path: string): void { const text = fs.readFileSync(path, 'utf-8'); if (path.endsWith('.yml') || path.endsWith('.yaml')) { - const data = YAML.parse(text) ?? {}; + const tree = readYaml(text); const flat = new Map(); - flatten('', data, flat); + // a document that is not a mapping - an empty file, a list, a lone scalar - has no keys + flatten('', tree instanceof Map ? tree : new Map(), flat); this.store = flat; } else { this.store = parseProperties(text); @@ -157,23 +462,41 @@ export class AppConfig { this.overrides.set(key, value); } - get(key: string, defaultValue: unknown = undefined): unknown { - if (this.overrides.has(key)) { - const value = this.overrides.get(key); - // an override's value resolves references the way a file value does, so a credential - // may be given as -Dkey='${ENV_VAR}' and never appear in the process list - return typeof value === 'string' ? this.substitute(value, defaultValue) : value; + /** + * A key's value as it was given - an override first, then the file's; `MISSING` when neither + * carries the key, and when the one that does carries no value: a key written without one + * (`key:`, a YAML null) reads as a key that is not there, as in the Java engine, and an override + * set to null or undefined clears the key rather than uncovering the file's. + */ + private stored(key: string): unknown { + const value = this.overrides.has(key) ? this.overrides.get(key) : this.store.get(key); + return value ?? MISSING; + } + + /** A key's value with its references resolved, a float of the file still a `YamlFloat`. */ + private read(key: string, defaultValue: unknown): unknown { + const value = this.stored(key); + if (value === MISSING) { + return defaultValue; } - if (this.store.has(key)) { - const value = this.store.get(key); - return typeof value === 'string' ? this.substitute(value, defaultValue) : value; + if (typeof value !== 'string') { + return value; } - return defaultValue; + // an override's value resolves references the way a file value does, so a credential + // may be given as -Dkey='${ENV_VAR}' and never appear in the process list + const resolved = this.substitute(value, defaultValue, [key]); + // a value its references leave empty is no value, as in the Java engine - '${NAME:}' is the + // idiom for an optional setting; an empty text written as one (key: '') stays one + return resolved === '' && HAS_REF.test(value) ? defaultValue : resolved; + } + + get(key: string, defaultValue: unknown = undefined): unknown { + return unwrap(this.read(key, defaultValue)); } getProperty(key: string, defaultValue?: string): string | undefined { - const value = this.get(key, defaultValue); - return value === undefined || value === null ? undefined : asText(value); + const value = this.read(key, defaultValue); + return value === undefined || value === null ? undefined : propertyText(value); } /** @@ -182,38 +505,68 @@ export class AppConfig { * app-log-context.yaml). */ resolveText(value: string): unknown { - return this.substitute(value, undefined); + return unwrap(this.substitute(value, undefined, [])); + } + + /** + * A text value with its references resolved, as text - what `getProperty` returns for a key + * that holds it; undefined when the whole value is a reference that resolves to nothing (used + * for `rest.yaml`, whose values are text). + */ + resolveProperty(value: string): string | undefined { + const resolved = this.substitute(value, undefined, []); + return resolved === undefined || resolved === null ? undefined : propertyText(resolved); } exists(key: string): boolean { return this.overrides.has(key) || this.store.has(key); } - private substitute(value: string, defaultValue: unknown): unknown { + /** + * `value` with its references resolved; `seen` names the keys being resolved on the way here, + * which is how a reference that leads back to one of them is told. + */ + private substitute(value: string, defaultValue: unknown, seen: readonly string[]): unknown { const whole = WHOLE_REF.exec(value.trim()); if (whole) { - const resolved = this.resolveRef(whole[1]); + const resolved = this.resolveRef(whole[1], seen); return resolved === undefined ? defaultValue : resolved; } return value.replace(REF, (_m, ref: string) => { - const resolved = this.resolveRef(ref); - return resolved === undefined || resolved === null ? '' : asText(resolved); + const resolved = this.resolveRef(ref, seen); + return resolved === undefined || resolved === null ? '' : propertyText(resolved); }); } - private resolveRef(ref: string): unknown { + /** + * What `${name:default}` stands for, in the engine's order: the environment variable, then the + * key of that name as a key is read - an override before the file's value - then the default. A + * reference that leads back to a key being resolved is a loop: it is logged, as the engine logs + * it, and has no value, so its default stands. + */ + private resolveRef(ref: string, seen: readonly string[]): unknown { const idx = ref.indexOf(':'); const name = (idx === -1 ? ref : ref.slice(0, idx)).trim(); const fallback = idx === -1 ? undefined : ref.slice(idx + 1); - if (name in process.env) return process.env[name]; - if (this.store.has(name)) { - const base = this.store.get(name); - if (typeof base === 'string' && /\$\{[^}]+\}/.test(base)) { - return this.substitute(base, undefined); - } - return base; + // the environment's own variables only: `in` would also find what every object inherits + if (Object.hasOwn(process.env, name)) { + return process.env[name]; + } + const base = name ? this.stored(name) : MISSING; + if (base === MISSING) { + return fallback; + } + if (seen.includes(name)) { + reportLoop(name); + return fallback; + } + if (typeof base === 'string' && HAS_REF.test(base)) { + const resolved = this.substitute(base, undefined, [...seen, name]); + // a key its own references leave without a value, or empty, is read as a key is: it has + // none, so the default of the reference to it stands + return resolved === undefined || resolved === null || resolved === '' ? fallback : resolved; } - return fallback; + return base; } } diff --git a/src/envelope.ts b/src/envelope.ts index 053a4bf7..41b9670b 100644 --- a/src/envelope.ts +++ b/src/envelope.ts @@ -27,6 +27,21 @@ export function isoUtc(date?: Date): string { } /** Normalize a payload for the wire: Date -> ISO string, safe BigInt -> number. */ +/** + * Put a value into a map under a name that comes from outside - a query parameter, a form field, a + * cookie, a header. Defined, never assigned: a name every object carries (`__proto__`, + * `constructor`, `toString`) is then a key like any other, as it is in the Python twin, where an + * assignment would drop the first and find an inherited function under the others. + */ +export function put>(map: M, name: string, value: M[string]): void { + Object.defineProperty(map, name, { value, writable: true, enumerable: true, configurable: true }); +} + +/** What a map holds under a name of its own - never what every object inherits. */ +export function own(map: Record, name: string): T | undefined { + return Object.hasOwn(map, name) ? map[name] : undefined; +} + function sanitize(value: unknown): unknown { if (value instanceof Date) return isoUtc(value); if (typeof value === 'bigint') return value; // encodes exactly as int64 @@ -35,7 +50,7 @@ function sanitize(value: unknown): unknown { if (value !== null && typeof value === 'object') { const out: Record = {}; for (const [k, v] of Object.entries(value as Record)) { - if (v !== undefined) out[k] = sanitize(v); + if (v !== undefined) put(out, k, sanitize(v)); } return out; } @@ -53,7 +68,7 @@ function normalize(value: unknown): unknown { if (value !== null && typeof value === 'object') { const out: Record = {}; for (const [k, v] of Object.entries(value as Record)) { - out[k] = normalize(v); + put(out, k, normalize(v)); } return out; } @@ -77,7 +92,7 @@ function asStringMap(value: unknown): Record { const result: Record = {}; if (value !== null && typeof value === 'object' && !Array.isArray(value)) { for (const [k, v] of Object.entries(value as Record)) { - result[k] = asText(v); + put(result, k, asText(v)); } } return result; @@ -112,7 +127,7 @@ export class EventEnvelope { // fluent helpers mirroring the engine API vocabulary setTo(route: string): this { this.to = route; return this; } setFrom(route: string): this { this.sender = route; return this; } - setHeader(key: string, value: unknown): this { this.headers[key] = String(value); return this; } + setHeader(key: string, value: unknown): this { put(this.headers, key, String(value)); return this; } setBody(body: unknown): this { this.body = body; return this; } setStatus(status: number): this { this.status = Math.trunc(status); return this; } setCorrelationId(cid: string): this { this.cid = cid; return this; } diff --git a/src/event-stream.ts b/src/event-stream.ts index eea366e9..8fb3afba 100644 --- a/src/event-stream.ts +++ b/src/event-stream.ts @@ -28,7 +28,7 @@ */ import type * as http from 'node:http'; import { Mailbox, raceMs } from './bus.js'; -import { appConfig } from './config.js'; +import { appConfig, durationMs, MAX_TIMER_MS } from './config.js'; import { EventEnvelope } from './envelope.js'; import { AppException } from './exceptions.js'; import { getLogger } from './log.js'; @@ -166,28 +166,25 @@ export function dataFrame(event: EventEnvelope, firstFrame: boolean): Buffer { return sseFrame(streamEventName(event), event.body as string); } +// the engines' key of the keep-alive comment interval of a Server-Sent Events reply +const KEEP_ALIVE = 'event.stream.keep.alive'; + /** * SSE keep-alive comment interval in ms (`event.stream.keep.alive`, - * default 30s; 0 disables - the engines' config key). + * default 30s; 0 disables - the engines' config key): a whole number of + * seconds, or such a number and, right after it, one of `ms`, `s`, `m`, + * `h`, `d`, up to the longest delay a timer holds (2147483647 ms). The Java + * engine reads any other value as no keep-alive at all, without a word; here + * it is refused by name - and the host reads the setting when it starts, so + * a wrong one stops the start. */ export function keepAliveMs(): number { - const raw = String(appConfig().getProperty('event.stream.keep.alive', '30s') ?? '30s') - .trim().toLowerCase(); - if (raw === '0' || raw === '0s' || raw === '0ms' || raw === '0m') { - return 0; - } - const parse = (text: string): number => Number.parseInt(text, 10); - let value: number; - if (raw.endsWith('ms')) { - value = parse(raw.slice(0, -2)); - } else if (raw.endsWith('s')) { - value = parse(raw.slice(0, -1)) * 1000; - } else if (raw.endsWith('m')) { - value = parse(raw.slice(0, -1)) * 60_000; - } else { - value = parse(raw) * 1000; + const ms = durationMs(appConfig().get(KEEP_ALIVE) ?? '30s'); + if (ms === undefined || ms > MAX_TIMER_MS) { + throw new AppException(400, `${KEEP_ALIVE} must be a duration such as 30s, 2m or 500ms` + + ' (seconds, ms, s, m, h, d), or 0 for none'); } - return Number.isFinite(value) ? value : 30_000; + return ms; } /** The outcome of `nextSegment` when the client left before the next keep-alive comment could be written. */ diff --git a/src/index.ts b/src/index.ts index f4f8d58c..170e6726 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,7 +13,7 @@ export { AsyncHttpRequest } from './async-http-request.js'; export type { UploadedFile } from './async-http-request.js'; export { PostOffice } from './client.js'; export type { CallOptions } from './client.js'; -export { AppConfig, appConfig, loadConfig } from './config.js'; +export { AppConfig, appConfig, loadConfig, parseYaml, parseYamlAsText } from './config.js'; export { EventEnvelope, isoUtc } from './envelope.js'; export { DATA, diff --git a/src/log-context.ts b/src/log-context.ts index 84eebf3f..d5d5fb8f 100644 --- a/src/log-context.ts +++ b/src/log-context.ts @@ -13,7 +13,11 @@ * in the resources folder (next to application.yml), mapping each output * key to a reserved `$token` - resolved live per log line - or a constant * (a literal, or `${ENV:default}` resolved once at load). - * - `app.log.context=false` opts out. + * - `app.log.context=false` opts out; the switch is `true` or `false`, and any + * other value stops the start by name. + * - The template is read as every YAML file of the pack is (YAML 1.2.2's core + * schema), and a constant that is not text is the text a setting reads: a + * boolean `true` or `false`, a float with its point. * - The `cid` token is the BUSINESS correlation-id only (the engine-managed * my_cid tag); an internal routing id under the `cid` label would mislead * log aggregation. @@ -23,9 +27,10 @@ import { existsSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { parse } from 'yaml'; -import { appConfig } from './config.js'; -import { isoUtc } from './envelope.js'; +import { appConfig, parseYamlAsText, switchValue } from './config.js'; +import type { AppConfig } from './config.js'; +import { asText, isoUtc } from './envelope.js'; +import { AppException } from './exceptions.js'; import { getLogger } from './log.js'; import { RESERVED_CONTEXT_TOKENS, TraceInfo } from './trace.js'; @@ -51,7 +56,7 @@ function defaultTemplate(): Record | undefined { if (!existsSync(candidate)) { return undefined; } - return contextSection(parse(readFileSync(candidate, 'utf-8')) ?? {}); + return contextSection(parseYamlAsText(readFileSync(candidate, 'utf-8')) ?? {}); } /** Resolve a reserved token to its live value (undefined when absent). */ @@ -76,7 +81,11 @@ export class LogContextConfig { constructor(template: Record | undefined) { for (const [outputKey, raw] of Object.entries(template ?? {})) { - this.parseEntry(outputKey, typeof raw === 'string' ? raw : String(raw)); + // an entry without a value is dropped, as the engines drop it; one that is not text is + // the text a setting reads, the same in both packs + if (raw !== undefined && raw !== null) { + this.parseEntry(outputKey, asText(raw)); + } } this.enabled = Object.keys(this.tokens).length > 0 || Object.keys(this.constants).length > 0; @@ -127,6 +136,20 @@ export class LogContextConfig { } } +/** + * `app.log.context` is on unless it says `false`: the boolean, or the text `true` or `false` in + * any letter case; no value and an empty one are on, the engines' default. The Java engine reads + * any other value as on without a word; here it stops the start, by name - the host reads the + * switch when it is built. + */ +export function enabled(config: AppConfig): boolean { + const flag = switchValue(config.get(FEATURE_FLAG), true); + if (flag === undefined) { + throw new AppException(400, `${FEATURE_FLAG} must be true or false`); + } + return flag; +} + /** * Resolve the active template; never logs itself - the caller emits the * warning AFTER installing the config, so the log line (which renders through @@ -134,7 +157,7 @@ export class LogContextConfig { */ function load(): { config: LogContextConfig; warning?: string } { const config = appConfig(); - if ((config.getProperty(FEATURE_FLAG, 'true') ?? 'true').toLowerCase() === 'false') { + if (!enabled(config)) { return { config: new LogContextConfig(undefined) }; } // an application override replaces the default entirely - it sits in the same @@ -143,7 +166,7 @@ function load(): { config: LogContextConfig; warning?: string } { const folder = config.resourcesDir; const candidate = folder ? join(folder, CONFIG_FILE) : undefined; if (candidate && existsSync(candidate)) { - const section = contextSection(parse(readFileSync(candidate, 'utf-8')) ?? {}); + const section = contextSection(parseYamlAsText(readFileSync(candidate, 'utf-8')) ?? {}); if (!section) { // the engines log a warning and disable; mirror the outcome return { diff --git a/src/otel/export.ts b/src/otel/export.ts index b2581370..0dcce6a0 100644 --- a/src/otel/export.ts +++ b/src/otel/export.ts @@ -15,6 +15,7 @@ * bounded), and the rejections that actually happen get a hint. Request headers are * never rendered, so no credential can reach the log. */ +import { timerMs } from '../config.js'; import { getLogger } from '../log.js'; import { ENDPOINT, ForwarderSettings } from './config.js'; import { encodeExportRequest, partialSuccess } from './otlp.js'; @@ -110,7 +111,8 @@ export class Exporter { if (failure.retryable && attempt <= this.backoffMs.length) { log.debug(`OTLP export attempt ${attempt} for span ${hex(span.spanId)} failed ` + `(${failure.detail}) - retrying`); - await new Promise((resolve) => setTimeout(resolve, this.backoffMs[attempt - 1]).unref()); + const backoff = this.backoffMs[attempt - 1]; + await new Promise((resolve) => setTimeout(resolve, backoff).unref()); // NOSONAR - sequential: a retry waits out its backoff continue; } throw new ExportFailure(attempt, failure.detail); @@ -130,7 +132,7 @@ export class Exporter { try { response = await fetch(this.endpoint, { method: 'POST', headers, body: body as BodyInit, - signal: AbortSignal.timeout(this.timeoutMs) + signal: AbortSignal.timeout(timerMs(this.timeoutMs)) }); payload = new Uint8Array(await response.arrayBuffer()); } catch (e) { diff --git a/src/otel/index.ts b/src/otel/index.ts index dfcc40a6..6c993b2d 100644 --- a/src/otel/index.ts +++ b/src/otel/index.ts @@ -11,7 +11,9 @@ * OpenTelemetry Collector - so one trace spans the engines and the polyglot * functions they call. Off by default: the switch is the only thing that turns it on. */ +import { switchValue } from '../config.js'; import type { AppConfig } from '../config.js'; +import { AppException } from '../exceptions.js'; import { getLogger } from '../log.js'; import type { FunctionRegistry } from '../registry.js'; import { DISTRIBUTED_TRACE_FORWARDER } from '../trace.js'; @@ -52,10 +54,17 @@ export function forwarder(exporter: Exporter): (headers: Record, }; } -/** Whether `otel.forwarding` is switched on (the text `true`, case-insensitive). */ +/** + * Whether `otel.forwarding` is switched on: the boolean, or the text `true` or `false` in any + * letter case; no value and an empty one are off. Any other value was read as off without a word, + * which is how forwarding meant to be on stays off - so it stops the start, by name. + */ export function enabled(config: AppConfig): boolean { - const value = config.getProperty(FORWARDING_SWITCH); - return value?.trim().toLowerCase() === 'true'; + const flag = switchValue(config.get(FORWARDING_SWITCH), false); + if (flag === undefined) { + throw new AppException(400, `${FORWARDING_SWITCH} must be true or false`); + } + return flag; } /** @@ -63,7 +72,7 @@ export function enabled(config: AppConfig): boolean { * `otel.forwarding=true` - the host's start-up hook. Returns the exporter, or * undefined when forwarding is off or a function already occupies the route (an * application's own forwarder wins, as in the engines). A misconfigured endpoint - * fails the start. + * fails the start, and so does a switch that is neither true nor false. */ export function activate(config: AppConfig, registry: FunctionRegistry): Exporter | undefined { if (!enabled(config)) return undefined; diff --git a/src/rest-automation.ts b/src/rest-automation.ts index 77df6374..f9d59707 100644 --- a/src/rest-automation.ts +++ b/src/rest-automation.ts @@ -31,18 +31,18 @@ * under the `static-content` rules - the `no-cache-pages` headers and the `filter` function. * * Off by default: with the switch off, the host is exactly what it was. No framework and no new - * dependency: the edge is `node:http`, and a multipart body is parsed by the runtime's own `Response`. + * dependency: the edge is `node:http`, and a multipart body is read by the pack's own reader + * (`parseUpload`), as the Python twin reads it. */ import { randomBytes, randomUUID } from 'node:crypto'; import * as fs from 'node:fs'; import * as http from 'node:http'; import { isAbsolute, join } from 'node:path'; -import { MIMEType } from 'node:util'; import { appOrigin } from './actuator.js'; import { AsyncHttpRequest, UploadedFile } from './async-http-request.js'; import { DeliveryTimeout, EventBus, Mailbox, raceMs, roundTripRecord } from './bus.js'; -import { AppConfig } from './config.js'; -import { EventEnvelope, isoUtc } from './envelope.js'; +import { AppConfig, parseYaml, switchValue, wholeNumber } from './config.js'; +import { EventEnvelope, isoUtc, own, put } from './envelope.js'; import { CLIENT_GONE, DATA, @@ -73,7 +73,7 @@ import { parseBody, parseCookies, parseQuery, - parseYaml, + parseUpload, ParsedBody, prettyJson, QueryValues, @@ -97,20 +97,19 @@ export const TRACEPARENT_HEADER = 'http.traceparent.header'; export const DEFAULT_TRACE_ID_HEADER = 'X-Trace-Id'; export const DEFAULT_CORRELATION_ID_HEADER = 'X-Correlation-Id'; const TRACEPARENT = 'traceparent'; +// the one header name the server's own map of a request's headers cannot hold +const PROTO = '__proto__'; // the bound on the files of one upload, all of them together (the pack's bounded form of the // engines' streaming upload) export const UPLOAD_MAX_BYTES = 'rest.upload.max.bytes'; export const DEFAULT_UPLOAD_MAX_BYTES = 16 * 1024 * 1024; -// what the parts' boundaries and headers may add to a multipart body beyond the files it carries: -// a body past the bound plus this is refused before it is parsed, so the memory a request takes -// stays bounded as it is in the Python pack's part-by-part reading +// what an upload's body may take on the wire beyond the parts' contents - its delimiters and the +// parts' headers - before it is refused unread const MULTIPART_HEADROOM = 1024 * 1024; const MULTIPART_FORM_DATA = 'multipart/form-data'; // the host's limit on a request body it reads into memory - the Python pack's client_max_size export const MAX_BODY_BYTES = 16 * 1024 * 1024; -// an upload's parts are text fields and files: the refusal of a part that is multipart itself -const NESTED_PART = 'Upload takes text fields and files, not a nested multipart part'; -// the answer when a reply cannot be rendered - a body the serializer refuses +// the answer when a reply cannot be rendered - a body a serializer refuses, JSON's or the wire codec's const UNRENDERABLE = 'Reply cannot be rendered'; // the edge's own service name in the trace records (the engines' REST edge) export const HTTP_REQUEST = 'http.request'; @@ -130,10 +129,17 @@ const HEX = /^[0-9A-Fa-f]{2}$/; // Python pack's edge receives its query string this way (yarl's decoding) const STRUCTURAL = new Set(['26', '3D', '2B']); -/** `rest.automation` is on - a boolean or the text `true`. */ +/** + * `rest.automation` is on: the boolean, or the text `true` or `false` in any letter case; no value + * and an empty one are off. The Java engine reads any other value as off without a word, which is + * how a switch meant to be on stays off - so here it stops the start, by name. + */ export function enabled(config: AppConfig): boolean { - const value = config.get(REST_AUTOMATION, false); - return value === true || (typeof value === 'string' && value.trim().toLowerCase() === 'true'); + const on = switchValue(config.get(REST_AUTOMATION), false); + if (on === undefined) { + throw new AppException(400, `${REST_AUTOMATION} must be true or false`); + } + return on; } /** @@ -190,7 +196,7 @@ export function loadTable(config: AppConfig): RoutingTable { if (data === null || data === undefined) { log.warn(`REST automation configuration is empty - ${path} (the default endpoints only)`); } else { - table = RoutingTable.load(substituteValues(data, (value) => config.resolveText(value))); + table = RoutingTable.load(substituteValues(data, (value) => config.resolveProperty(value))); log.info(`Loading REST automation from ${path}`); } } @@ -246,7 +252,7 @@ export function restError(res: http.ServerResponse, status: number, message: str * structure that contains itself. The reason goes to the log; the response and the trace record * carry the one message both packs answer. */ -function unrendered(service: string | undefined, cause: unknown): AppException { +export function unrendered(service: string | undefined, cause: unknown): AppException { const reason = cause instanceof Error ? cause.message : String(cause); log.error(`Unable to render the reply of ${service || 'unknown'} - ${reason}`); return new AppException(500, UNRENDERABLE); @@ -282,7 +288,7 @@ function chunkBytes(body: unknown): Buffer { * content type and the idle allowance - the entry's timeout, or the head's `x-ttl` in seconds. The * stream's own markers never reach the wire. */ -function streamHead(first: EventEnvelope, timeoutMs: number): +export function streamHead(first: EventEnvelope, timeoutMs: number): { headers: Record; cookies: string[]; contentType: string | undefined; idleMs: number } { const headers: Record = {}; const cookies: string[] = []; @@ -294,8 +300,8 @@ function streamHead(first: EventEnvelope, timeoutMs: number): continue; } if (key === X_TTL) { - const seconds = Number.parseInt(value.trim(), 10); - if (Number.isFinite(seconds) && seconds > 0) { + const seconds = wholeNumber(value); + if (seconds) { idleMs = seconds * 1000; } } else if (key === 'content-type') { @@ -303,7 +309,7 @@ function streamHead(first: EventEnvelope, timeoutMs: number): } else if (key === 'set-cookie') { cookies.push(...value.split('|').map((c) => c.trim()).filter((c) => c.length > 0)); } else { - headers[key] = value; + put(headers, key, value); } } return { headers, cookies, contentType, idleMs }; @@ -428,9 +434,16 @@ function requestHeaders(req: http.IncomingMessage): Record { const headers: Record = {}; for (const [name, value] of Object.entries(req.headers)) { if (value !== undefined) { - headers[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : value; + put(headers, name.toLowerCase(), Array.isArray(value) ? value.join(', ') : value); } } + // the server assigns each header to its map, so one named __proto__ never gets there: it is + // taken from the lines as they arrived, joined as the server joins a repeated header + const lines = req.rawHeaders; + const dropped = lines.filter((_line, index) => index % 2 === 1 && lines[index - 1].toLowerCase() === PROTO); + if (dropped.length > 0) { + put(headers, PROTO, dropped.join(', ')); + } return headers; } @@ -465,57 +478,6 @@ export function readBody(req: http.IncomingMessage): Promise { return readWithin(req, MAX_BODY_BYTES, () => new AppException(413, `Request body exceeds ${MAX_BODY_BYTES} bytes`)); } -/** One part of a multipart body as it arrived: whether it is multipart itself, and the bytes of its content. */ -interface ArrivedPart { - nested: boolean; - size: number; -} - -/** True for a header line that declares a `multipart/*` content type - a part that is multipart itself. */ -function declaresMultipart(line: string): boolean { - const colon = line.indexOf(':'); - if (colon === -1 || line.slice(0, colon).trim().toLowerCase() !== 'content-type') { - return false; - } - const type = (baseContentType(line.slice(colon + 1)) ?? '').toLowerCase(); - return type === 'multipart' || type.startsWith('multipart/'); -} - -/** - * The parts of a multipart body the runtime has parsed, read off the same delimiters and so in - * the order of its entries. The runtime hands a part over as a text or a `File`; whether the part - * declared a `multipart/*` type, and how many bytes a text field arrived as, only the body tells. - */ -function arrivedParts(body: Buffer, contentType: string): ArrivedPart[] { - const boundary = Buffer.from(new MIMEType(contentType).params.get('boundary') ?? '', 'utf-8'); - const delimiter = Buffer.concat([Buffer.from('--'), boundary]); - const parts: ArrivedPart[] = []; - let at = body.indexOf(delimiter); - while (at !== -1) { - // after a delimiter, two more dashes close the body and a line end opens a part - at += delimiter.length; - if (body.toString('latin1', at, at + 2) === '--') { - break; - } - // the header lines, up to the empty one - at += 2; - let nested = false; - for (let end = body.indexOf('\r\n', at); end > at; end = body.indexOf('\r\n', at)) { - nested ||= declaresMultipart(body.toString('latin1', at, end)); - at = end + 2; - } - // the content, from the empty line to the line end and the dashes before the next boundary - at += 2; - const next = body.indexOf(boundary, at); - if (next === -1) { - break; - } - parts.push({ nested, size: next - 4 - at }); - at = next - 2; - } - return parts; -} - const uuidHex = (): string => randomUUID().replaceAll('-', ''); /** @@ -620,18 +582,11 @@ async function within(work: Promise, timeoutMs: number): Promise /** * The wait for a built-in service: the entry's timeout, unless the caller sent an `x-ttl` that is a - * number - then that many milliseconds, a second at least. + * whole number - then that many milliseconds, a second at least. */ function callerTtlMs(req: http.IncomingMessage, timeoutMs: number): number { - let ttlMs = timeoutMs; - const header = req.headers[X_TTL]; - if (header !== undefined) { - const sent = Number.parseInt(String(header).trim(), 10); - if (Number.isFinite(sent)) { - ttlMs = Math.max(1000, sent); - } - } - return ttlMs; + const sent = wholeNumber(req.headers[X_TTL]); + return sent === undefined ? timeoutMs : Math.max(1000, sent); } /** @@ -698,8 +653,13 @@ export class RestAutomation { this.cidHeader = (config.getProperty(CORRELATION_ID_HEADER, DEFAULT_CORRELATION_ID_HEADER) || DEFAULT_CORRELATION_ID_HEADER).toLowerCase(); this.traceparentHeader = (config.getProperty(TRACEPARENT_HEADER, TRACEPARENT) || TRACEPARENT).toLowerCase(); - const bound = Number.parseInt(String(config.get(UPLOAD_MAX_BYTES, DEFAULT_UPLOAD_MAX_BYTES)), 10); - this.uploadMaxBytes = Number.isFinite(bound) ? bound : DEFAULT_UPLOAD_MAX_BYTES; + // a bound that is no whole number stops the start: a default taken in its place would be a + // bound the installation did not set + const bound = wholeNumber(config.get(UPLOAD_MAX_BYTES) ?? DEFAULT_UPLOAD_MAX_BYTES); + if (bound === undefined) { + throw new AppException(400, `${UPLOAD_MAX_BYTES} must be a whole number >= 0`); + } + this.uploadMaxBytes = bound; } /** The edge when `rest.automation` is on, else undefined. */ @@ -799,23 +759,35 @@ export class RestAutomation { const [traceId, parentSpan] = this.resolveTrace(info, headers, traceHeader); // a business correlation id is always ensured; one header name serving both roles yields one // id, not two - let cid = headers[cidHeader]; + // a header's name comes from the configuration here, and is read as any name from outside + let cid = own(headers, cidHeader); if (!cid) { cid = cidHeader === traceHeader && traceId ? traceId : uuidHex(); } - headers[cidHeader] = cid; + put(headers, cidHeader, cid); headers[X_TTL] ??= String(info.timeoutSeconds * 1000); const queryText = decodeQueryString(url.search.startsWith('?') ? url.search.slice(1) : url.search); const query = parseQuery(queryText); const cookies = parseCookies(headers.cookie); delete headers.cookie; const accept = headers.accept; - const { parsed, files, raw } = await this.readEntryBody(req, info, method, headers, query); + const tracePath = queryText ? `${method} ${path}?${queryText}` : `${method} ${path}`; + const edge = traceId ? new RestEdge(this.bus, traceId, tracePath, parentSpan) : undefined; + let read: { parsed: ParsedBody; files: UploadedFile[]; raw: Buffer }; + try { + read = await this.readEntryBody(req, info, method, headers, query); + } catch (e) { + // the engines' edge: a traced request is recorded once its trace is resolved, so a refusal + // raised while the body is read - a 400, a 413 - leaves its record + if (e instanceof AppException) { + edge?.record(e.status, e.message); + } + throw e; + } + const { parsed, files, raw } = read; const httpRequest = requestModel(req, info, { method, path, headers, pathParams: assigned.pathParams, query, queryText, cookies, parsed, files }); - const tracePath = queryText ? `${method} ${path}?${queryText}` : `${method} ${path}`; - const edge = traceId ? new RestEdge(this.bus, traceId, tracePath, parentSpan) : undefined; return { httpRequest, cid, cidHeader, traceId, tracePath, accept, edge, isHead: method === 'HEAD', raw }; } @@ -831,7 +803,7 @@ export class RestAutomation { if (traceparent === undefined) { const custom = (info.traceparentHeader ?? this.traceparentHeader).toLowerCase(); if (custom !== TRACEPARENT) { - traceparent = parseTraceparent(headers[custom]); + traceparent = parseTraceparent(own(headers, custom)); } } let traceId: string | undefined; @@ -839,7 +811,7 @@ export class RestAutomation { if (traceparent !== undefined) { [traceId, parentSpan] = traceparent; } else { - traceId = headers[traceHeader]; + traceId = own(headers, traceHeader); } traceId = info.tracing ? (traceId || uuidHex()) : undefined; return [traceId, parentSpan]; @@ -859,7 +831,7 @@ export class RestAutomation { // become query parameters, the body stays absent const read = await this.readMultipart(req); for (const [name, value] of Object.entries(read.fields)) { - query[name] = value; + put(query, name, value); } return { parsed: { kind: 'upload', value: null }, files: read.files, raw: Buffer.alloc(0) }; } @@ -867,63 +839,24 @@ export class RestAutomation { const parsed = parseBody(headers['content-type'], raw); if (parsed.kind === 'form') { for (const [name, value] of Object.entries(parsed.value as Record)) { - query[name] = value; + put(query, name, value); } } return { parsed, files: [], raw }; } /** - * The parts of a multipart body: a part with a filename is a file (its field name the upload tag, - * its declared type or octet-stream), any other part a text field; a part that is multipart itself - * is refused. The parts together, counted in bytes as they arrived, may not exceed - * `rest.upload.max.bytes` - a 413 the moment they do. + * The parts of a multipart body, read by the pack's own reader (`parseUpload`): a part with a + * filename is a file (its field name the upload tag, its declared type or octet-stream), any other + * part a text field; what a form does not send is refused by name. The parts together, counted in + * bytes as they arrived, may not exceed `rest.upload.max.bytes` - a 413; a body that outgrows the + * bound by more than its framing can take is refused while it arrives, the rest of it unread. */ private async readMultipart(req: http.IncomingMessage): Promise<{ files: UploadedFile[]; fields: Record }> { - const files: UploadedFile[] = []; - const fields: Record = {}; const bound = this.uploadMaxBytes; - const exceeded = (): AppException => new AppException(413, `Upload exceeds ${bound} bytes`); - const contentType = String(req.headers['content-type']); - const raw = await readWithin(req, bound + MULTIPART_HEADROOM, exceeded); - let form: FormData; - try { - form = await new Response(raw as BodyInit, { headers: { 'content-type': contentType } }).formData(); - } catch (e) { - throw new AppException(400, `Invalid multipart body - ${(e as Error).message ?? String(e)}`); - } - const entries = [...form.entries()]; - const arrived = arrivedParts(raw, contentType); - if (arrived.length !== entries.length) { - // the runtime read the parts off another boundary than the one the content type declares - throw new AppException(400, 'Invalid multipart body - its boundary is not the one the content type declares'); - } - let total = 0; - for (const [index, [name, value]] of entries.entries()) { - const part = arrived[index]; - if (part.nested) { - throw new AppException(400, NESTED_PART); - } - if (typeof value === 'string') { - // the bytes the field arrived as, never the length of the text they spell - total += part.size; - if (total > bound) { - throw exceeded(); - } - fields[name] = value; - continue; - } - const content = Buffer.from(await value.arrayBuffer()); // NOSONAR - sequential: the bound is a running total - total += content.length; - if (total > bound) { - throw exceeded(); - } - files.push({ - name: value.name, contentType: value.type || 'application/octet-stream', size: content.length, - tag: name || 'file', content - }); - } - return { files, fields }; + const raw = await readWithin(req, bound + MULTIPART_HEADROOM, + () => new AppException(413, `Upload exceeds ${bound} bytes`)); + return parseUpload(raw, req.headers['content-type'], bound); } /** @@ -1041,7 +974,7 @@ export class RestAutomation { for (const [name, value] of Object.entries(first.headers)) { const key = name.toLowerCase(); if (key !== X_EVENT_STREAM && key !== X_EVENT_NAME) { - kept[name] = value; + put(kept, name, value); } } first.headers = kept; @@ -1109,7 +1042,7 @@ export class RestAutomation { headers = info.headers.response.apply(headers); } if (!Object.keys(headers).some((name) => name.toLowerCase() === prepared.cidHeader)) { - headers[prepared.cidHeader] = prepared.cid; + put(headers, prepared.cidHeader, prepared.cid); } if (info.cors !== undefined) { for (const [name, value] of info.cors.headers) { @@ -1254,7 +1187,17 @@ export class RestAutomation { const filtered = await this.runFilter(req, url, service, path); Object.assign(extra, filtered.headers); if (filtered.getStatus() !== 200) { - const [kind, payload] = envelopePayload(filtered); + let kind: string | undefined; + let payload: Buffer; + try { + [kind, payload] = envelopePayload(filtered); + } catch (e) { + // the filter's own reply is the response, and it cannot be rendered: the answer any other + // such reply gets + const failure = unrendered(filter.service, e); + restError(res, failure.status, failure.message); + return true; + } for (const [name, value] of Object.entries(filtered.headers)) { res.setHeader(name, value); } diff --git a/src/rest-routing.ts b/src/rest-routing.ts index 820b3d2e..bfb4f3ce 100644 --- a/src/rest-routing.ts +++ b/src/rest-routing.ts @@ -16,18 +16,21 @@ * or `service: http.flow.adapter` - flows run in the engines), the HTTP relay (an `http(s)://` * service) and the A/B dual service (a list of two routes). `upload: true` is the pack's bounded form * of the engines' streaming upload: the files arrive in the request map, their bytes beside the - * engines' keys, within `rest.upload.max.bytes`. Deferred as in the Rust port: `custom.content.types`, - * `mime.types`, XML and request-body streaming. + * engines' keys, within `rest.upload.max.bytes` - the multipart body is read by `parseUpload`, the + * pack's own reader, so both packs take the same parts and refuse the same ones. Deferred as in the + * Rust port: `custom.content.types`, `mime.types`, XML and request-body streaming. */ -import YAML from 'yaml'; -import type { ScalarTag } from 'yaml'; -import { asText } from './envelope.js'; +import type { UploadedFile } from './async-http-request.js'; +import { durationMs, parseYaml, switchValue } from './config.js'; +import { asText, own, put } from './envelope.js'; import { AppException } from './exceptions.js'; export const ALLOWED_METHODS = ['GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'PATCH'] as const; export const DEFAULT_TIMEOUT_MS = 30_000; export const MIN_TIMEOUT_MS = 1_000; export const MAX_TIMEOUT_MS = 300_000; +// what an entry's timeout is, in the words of its refusal +const TIMEOUT_RULE = 'a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)'; export const FLOW_ADAPTER = 'http.flow.adapter'; // the engines' built-in default endpoints (platform-core's default-rest.yaml): merged only when the // application's rest.yaml does not already claim the URL - a user entry always wins @@ -64,6 +67,31 @@ rest: const PROTECTED_PREFIX = 'my_'; export const HTML_START = '
\n';
 export const HTML_END = '\n
'; +// ---- an upload's multipart body: what a browser's form sends, and the refusal of anything else ---- +// an upload's parts are text fields and files: the refusal of a part that is multipart itself +const NESTED_PART = 'Upload takes text fields and files, not a nested multipart part'; +// a boundary as RFC 2046 allows one: up to 70 of these characters, the last one not a space +const BOUNDARY = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; +// one parameter of a header - ; name="value" or ; name=value, no blank inside the name or beside +// the equals sign - and what may follow the last one +const PARAMETER = /[ \t]*;[ \t]*([^=;" \t]*)=(?:"([^"]*)"|([^;"]*))/y; +const PARAMETERS_END = /^[ \t]*(?:;[ \t]*)?$/; +// the three characters a form escapes in a field name and a filename +const ESCAPED = /%(22|0[AaDd])/g; +const UNESCAPED: Readonly> = { 22: '"', '0a': '\n', '0d': '\r' }; +// the charsets the extended form of a parameter may name (RFC 5987: name*, filename*), under +// their names in a refusal; and a run of the percent-encoded bytes of its value +const EXTENDED_CHARSETS: Readonly> = { 'utf-8': 'UTF-8', 'iso-8859-1': 'ISO-8859-1' }; +const PERCENT_BYTES = /(?:%[0-9A-Fa-f]{2})+/g; +// the transfer encodings that leave a part's bytes as they are +const PLAIN_TRANSFER: ReadonlySet = new Set(['7bit', '8bit', 'binary']); +// the charsets a text field may declare, under their names in a refusal +const FIELD_CHARSETS: Readonly> = { + 'utf-8': 'UTF-8', utf8: 'UTF-8', 'iso-8859-1': 'ISO-8859-1', 'us-ascii': 'US-ASCII' +}; +// text that is UTF-8 or the error thrown, a byte order mark kept as the character it is +const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); +const CRLF = Buffer.from('\r\n'); type Pair = [string, string]; @@ -78,49 +106,25 @@ function text(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; } -/** Python's int() over text: an optional sign and decimal digits, surrounding blanks allowed. */ -function integer(value: string): number | undefined { - const trimmed = value.trim(); - return /^[+-]?\d+$/.test(trimmed) ? Number.parseInt(trimmed, 10) : undefined; -} - /** - * A duration like `30s`, `2m`, `1500ms` or a bare number of seconds, in milliseconds; the default - * 30 s when unparsable, clamped to 1 s - 5 min (the engines' rule). + * An entry's `timeout` in milliseconds: a whole number of seconds, or such a number and, right + * after it, one of `ms`, `s`, `m`, `h`, `d` (`30s`, `2m`, `1500ms`), clamped to 1 s - 5 min as the + * engines clamp it; no value is the default 30 s. Undefined for a value that is no duration: the + * Java engine reads one as a second without a word, so here the entry is refused. */ -export function parseTimeout(value: unknown): number { - let parsed: number | undefined; - if (typeof value === 'boolean') { - parsed = undefined; - } else if (typeof value === 'number') { - parsed = Number.isFinite(value) ? Math.trunc(value) * 1000 : undefined; - } else if (typeof value === 'string') { - const lowered = value.trim().toLowerCase(); - let scale = 1000; - let digits = lowered; - if (lowered.endsWith('ms')) { - scale = 1; - digits = lowered.slice(0, -2); - } else if (lowered.endsWith('m')) { - scale = 60_000; - digits = lowered.slice(0, -1); - } else if (lowered.endsWith('s')) { - digits = lowered.slice(0, -1); - } - const number = integer(digits); - parsed = number === undefined ? undefined : number * scale; +export function parseTimeout(value: unknown): number | undefined { + if (value === undefined || value === null) { + return DEFAULT_TIMEOUT_MS; } - if (parsed === undefined || parsed < 0) { - parsed = DEFAULT_TIMEOUT_MS; - } - return Math.max(MIN_TIMEOUT_MS, Math.min(MAX_TIMEOUT_MS, parsed)); + const ms = durationMs(value); + return ms === undefined ? undefined : Math.max(MIN_TIMEOUT_MS, Math.min(MAX_TIMEOUT_MS, ms)); } function without(headers: Record, lowered: string): Record { const result: Record = {}; for (const [name, value] of Object.entries(headers)) { if (name.toLowerCase() !== lowered) { - result[name] = value; + put(result, name, value); } } return result; @@ -141,7 +145,7 @@ export class HeaderTransform { const filtered: Record = {}; for (const [name, value] of Object.entries(result)) { if (kept.has(name.toLowerCase())) { - filtered[name] = value; + put(filtered, name, value); } } result = filtered; @@ -152,7 +156,7 @@ export class HeaderTransform { } for (const [name, value] of this.add) { result = without(result, name.toLowerCase()); - result[name] = value; + put(result, name, value); } return result; } @@ -315,7 +319,7 @@ export class RouteInfo { return undefined; } } else if (kind === 'param') { - params[value] = actual; + put(params, value, actual); } } return params; @@ -548,24 +552,17 @@ function parseMethods(index: number, entry: Mapping): string[] { * fails the load, by the entry and the flag. */ function parseFlag(index: number, entry: Mapping, key: string): boolean { - const value = lookup(entry, key); - if (value === undefined || value === null || value === '') { - return false; - } - if (typeof value === 'boolean') { - return value; - } - const lowered = typeof value === 'string' ? value.toLowerCase() : ''; - if (lowered === 'true' || lowered === 'false') { - return lowered === 'true'; + const flag = switchValue(lookup(entry, key), false); + if (flag === undefined) { + throw new AppException(400, `rest[${index}] '${key}' must be true or false`); } - throw new AppException(400, `rest[${index}] '${key}' must be true or false`); + return flag; } /** * One `rest` entry. Its faults are reported in this order, the first one found failing the load: - * the service, the url, the methods, then the cors and the headers reference, then the flags - - * tracing, stream, upload. + * the service, the url, the methods, then the cors and the headers reference, then the timeout, + * then the flags - tracing, stream, upload. */ function parseRoute(index: number, entry: Mapping, corsBlocks: Map, headerBlocks: Map): RouteInfo { @@ -591,9 +588,13 @@ function parseRoute(index: number, entry: Mapping, corsBlocks: Map unkn if (isMapping(data)) { const out: Mapping = {}; for (const [key, value] of Object.entries(data)) { - out[key] = substituteValues(value, resolve); + put(out, key, substituteValues(value, resolve)); } return out; } return data; } -const BOOLEAN_TAG = 'tag:yaml.org,2002:bool'; - -/** A boolean as PyYAML resolves one: the words that spell `value`. */ -const booleanTag = (value: boolean, words: RegExp): ScalarTag => ({ - identify: (found) => found === value, default: true, tag: BOOLEAN_TAG, test: words, resolve: () => value -}); - -// PyYAML's booleans - and SnakeYAML's, the Java engine's reader: yes and no, true and false, on and -// off. The YAML 1.1 specification also reads the single letters y and n as booleans; to those two -// readers they are text, so they are text here -const PYYAML_BOOLEANS = [ - booleanTag(true, /^(?:yes|Yes|YES|true|True|TRUE|on|On|ON)$/), - booleanTag(false, /^(?:no|No|NO|false|False|FALSE|off|Off|OFF)$/) -]; - -/** A YAML text as the Python pack's `yaml.safe_load` reads it: an empty document is null. */ -export function parseYaml(yamlText: string): unknown { - // YAML 1.1 (yes/no/on/off are booleans, as PyYAML reads them) with duplicate keys tolerated, the - // last winning - so an engine's rest.yaml reads here as it reads in the Python pack - return YAML.parse(yamlText, { - version: '1.1', - uniqueKeys: false, - customTags: (tags) => [ - ...tags.filter((tag) => typeof tag === 'string' || tag.tag !== BOOLEAN_TAG), ...PYYAML_BOOLEANS - ] - }); -} - const pathSegments = (path: string): string[] => path.split('/').filter((s) => s.length > 0); /** The parsed routing table (the engines' `RoutingEntry`). */ @@ -797,13 +770,13 @@ export function parseQuery(queryText: string): QueryValues { const [rawName, , rawValue] = partition(pair, '='); const name = urlDecode(rawName); const value = urlDecode(rawValue); - const existing = query[name]; + const existing = own(query, name); if (existing === undefined) { - query[name] = value; + put(query, name, value); } else if (Array.isArray(existing)) { existing.push(value); } else { - query[name] = [existing, value]; + put(query, name, [existing, value]); } } return query; @@ -817,7 +790,7 @@ export function parseCookies(header: string | undefined): Record for (const item of header.split(';')) { const [name, found, value] = partition(item, '='); if (found) { - cookies[name.trim()] = value.trim(); + put(cookies, name.trim(), value.trim()); } } return cookies; @@ -831,6 +804,301 @@ export function baseContentType(contentType: string | undefined): string | undef return partition(contentType, ';')[0].trim(); } +const invalidUpload = (reason: string): AppException => new AppException(400, `Invalid multipart body - ${reason}`); + +const isBlank = (character: string): boolean => character === ' ' || character === '\t'; + +/** Text without the blanks - spaces and tabs - around it. */ +function trimBlanks(text: string): string { + let start = 0; + let end = text.length; + while (start < end && isBlank(text[start])) { + start += 1; + } + while (end > start && isBlank(text[end - 1])) { + end -= 1; + } + return text.slice(start, end); +} + +/** + * The parameters of a header after its first value - `; name="a"; filename=b` - under their names + * in lower case, the first of a name standing: a value in double quotes runs to the next one, a + * bare value to the next semicolon. Undefined when the text is anything else. + */ +function parameters(text: string): Map | undefined { + const found = new Map(); + let at = 0; + for (;;) { + PARAMETER.lastIndex = at; + const match = PARAMETER.exec(text); + if (match === null) { + break; + } + const name = match[1].toLowerCase(); + if (!found.has(name)) { + found.set(name, match[2] ?? trimBlanks(match[3])); + } + at = PARAMETER.lastIndex; + } + return PARAMETERS_END.test(text.slice(at)) ? found : undefined; +} + +/** + * A part's header as its first value, in lower case, and its parameters; a header the part does + * not carry is an empty value without parameters. + */ +function headerParameters(headers: Map, name: string): [string, Map] { + const [first, found, rest] = partition(headers.get(name) ?? '', ';'); + const params = parameters(found ? `;${rest}` : ''); + if (params === undefined) { + throw invalidUpload("a part's header parameters are malformed"); + } + return [trimBlanks(first).toLowerCase(), params]; +} + +/** The boundary the request's content type declares, as the bytes the body is delimited by. */ +function boundaryOf(contentType: string | undefined): Buffer { + const [, found, rest] = partition(contentType ?? '', ';'); + const boundary = parameters(found ? `;${rest}` : '')?.get('boundary') ?? ''; + if (!BOUNDARY.test(boundary)) { + throw invalidUpload('the content type declares no boundary'); + } + return Buffer.from(boundary, 'latin1'); +} + +/** + * Where the first delimiter starts: at the first byte, or on a line of its own after a preamble, + * which is ignored. + */ +function firstDelimiter(body: Buffer, delimiter: Buffer): number { + if (body.subarray(0, delimiter.length).equals(delimiter)) { + return 0; + } + const at = body.indexOf(Buffer.concat([CRLF, delimiter])); + if (at === -1) { + throw invalidUpload('no part is delimited by the boundary the content type declares'); + } + return at + 2; +} + +/** + * Where the part after a delimiter starts - past blanks and the line end - or -1 when the delimiter + * is the closing one, with two dashes after it; what follows that is ignored. + */ +function afterDelimiter(body: Buffer, start: number): number { + let at = start; + if (body.toString('latin1', at, at + 2) === '--') { + return -1; + } + while (body[at] === 0x20 || body[at] === 0x09) { + at += 1; + } + if (body.toString('latin1', at, at + 2) !== '\r\n') { + throw invalidUpload('a delimiter is followed by neither a line end nor the closing dashes'); + } + return at + 2; +} + +/** + * A part's header lines under their names in lower case, the first of a name standing, and where + * its content starts - after the empty line. + */ +function partHeaders(body: Buffer, start: number): [Map, number] { + const headers = new Map(); + let at = start; + for (;;) { + const end = body.indexOf(CRLF, at); + if (end === -1) { + throw invalidUpload('the closing delimiter is missing'); + } + if (end === at) { + return [headers, end + 2]; + } + let line: string; + try { + line = UTF8.decode(body.subarray(at, end)); + } catch { + throw invalidUpload("a part's headers are not UTF-8"); + } + const [name, found, value] = partition(line, ':'); + if (!found) { + throw invalidUpload("a part's header line is not 'name: value'"); + } + const key = trimBlanks(name).toLowerCase(); + if (!headers.has(key)) { + headers.set(key, trimBlanks(value)); + } + at = end + 2; + } +} + +/** + * A field name or a filename as the form spelt it: a double quote, a line feed and a carriage + * return arrive as `%22`, `%0A` and `%0D`. + */ +const unescapeName = (text: string): string => + text.replace(ESCAPED, (_m, code: string) => UNESCAPED[code.toLowerCase()]); + +/** + * A part's field name and, for a file, its filename - after the part is held against what an upload + * takes: no part that is multipart itself, a `form-data` disposition with a `name`, and bytes that + * arrive as they are. + */ +function partNames(headers: Map): [string, string | undefined] { + const declared = (baseContentType(headers.get('content-type')) ?? '').toLowerCase(); + if (declared === 'multipart' || declared.startsWith('multipart/')) { + throw new AppException(400, NESTED_PART); + } + const [disposition, params] = headerParameters(headers, 'content-disposition'); + const name = named(params, 'name'); + if (disposition !== 'form-data' || name === undefined) { + throw invalidUpload("a part is not 'Content-Disposition: form-data' with a name"); + } + const transfer = headers.get('content-transfer-encoding'); + if (transfer !== undefined && !PLAIN_TRANSFER.has(transfer.toLowerCase())) { + throw new AppException(400, 'Upload takes the bytes of a part as they are, not a' + + ` Content-Transfer-Encoding of '${transfer}'`); + } + const encoding = headers.get('content-encoding'); + if (encoding !== undefined && encoding.toLowerCase() !== 'identity') { + throw new AppException(400, 'Upload takes the bytes of a part as they are, not a' + + ` Content-Encoding of '${encoding}'`); + } + return [name, named(params, 'filename')]; +} + +/** Bytes as text in a charset a text field may declare; undefined when they are not that text. */ +function decodeField(content: Buffer, charset: string): string | undefined { + if (charset === 'ISO-8859-1') { + return content.toString('latin1'); + } + if (charset === 'US-ASCII') { + return content.every((byte) => byte < 0x80) ? content.toString('latin1') : undefined; + } + try { + return UTF8.decode(content); + } catch { + return undefined; + } +} + +/** + * A parameter in the extended form of RFC 5987 (`name*`, `filename*`) as text - what a client + * writes for a name that is not ASCII: `charset'language'value`, the charset UTF-8 or ISO-8859-1 + * in any letter case, the language passed over, and the value's bytes percent-encoded, any other + * character standing for itself. + */ +function extendedText(key: string, value: string): string { + const first = value.indexOf("'"); + const second = first === -1 ? -1 : value.indexOf("'", first + 1); + if (second === -1) { + throw invalidUpload(`a part's ${key} is not charset'language'value`); + } + const declared = value.slice(0, first); + const lowered = declared.toLowerCase(); + const charset = Object.hasOwn(EXTENDED_CHARSETS, lowered) ? EXTENDED_CHARSETS[lowered] : undefined; + if (charset === undefined) { + throw new AppException(400, `Upload takes a part's ${key} in UTF-8 or ISO-8859-1, not in '${declared}'`); + } + const encoded = value.slice(second + 1); + if (encoded.replace(PERCENT_BYTES, '').includes('%')) { + throw invalidUpload(`a part's ${key} holds a % that two hexadecimal digits do not follow`); + } + let asDeclared = true; + const text = encoded.replace(PERCENT_BYTES, (run) => { + const decoded = decodeField(Buffer.from(run.replaceAll('%', ''), 'hex'), charset); + asDeclared &&= decoded !== undefined; + return decoded ?? ''; + }); + if (!asDeclared) { + throw new AppException(400, `Upload parameter ${key} of a part is not ${charset}`); + } + return text; +} + +/** + * A part's `name` or `filename`: the extended parameter when the part carries one - it wins over + * the plain one, wherever it stands - else the plain one as the form spelt it; undefined when the + * part carries neither. + */ +function named(params: Map, key: string): string | undefined { + const extended = params.get(`${key}*`); + if (extended !== undefined) { + return extendedText(`${key}*`, extended); + } + const plain = params.get(key); + return plain === undefined ? undefined : unescapeName(plain); +} + +/** A text field's bytes as text: UTF-8, unless the part declares ISO-8859-1 or US-ASCII. */ +function fieldText(name: string, headers: Map, content: Buffer): string { + const declared = headerParameters(headers, 'content-type')[1].get('charset') ?? 'utf-8'; + const lowered = declared.toLowerCase(); + const charset = Object.hasOwn(FIELD_CHARSETS, lowered) ? FIELD_CHARSETS[lowered] : undefined; + if (charset === undefined) { + throw new AppException(400, `Upload takes a text field in UTF-8, ISO-8859-1 or US-ASCII, not in '${declared}'`); + } + const text = decodeField(content, charset); + if (text === undefined) { + throw new AppException(400, `Upload text field '${name}' is not ${charset}`); + } + return text; +} + +/** + * The files and the text fields of a `multipart/form-data` body, read as a browser's form sends + * one and the same way in both packs. The body is delimited by the boundary its content type + * declares, with `\r\n` line ends; a part is `Content-Disposition: form-data` with a `name` and, for + * a file, a `filename` (an empty one included: a file input left empty) - in quotes, where `%22`, + * `%0A` and `%0D` stand for a quote and the two line ends, or bare, or in the extended form a + * client writes for a name that is not ASCII (`filename*=UTF-8''...`, `name*`), which wins over + * the plain one. A file's type is its + * `Content-Type` as written, `application/octet-stream` without one; its bytes are the bytes that + * arrived. A text field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares; a later field of + * a name replaces an earlier one. The parts' contents together, counted in bytes in the order they + * arrive, may not exceed `bound` - a 413. Anything else is a 400 that names it: a part that is + * multipart itself, a part without a name, an extended parameter that is malformed, in another + * charset or not the text it declares, a transfer or content encoding that changes the bytes, a + * field in another charset or one that is not the text it declares, a body that is not delimited + * as declared. + */ +export function parseUpload(body: Buffer, contentType: string | undefined, + bound: number): { files: UploadedFile[]; fields: Record } { + const delimiter = Buffer.concat([Buffer.from('--'), boundaryOf(contentType)]); + const closing = Buffer.concat([CRLF, delimiter]); + const files: UploadedFile[] = []; + const fields: Record = {}; + let total = 0; + let at = firstDelimiter(body, delimiter); + for (;;) { + at = afterDelimiter(body, at + delimiter.length); + if (at === -1) { + return { files, fields }; + } + const [headers, start] = partHeaders(body, at); + const [name, filename] = partNames(headers); + const end = body.indexOf(closing, start); + if (end === -1) { + throw invalidUpload('the closing delimiter is missing'); + } + const content = body.subarray(start, end); + total += content.length; + if (total > bound) { + throw new AppException(413, `Upload exceeds ${bound} bytes`); + } + if (filename === undefined) { + put(fields, name, fieldText(name, headers, content)); + } else { + files.push({ + name: filename, contentType: headers.get('content-type') || 'application/octet-stream', + size: content.length, tag: name || 'file', content + }); + } + at = end + 2; + } +} + /** * The request body by its declared content type: `value` (a map, a list, text or null), `form` * (fields that become query parameters) or `bytes`. @@ -868,7 +1136,7 @@ export function parseBody(contentType: string | undefined, data: Buffer): Parsed const fields: Record = {}; for (const pair of data.toString('utf-8').split('&').filter((p) => p.length > 0)) { const [name, , value] = partition(pair, '='); - fields[urlDecode(name)] = urlDecode(value); + put(fields, urlDecode(name), urlDecode(value)); } return { kind: 'form', value: fields }; } @@ -925,7 +1193,7 @@ export function stripNulls(value: unknown): unknown { const out: Mapping = {}; for (const [key, item] of Object.entries(value)) { if (item !== null && item !== undefined) { - out[key] = stripNulls(item); + put(out, key, stripNulls(item)); } } return out; @@ -1048,7 +1316,7 @@ function splitReplyHeaders(replyHeaders: Record, isHead: boolean } else if (key === 'set-cookie') { cookies.push(...value.split('|').map((c) => c.trim())); } else { - headers[key] = value; + put(headers, key, value); } } return { contentType, cookies, headers }; @@ -1067,7 +1335,7 @@ function wireHeaders(functionHeaders: Record, contentType: strin headers = transform.apply(headers); } if (!Object.keys(headers).some((name) => name.toLowerCase() === cidHeader)) { - headers[cidHeader] = cid; + put(headers, cidHeader, cid); } if (contentType !== undefined) { headers['content-type'] = contentType; diff --git a/src/server.ts b/src/server.ts index 3aef5ecd..ac45eb05 100644 --- a/src/server.ts +++ b/src/server.ts @@ -30,8 +30,8 @@ import { randomBytes } from 'node:crypto'; import * as http from 'node:http'; import { Actuator, appOrigin, sendError } from './actuator.js'; import { DeliveryTimeout, EventBus, Mailbox, raceMs, roundTripRecord, TraceFields } from './bus.js'; -import { appConfig } from './config.js'; -import { EventEnvelope, isoUtc } from './envelope.js'; +import { AppConfig, appConfig, wholeNumber } from './config.js'; +import { EventEnvelope, isoUtc, put } from './envelope.js'; import { resolveFolder, StaticContent } from './static-content.js'; import { DATA, @@ -51,14 +51,17 @@ import { } from './event-stream.js'; import { AppException } from './exceptions.js'; import { getLogger } from './log.js'; +import { enabled as logContextEnabled } from './log-context.js'; import { activate as activateOtelForwarder } from './otel/index.js'; import { defaultRegistry, FunctionRegistry, ServiceDef } from './registry.js'; -import { readBody, RestAutomation, restError } from './rest-automation.js'; +import { readBody, RestAutomation, restError, unrendered } from './rest-automation.js'; import { MY_CID_TAG, MY_CORRELATION_ID } from './trace.js'; const OCTET_STREAM = 'application/octet-stream'; // the engines' reserved route name for the Event-over-HTTP ingress const EVENT_API_SERVICE = 'event.api.service'; +const SERVER_PORT = 'rest.server.port'; +const DEFAULT_PORT = 8085; // the edge's own service name and path in its round-trip record (the engines' REST edge) const HTTP_REQUEST = 'http.request'; const EDGE_PATH = 'POST /api/event'; @@ -79,6 +82,40 @@ function transportError(res: http.ServerResponse, status: number, message: strin res.end(bytes); } +/** + * A single-shot reply written as the HTTP 200 that carries its envelope; returns the status and the + * error for the edge's record. A reply the wire codec refuses - a type MsgPack does not hold - is + * answered as any other reply that cannot be rendered: a 500, here an envelope as every transport + * failure of this endpoint is. + */ +function relay(res: http.ServerResponse, route: string | undefined, + reply: EventEnvelope): [number, string | undefined] { + let bytes: Uint8Array; + try { + bytes = reply.toBytes(); + } catch (e) { + const failure = unrendered(route, e); + transportError(res, failure.status, failure.message); + return [failure.status, failure.message]; + } + res.writeHead(200, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); + res.end(bytes); + return [200, undefined]; +} + +/** + * The port `rest.server.port` names (8085 without one): a whole number up to 65535, 0 for one the + * system picks. The Java engine starts no server for a value it cannot read, without a word; here + * such a value stops the start, by name. + */ +export function serverPort(config: AppConfig): number { + const port = wholeNumber(config.get(SERVER_PORT) ?? DEFAULT_PORT); + if (port === undefined || port > 65535) { + throw new AppException(400, `${SERVER_PORT} must be a port number from 0 to 65535`); + } + return port; +} + /** The request body as an envelope; a body the codec rejects is answered with the 400 and yields undefined. */ function decodeEvent(res: http.ServerResponse, raw: Buffer): EventEnvelope | undefined { try { @@ -111,7 +148,7 @@ function handlerHeaders(event: EventEnvelope): Record { for (const [k, v] of Object.entries(event.headers)) { const key = k.toLowerCase(); if (key !== 'x-event-api' && !key.startsWith('my_')) { - headers[k] = v; + put(headers, k, v); } } const myCid = event.tags[MY_CID_TAG]; @@ -219,6 +256,10 @@ export class EventApiServer { // REST automation (rest.automation=true): the routing table of rest.yaml, loaded at // construction so a misconfigured entry fails the start, never a request this.rest = RestAutomation.load(appConfig(), this); + // read here for the same reason: a keep-alive that is no duration stops the start, and so + // does a log context switch that is neither true nor false + keepAliveMs(); + logContextEnabled(appConfig()); } /** @@ -227,7 +268,8 @@ export class EventApiServer { */ async handleEvent(req: http.IncomingMessage, res: http.ServerResponse, raw: Buffer): Promise { - const ttl = Math.max(1000, Number.parseInt(String(req.headers['x-ttl'] ?? '0'), 10) || 0); + // a value that is no whole number counts as none + const ttl = Math.max(1000, wholeNumber(req.headers[X_TTL]) ?? 0); const isAsync = req.headers['x-async'] === 'true'; const event = decodeEvent(res, raw); if (!event) { @@ -295,12 +337,11 @@ export class EventApiServer { const reply = await this.registry.bus.deliver(service, headers, event.body, ttl, trace); log.info(`Handled ${event.to} status=${reply.getStatus()} ` + `exec_time=${reply.execTime}ms trace_id=${event.traceId ?? 'none'}`); - const bytes = reply.toBytes(); - res.writeHead(200, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); - res.end(bytes); + const [status, error] = relay(res, event.to, reply); if (edge) { + // the function answered - its own record stands whatever becomes of the reply edge.recordFunction(event.sender, reply, dispatched, started); - edge.recordEdge(200); + edge.recordEdge(status, error); } } catch (e) { if (e instanceof DeliveryTimeout) { @@ -367,10 +408,8 @@ export class EventApiServer { // contract for an uncaught interceptor exception) log.info(`Handled ${event.to} status=${first.getStatus()} ` + `exec_time=${first.execTime ?? 0}ms trace_id=${event.traceId ?? 'none'}`); - const bytes = first.toBytes(); - res.writeHead(200, { 'content-type': OCTET_STREAM, 'content-length': bytes.length }); - res.end(bytes); - edge?.recordEdge(200); + const [status, error] = relay(res, event.to, first); + edge?.recordEdge(status, error); return; } if (!capable) { @@ -379,7 +418,17 @@ export class EventApiServer { transportError(res, 406, STREAM_CALLER_REQUIRED); return; } - const status = await streamResponse(res, queue, first, marker, ttl); + let head: Buffer; + try { + head = envelopeFrame(first); + } catch (e) { + // a head the wire codec refuses, before anything is sent: the single-shot answer + const failure = unrendered(event.to, e); + edge?.recordEdge(failure.status, failure.message); + transportError(res, failure.status, failure.message); + return; + } + const status = await streamResponse(res, queue, first, head, marker, ttl); // the engines' edge: a stream failing in-band after its head reports the // failure's own status edge?.recordEdge(status); @@ -462,21 +511,22 @@ export class EventApiServer { } /** - * Render the envelope-mode SSE dialect: envelope frames for the head, the - * terminals and non-text segments; raw frames for plain text. The x-ttl - * allowance (overridable by the producer's head control, in seconds) is the - * per-segment idle; expiry fails the stream in-band with the standard 408 - * error body. Keep-alive comments ride while the producer is quiet - * (event.stream.keep.alive, the engines' key). + * Render the envelope-mode SSE dialect: envelope frames for the head (`head`, + * the first envelope's frame), the terminals and non-text segments; raw + * frames for plain text. The x-ttl allowance (overridable by the producer's + * head control, a whole number of seconds) is the per-segment idle; expiry + * fails the stream in-band with the standard 408 error body. Keep-alive + * comments ride while the producer is quiet (event.stream.keep.alive, the + * engines' key). */ async function streamResponse(res: http.ServerResponse, queue: Mailbox, - first: EventEnvelope, firstMarker: string, + first: EventEnvelope, head: Buffer, firstMarker: string, ttl: number): Promise { let idleMs = ttl; for (const [key, value] of Object.entries(first.headers)) { if (key.toLowerCase() === X_TTL) { - const seconds = Number.parseInt(String(value).trim(), 10); - if (Number.isFinite(seconds) && seconds > 0) { + const seconds = wholeNumber(value); + if (seconds) { idleMs = seconds * 1000; } } @@ -485,7 +535,7 @@ async function streamResponse(res: http.ServerResponse, queue: Mailbox; + try { + action = classifySegment(event); + } catch (e) { + // a segment the wire codec refuses fails the stream in band, as an exception does + const failure = unrendered(event.sender, e); + res.write(envelopeFrame(exceptionEnvelope(failure.status, failure.message))); + return failure.status; + } if (action.warn) { log.warn('Dropping event - invalid x-event-stream signal'); } @@ -616,7 +674,7 @@ export class Platform { async run(options: { port?: number; host?: string } = {}): Promise { const config = appConfig(); const appName = config.getProperty('application.name', 'application'); - const port = options.port ?? Number(config.get('rest.server.port', 8085)); + const port = options.port ?? serverPort(config); const host = options.host ?? '127.0.0.1'; // the opt-in OpenTelemetry forwarder registers on the extension route before // the route list is announced diff --git a/test/bus.test.ts b/test/bus.test.ts index 76f8a690..46e84f6d 100644 --- a/test/bus.test.ts +++ b/test/bus.test.ts @@ -1,7 +1,9 @@ /** Primitive event bus pins: local RPC (public+private), FIFO, workers, deadlines. */ import assert from 'node:assert/strict'; import { test } from 'node:test'; +import { EventBus, raceMs } from '../src/bus.js'; import { PostOffice } from '../src/client.js'; +import { MAX_TIMER_MS, timerMs } from '../src/config.js'; import { EventEnvelope } from '../src/envelope.js'; import { FunctionRegistry } from '../src/registry.js'; import { getTrace, runWithTrace } from '../src/trace.js'; @@ -25,6 +27,29 @@ test('local rpc to public route (headers verbatim)', async () => { assert.ok(typeof reply.execTime === 'number'); }); +test('a delay longer than a timer holds waits, it does not fire at once', async () => { + // setTimeout keeps its delay in 32 bits: 3,000,000,000 ms would fire after one - the delay is + // capped at the longest a timer holds, so the wait is that long instead of none at all + assert.equal(MAX_TIMER_MS, 2147483647); + assert.deepEqual([1, 2147483647, 2147483648, 3000000000, Infinity].map(timerMs), + [1, 2147483647, 2147483647, 2147483647, 2147483647]); + for (const delay of [2147483648, 3000000000, 9007199254740991, Infinity]) { + assert.equal(await raceMs(sleep(30).then(() => 'in time'), delay), 'in time', String(delay)); + } + // a reply within a time to live of that length is the reply, not a 408 + const registry = new FunctionRegistry(); + registry.register('bus.slow', async () => { + await sleep(30); + return 'done'; + }); + const service = registry.get('bus.slow'); + assert.ok(service); + const reply = await new EventBus().deliver(service, {}, null, 3000000000); + assert.equal(reply.body, 'done'); + const local = await new PostOffice(undefined, {}, registry).request('bus.slow', null, { timeoutMs: 3000000000 }); + assert.equal(local.getStatus(), 200); +}); + test('local rpc reaches a private route (engine semantics)', async () => { const registry = new FunctionRegistry(); registry.register('bus.secret', async () => ({ secret: 'ok' }), { isPrivate: true }); diff --git a/test/client.test.ts b/test/client.test.ts index de21ed1b..212900ed 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -1,8 +1,14 @@ /** PostOffice client tests against the in-process host (full wrapper loop). */ import assert from 'node:assert/strict'; -import type * as http from 'node:http'; +import * as fs from 'node:fs'; +import * as http from 'node:http'; +import * as os from 'node:os'; +import * as path from 'node:path'; import { after, before, test } from 'node:test'; import { PostOffice } from '../src/client.js'; +import { appConfig, loadConfig } from '../src/config.js'; +import { EventEnvelope } from '../src/envelope.js'; +import { AppException } from '../src/exceptions.js'; import { FunctionRegistry } from '../src/registry.js'; import { EventApiServer } from '../src/server.js'; import { getTrace, runWithTrace } from '../src/trace.js'; @@ -65,3 +71,66 @@ test('drop-n-forget ack', async () => { assert.equal(ack.getStatus(), 202); assert.equal((ack.body as Record).delivered, true); }); + +const GUARDED_YAML = `rest: + - service: "event.api.service" + methods: ['POST'] + url: "/api/event" + authentication: "client.guard" +`; + +test('an edge-level REST error is the failure it carries', async () => { + // a peer whose /api/event sits behind a REST automation entry with an authentication function + // that lets nobody through: the entry answers for the Event API - JSON, not an envelope - and + // request() and send() return the failure it carries, as stream() and the engines' client do + const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-client-')); + fs.mkdirSync(path.join(folder, 'resources')); + fs.writeFileSync(path.join(folder, 'resources', 'rest.yaml'), GUARDED_YAML); + loadConfig(undefined, folder); + appConfig().set('rest.automation', true); + const registry = buildRegistry(); + registry.register('client.guard', async () => false); + const guarded = new EventApiServer(registry).createServer(); + await new Promise((resolve) => guarded.listen(0, '127.0.0.1', resolve)); + const address = guarded.address() as { port: number }; + try { + const po = new PostOffice(`http://127.0.0.1:${address.port}/api/event`); + const reply = await po.request('client.echo', { hello: 'world' }, { timeoutMs: 5000 }); + assert.equal(reply.getStatus(), 401); + assert.equal(reply.body, 'Unauthorized'); + const ack = await po.send('client.echo', { fire: 'forget' }, { timeoutMs: 5000 }); + assert.equal(ack.getStatus(), 401); + assert.equal(ack.body, 'Unauthorized'); + const streamed: EventEnvelope[] = []; + for await (const segment of po.stream('client.echo', {}, { timeoutMs: 5000 })) { + streamed.push(segment); + } + assert.deepEqual(streamed.map((s) => [s.getStatus(), s.body]), [[401, 'Unauthorized']]); + } finally { + await new Promise((resolve) => guarded.close(() => resolve())); + loadConfig(); + fs.rmSync(folder, { recursive: true, force: true }); + } +}); + +test('a reply that is neither an envelope nor a REST error is still thrown', async () => { + // a peer that answers something else - a proxy's page, JSON that is no error body - is not read + // as a failure the function sent: the call throws, as it did + const peer = http.createServer((_req, res) => { + res.writeHead(503, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ type: 'notice', message: 'maintenance' })); + }); + await new Promise((resolve) => peer.listen(0, '127.0.0.1', resolve)); + const address = peer.address() as { port: number }; + try { + const po = new PostOffice(`http://127.0.0.1:${address.port}/api/event`); + await assert.rejects(po.request('client.echo', {}, { timeoutMs: 5000 }), (e: unknown) => { + assert.ok(e instanceof AppException); + assert.equal(e.status, 503); + assert.ok(e.message.startsWith('Invalid event-over-http response - ')); + return true; + }); + } finally { + await new Promise((resolve) => peer.close(() => resolve())); + } +}); diff --git a/test/config.test.ts b/test/config.test.ts index 8ed8e8b0..8155dfdf 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,12 +1,24 @@ -/** AppConfig tests: resources/ convention, -D overrides, ${ENV:default} substitution. */ +/** + * AppConfig tests: resources/ convention, -D overrides, ${ENV:default} substitution, and the shared + * vectors of how a YAML file, a number, a duration and a switch are read. + */ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { test } from 'node:test'; import { fileURLToPath } from 'node:url'; -import { AppConfig, mainScriptDir, parseDArgs } from '../src/config.js'; +import { AppConfig, durationMs, mainScriptDir, parseDArgs, switchValue, wholeNumber } from '../src/config.js'; +import { parseYaml, parseYamlAsText } from '../src/index.js'; +import { resetLogForTest } from '../src/log.js'; + +const VECTORS_FILE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../test/vectors/config-vectors.json'); +// the Python twin pins the same digest: change the file in both packs or in neither +const VECTORS_SHA256 = '2b6b7fb3d9f73f1cbce4ac169b954577183d8cd8f1a824e9e2b10723199f161e'; +type Json = Record; // eslint-disable-line @typescript-eslint/no-explicit-any +const vectors: Json = JSON.parse(fs.readFileSync(VECTORS_FILE, 'utf-8')); function tempFile(name: string, text: string): string { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-config-')); @@ -201,3 +213,247 @@ test('the application folder is known', () => { assert.equal(config.appDir, appDir); assert.equal(config.resourcesDir, path.dirname(other)); }); + +// ---- the shared vectors: one file, read the same way by both packs ---- + +/** The configuration of an application.yml with this text, under these -D overrides. */ +function loaded(text: string, overrides: Record = {}): AppConfig { + return new AppConfig(tempFile('application.yml', text), Object.entries(overrides).map(([key, value]) => `-D${key}=${value}`)); +} + +/** The kind of a value `get` returns, in the vectors' words. */ +function kindOf(value: unknown): string { + if (value === null || value === undefined) { + return 'null'; + } + if (typeof value === 'boolean') { + return 'boolean'; + } + if (typeof value === 'bigint' || typeof value === 'number') { + return 'number'; + } + return typeof value === 'string' ? 'text' : 'other'; +} + +/** A kind of the vectors as this pack tells it: an integer and a float are one kind of number here. */ +const kindHere = (kind: string): string => (kind === 'integer' || kind === 'float' ? 'number' : kind); + +test('the vector file is the one the python twin runs', () => { + const digest = createHash('sha256').update(fs.readFileSync(VECTORS_FILE)).digest('hex'); + assert.equal(digest, VECTORS_SHA256, "update both packs' pins when the shared file changes"); + assert.equal(vectors.version, 2); +}); + +test('vectors: scalar cases', () => { + // what a setting's reader receives for every scalar of the list: the kind of value from get, the + // text from getProperty - or a file that does not load. The expected values are those of YAML + // 1.2.2's core schema, from a reference written from the specification + for (const c of vectors.scalar_cases) { + const text = `k: ${c.yaml}\n`; + if (c.kind === 'error') { + assert.throws(() => loaded(text), Error, c.yaml); + continue; + } + const config = loaded(text); + assert.equal(kindOf(config.get('k')), kindHere(c.kind), c.yaml); + assert.equal(config.getProperty('k') ?? null, c.text, c.yaml); + } +}); + +test('vectors: an integer is whole and exact, a float keeps its point', () => { + for (const c of vectors.scalar_cases) { + if (c.kind !== 'integer' && c.kind !== 'float') { + continue; + } + const value = loaded(`k: ${c.yaml}\n`).get('k'); + if (c.kind === 'integer') { + // exact: a number up to the largest whole one this pack holds, a BigInt beyond it + assert.equal(String(value), c.text, c.yaml); + assert.equal(typeof value === 'bigint' || Number.isSafeInteger(value), true, c.yaml); + } else { + assert.equal(typeof value, 'number', c.yaml); + } + } +}); + +test('vectors: key cases', () => { + for (const c of vectors.key_cases) { + const config = loaded(c.yaml); + for (const [key, expected] of Object.entries(c.expect)) { + assert.equal(config.getProperty(key) ?? null, expected, `${c.name}: ${key}`); + } + assert.equal(config.exists(''), false, c.name); + } +}); + +test('vectors: reference cases', () => { + for (const c of vectors.reference_cases) { + const before: Record = {}; + const names = [...(c.unset ?? []), ...Object.keys(c.env ?? {})] as string[]; + for (const name of names) { + before[name] = process.env[name]; + delete process.env[name]; + } + Object.assign(process.env, c.env ?? {}); + try { + const config = loaded(c.file, c.overrides); + const defaults: Record = c.defaults ?? {}; + for (const [key, expected] of Object.entries(c.expect)) { + assert.equal(config.getProperty(key, defaults[key]) ?? null, expected, `${c.name}: ${key}`); + if (key in defaults) { + // a key read with a default gives the same from get: the cases with one hold text + assert.equal(config.get(key, defaults[key]), expected, `${c.name}: ${key}`); + } + } + for (const [key, kind] of Object.entries(c.kinds ?? {})) { + assert.equal(kindOf(config.get(key)), kindHere(kind as string), `${c.name}: ${key}`); + } + } finally { + for (const name of names) { + if (before[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = before[name]; + } + } + } + } +}); + +test('vectors: default cases', () => { + // a key written without a value is a key that is not there: the default, as in the engine + for (const c of vectors.default_cases) { + const config = loaded(c.file, c.overrides); + for (const [key, expected] of Object.entries(c.expect)) { + assert.equal(config.getProperty(key, c.defaults[key]), expected, `${c.name}: ${key}`); + assert.equal(config.get(key, c.defaults[key]), expected, `${c.name}: ${key}`); + } + } +}); + +test('the spellings of YAML 1.1 are text and a leading zero is no octal', () => { + // the file is read by YAML 1.2.2: what only YAML 1.1 takes for a boolean or a number is text, 010 + // is ten, 0o10 is eight, and << is a key like any other + const config = loaded('a: yes\nb: 16_000\nc: 1:30\nd: 0b101\ne: 2026-11-30\nf: 010\ng: 0o10\n' + + 'h: =\ni: On\nj: 0x1F\nk: 1e3\n<<:\n x: 1\n'); + assert.deepEqual(Object.fromEntries([...'abcdehi'].map((key) => [key, config.get(key)])), { + a: 'yes', b: '16_000', c: '1:30', d: '0b101', e: '2026-11-30', h: '=', i: 'On' + }); + assert.deepEqual([...'fgj'].map((key) => config.get(key)), [10, 8, 31]); + assert.equal(config.getProperty('k'), '1000.0'); + assert.equal(config.get('<<.x'), 1); +}); + +test('a companion file is read by the same reader', () => { + // parseYaml reads any YAML text of the pack - a companion file of an extension too - and + // parseYamlAsText gives the text a setting reads of every value that is not text + const text = 'a: 010\nb: 1.0\nc: yes\nd: ~\ne: [true, 2.50, 0o17]\nf:\n g: 1e3\n'; + assert.deepEqual(parseYaml(text), { a: 10, b: 1, c: 'yes', d: null, e: [true, 2.5, 15], f: { g: 1000 } }); + assert.deepEqual(parseYamlAsText(text), + { a: '10', b: '1.0', c: 'yes', d: null, e: ['true', '2.5', '15'], f: { g: '1000.0' } }); + assert.equal(parseYaml(''), null); + assert.equal(parseYamlAsText(''), null); + assert.throws(() => parseYaml('a: !!binary aGVsbG8=\n'), Error); +}); + +test('a tag outside the core schema does not load', () => { + // the core schema's tags and no other: a scalar under one is valid when its content is one of + // the tag's forms, and under ! it is text + const config = loaded("a: !!float 1\nb: !!int '0x1F'\nc: !!str 010\nd: ! 010\ne: !!null ~\n"); + assert.deepEqual([...'abcde'].map((key) => config.getProperty(key) ?? null), ['1.0', '31', '010', '010', null]); + for (const text of ['a: !!binary aGVsbG8=\n', 'a: !!timestamp 2026-11-30\n', 'a: !!set {a, b}\n', + 'a: !!int 1_0\n', 'a: !!bool yes\n', 'a: !custom x\n']) { + assert.throws(() => loaded(text), Error, text); + } +}); + +test('a value its references leave empty reads as its default', () => { + // '${NAME:}' is the idiom for an optional setting: unset, the key reads as its default, as in + // the Java engine; an empty text written as one stays an empty text + delete process.env.MERCURY_TEST_EFFORT; + const config = loaded("llm.effort: '${MERCURY_TEST_EFFORT:}'\nliteral: ''\n"); + assert.equal(config.get('llm.effort'), undefined); + assert.equal(config.get('llm.effort', 'medium'), 'medium'); + assert.equal(config.getProperty('llm.effort', 'medium'), 'medium'); + assert.equal(config.getProperty('literal', 'dflt'), ''); + // where a text is resolved, not a key read, nothing changes: an empty text stays one + assert.equal(config.resolveProperty('${MERCURY_TEST_EFFORT:}'), ''); + process.env.MERCURY_TEST_EFFORT = 'high'; + try { + assert.equal(config.get('llm.effort', 'medium'), 'high'); + } finally { + delete process.env.MERCURY_TEST_EFFORT; + } +}); + +test('an override set to null clears the key', () => { + // set(key, null) leaves the key without a value - its default - and never uncovers the value the + // file holds; a later set gives it one again + const config = loaded('a: text\nuses: ${a:fallback}\n'); + assert.equal(config.get('a', 'dflt'), 'text'); + for (const cleared of [null, undefined]) { + config.set('a', cleared); + assert.equal(config.get('a', 'dflt'), 'dflt'); + assert.equal(config.get('a'), undefined); + assert.equal(config.getProperty('a', 'dflt'), 'dflt'); + assert.equal(config.get('uses'), 'fallback'); + assert.equal(config.exists('a'), true); + } + config.set('a', 'again'); + assert.equal(config.get('a', 'dflt'), 'again'); +}); + +test('vectors: number, duration and switch cases', () => { + for (const c of vectors.whole_number_cases) { + assert.equal(wholeNumber(c.value) ?? null, c.number, JSON.stringify(c)); + } + for (const c of vectors.duration_cases) { + assert.equal(durationMs(c.value) ?? null, c.ms, JSON.stringify(c)); + } + for (const c of vectors.switch_cases) { + assert.equal(switchValue(c.value, c.default) ?? null, c.switch, JSON.stringify(c)); + } +}); + +test('a reference sees a -D argument and a set override', () => { + // ${flag:false} with -Dflag=true is true, as in the Java engine, where a reference reads the + // system property before the file; set is the same override, made at run time + const text = 'flag: false\nuses: ${flag:false}\nother: ${late:none}\n'; + assert.equal(loaded(text).get('uses'), false); + const config = loaded(text, { flag: 'true' }); + assert.equal(config.get('uses'), 'true'); + assert.equal(config.get('other'), 'none'); + config.set('late', 'set'); + assert.equal(config.get('other'), 'set'); + config.set('flag', false); + assert.equal(config.get('uses'), false); +}); + +test('a reference loop is logged and has no value', (t) => { + const config = loaded('a: ${b:1}\nb: ${a:2}\nc: ${c}\n'); + const lines: string[] = []; + resetLogForTest(); + t.mock.method(process.stdout, 'write', (chunk: string | Uint8Array) => { + lines.push(String(chunk)); + return true; + }); + try { + assert.equal(config.get('a'), '2'); + assert.equal(config.get('c', 'default'), 'default'); + } finally { + t.mock.restoreAll(); + } + const warnings = lines.filter((line) => line.includes('mercury.config')).map((line) => line.trim().split(' - ')[1]); + assert.deepEqual(warnings, ["Config loop for 'a' detected", "Config loop for 'c' detected"]); +}); + +test('resolveProperty is the text a value reads as', () => { + const config = loaded('flag: true\nrate: 1.0\n'); + assert.equal(config.resolveText('${flag}'), true); + assert.equal(config.resolveProperty('${flag}'), 'true'); + assert.equal(config.resolveText('${rate}'), 1); + assert.equal(config.resolveProperty('${rate}'), '1.0'); + assert.equal(config.resolveProperty('is ${flag} at ${rate}'), 'is true at 1.0'); + assert.equal(config.resolveProperty('${NOT_SET_ANYWHERE}'), undefined); + assert.equal(config.resolveProperty('plain'), 'plain'); +}); diff --git a/test/log-context.test.ts b/test/log-context.test.ts index fc589b72..c763ed84 100644 --- a/test/log-context.test.ts +++ b/test/log-context.test.ts @@ -3,13 +3,20 @@ * template rendering, the updateContext developer API and feature gating. */ import assert from 'node:assert/strict'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; import { test } from 'node:test'; -import { appConfig } from '../src/config.js'; +import { AppConfig, appConfig, loadConfig } from '../src/config.js'; +import { AppException } from '../src/exceptions.js'; import { + enabled, LogContextConfig, logContextConfig, resetLogContextForTest } from '../src/log-context.js'; +import { FunctionRegistry } from '../src/registry.js'; +import { EventApiServer } from '../src/server.js'; import { runWithTrace, TraceInfo, updateContext } from '../src/trace.js'; // mirror of the engines' built-in default-log-context.yaml @@ -71,6 +78,68 @@ test('updateContext merges custom keys and guards reserved keys', () => { updateContext('tenant', 'ignored'); }); +test('the template file is read as every YAML file of the pack', () => { + // app-log-context.yaml goes through the pack's one reader, YAML 1.2.2: what only YAML 1.1 takes + // for a boolean or a number is text, a constant that is not text is the text a setting reads, and + // an entry without a value is dropped, as the engines drop it + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-log-context-')); + fs.writeFileSync(path.join(dir, 'application.yml'), 'application.name: demo\n'); + fs.writeFileSync(path.join(dir, 'app-log-context.yaml'), + 'context:\n trace: $traceId\n word: yes\n flag: true\n rate: 1.0\n zero: 010\n count: 16_000\n' + + " none:\n quoted: 'on'\n empty: ''\n"); + loadConfig(path.join(dir, 'application.yml')); + resetLogContextForTest(); + try { + assert.deepEqual(logContextConfig().render(infoUnderTest()), { + trace: '4bf92f3577b34da6a3ce929d0e0e4736', word: 'yes', flag: 'true', rate: '1.0', zero: '10', + count: '16_000', quoted: 'on', empty: '' + }); + } finally { + loadConfig(); + resetLogContextForTest(); + } +}); + +test('a constant given in code is the text a setting reads', () => { + const context = new LogContextConfig({ flag: true, count: 3, ratio: 0.5, none: null }).render(infoUnderTest()); + assert.deepEqual(context, { flag: 'true', count: '3', ratio: '0.5' }); +}); + +// the values a switch is read from, and what it is set to: null for one that is refused +const SWITCH_PROBES: Array<[unknown, boolean | null]> = [ + [true, true], ['true', true], ['TRUE', true], ['tRuE', true], [false, false], ['false', false], + ['False', false], ['yes', null], ['no', null], ['on', null], ['off', null], ['1', null], [1, null], + [0, null], [' true ', null], ['maybe', null] +]; + +test('the switch is true or false and on without a value', () => { + const config = new AppConfig(undefined, []); + assert.equal(enabled(config), true); + config.set('app.log.context', ''); + assert.equal(enabled(config), true); + for (const [value, expected] of SWITCH_PROBES) { + config.set('app.log.context', value); + if (expected === null) { + assert.throws(() => enabled(config), (e: unknown) => e instanceof AppException && e.status === 400 && + e.message === 'app.log.context must be true or false', String(value)); + } else { + assert.equal(enabled(config), expected, String(value)); + } + } +}); + +test('a switch that is neither stops the host by name', () => { + try { + appConfig().set('app.log.context', 'off'); + assert.throws(() => new EventApiServer(new FunctionRegistry()), + (e: unknown) => e instanceof AppException && e.message === 'app.log.context must be true or false'); + appConfig().set('app.log.context', 'FALSE'); + assert.deepEqual(new EventApiServer(new FunctionRegistry()).registry.routes(), []); + } finally { + appConfig().set('app.log.context', 'true'); + } +}); + test('the app.log.context flag disables the feature', () => { try { appConfig().set('app.log.context', 'false'); diff --git a/test/mcp-binding.test.mjs b/test/mcp-binding.test.mjs index eb81ed3b..1aeeac23 100644 --- a/test/mcp-binding.test.mjs +++ b/test/mcp-binding.test.mjs @@ -313,6 +313,19 @@ for (const [entry, message] of [ }); } +test('the server file is read as every YAML file of the pack', () => { + // mcp-servers.yml goes through the pack's one reader, YAML 1.2.2: what only YAML 1.1 takes for a + // boolean or a number is text, and a value that is not text is the text a setting reads - the + // same arguments and the same environment reach the server from both packs + const path = join(scratch, 'mcp-servers-as-text.yml'); + writeFileSync(path, 'servers:\n s:\n transport: stdio\n command: run\n args: [yes, 010, true, 1.0, 16_000]\n' + + ' env:\n WORD: on\n FLAG: true\n RATIO: 2.0\n ZERO: 010\n timeout_ms: 2000\n', 'utf8'); + const [spec] = loadServers(path); + assert.deepEqual(spec.args, ['yes', '10', 'true', '1.0', '16_000']); + assert.deepEqual(spec.env, { WORD: 'on', FLAG: 'true', RATIO: '2.0', ZERO: '10' }); + assert.equal(spec.timeout_ms, 2000); +}); + test('an empty server map loads no server', () => { const { log } = servers({}); assert.deepEqual(loadServers(undefined, log), []); diff --git a/test/otel-forwarder.test.ts b/test/otel-forwarder.test.ts index 0edaa3a5..45bf8387 100644 --- a/test/otel-forwarder.test.ts +++ b/test/otel-forwarder.test.ts @@ -8,8 +8,9 @@ import assert from 'node:assert/strict'; import * as http from 'node:http'; import { after, before, test } from 'node:test'; import { AppConfig } from '../src/config.js'; +import { AppException } from '../src/exceptions.js'; import { - activate, attribute, describeHttpFailure, DISTRIBUTED_TRACE_FORWARDER, encodeExportRequest, + activate, attribute, describeHttpFailure, DISTRIBUTED_TRACE_FORWARDER, enabled, encodeExportRequest, Exporter, ExportFailure, fixedSettings, INSTRUMENTATION_SCOPE, parseHeaders, parseIso8601Nanos, partialSuccess, ProtoReader, ProtoWriter, settingsFromConfig, SPAN_FLAGS_SAMPLED_LOCAL, spanFromDataset @@ -411,6 +412,36 @@ test('the credential is re-read on every export', async () => { // activation and the host hook // --------------------------------------------------------------------------- +// the values a switch is read from, and what it is set to: null for one that is refused +const SWITCH_PROBES: Array<[unknown, boolean | null]> = [ + [true, true], ['true', true], ['TRUE', true], ['tRuE', true], [false, false], ['false', false], + ['False', false], ['yes', null], ['no', null], ['on', null], ['off', null], ['1', null], [1, null], + [0, null], [' true ', null], ['maybe', null] +]; + +test('the switch is true or false and off without a value', () => { + const config = new AppConfig(undefined, []); + assert.equal(enabled(config), false); + config.set('otel.forwarding', ''); + assert.equal(enabled(config), false); + for (const [value, expected] of SWITCH_PROBES) { + config.set('otel.forwarding', value); + if (expected === null) { + assert.throws(() => enabled(config), (e: unknown) => e instanceof AppException && e.status === 400 && + e.message === 'otel.forwarding must be true or false', String(value)); + } else { + assert.equal(enabled(config), expected, String(value)); + } + } +}); + +test('a switch that is neither stops the start by name', () => { + const registry = new FunctionRegistry(); + assert.throws(() => activate(configWith({ 'otel.forwarding': 'yes' }), registry), + (e: unknown) => e instanceof AppException && e.message === 'otel.forwarding must be true or false'); + assert.equal(registry.exists(DISTRIBUTED_TRACE_FORWARDER), false); +}); + test('the switch is the only thing that turns it on', () => { const registry = new FunctionRegistry(); assert.equal(activate(configWith({}), registry), undefined); diff --git a/test/rest-automation.test.ts b/test/rest-automation.test.ts index 091231df..073341f3 100644 --- a/test/rest-automation.test.ts +++ b/test/rest-automation.test.ts @@ -14,9 +14,10 @@ import { fileURLToPath } from 'node:url'; import { AsyncHttpRequest } from '../src/async-http-request.js'; import { appConfig, loadConfig } from '../src/config.js'; import { EventEnvelope } from '../src/envelope.js'; -import { EventStreamWriter } from '../src/event-stream.js'; +import { EventStreamWriter, keepAliveMs } from '../src/event-stream.js'; import { AppException } from '../src/exceptions.js'; import { FunctionRegistry } from '../src/registry.js'; +import { streamHead } from '../src/rest-automation.js'; import { acceptFallbackType, CorsInfo, @@ -28,6 +29,7 @@ import { parseCookies, parseQuery, parseTimeout, + parseUpload, renderPayload, RouteInfo, RoutingTable, @@ -39,7 +41,7 @@ import { getTrace } from '../src/trace.js'; const here = path.dirname(fileURLToPath(import.meta.url)); const VECTORS_FILE = path.resolve(here, '../../test/vectors/rest-automation-vectors.json'); // the Python twin pins the same digest: change the file in both packs or in neither -const VECTORS_SHA256 = '02fb140f780a9b781dc6cfc7a1c48b1b8094a089cae350dbf5e813754517a51d'; +const VECTORS_SHA256 = 'd7fdef7f56529bdc1faffdefda87bb1cfc70c91600faa8049940e2c594ca3d24'; const MY_CID = 'my_correlation_id'; type Json = Record; // eslint-disable-line @typescript-eslint/no-explicit-any @@ -61,7 +63,7 @@ function routeView(route: RouteInfo): Json { test('the vector file is the one the python twin runs', () => { const digest = createHash('sha256').update(fs.readFileSync(VECTORS_FILE)).digest('hex'); assert.equal(digest, VECTORS_SHA256, "update both packs' pins when the shared file changes"); - assert.equal(vectors.version, 3); + assert.equal(vectors.version, 5); }); test('vectors: load cases', () => { @@ -91,7 +93,7 @@ test('vectors: load cases', () => { test('vectors: timeout cases', () => { for (const c of vectors.timeout_cases) { - assert.equal(parseTimeout(c.value), c.ms, JSON.stringify(c)); + assert.equal(orNull(parseTimeout(c.value)), c.ms, JSON.stringify(c)); } }); @@ -234,6 +236,33 @@ test('vectors: upload read cases', () => { } }); +const UPLOAD_BOUND = 16 * 1024 * 1024; + +/** A case's body: text, or base64 where the bytes are no UTF-8. */ +const uploadBody = (c: Json): Buffer => + 'body_base64' in c ? Buffer.from(c.body_base64, 'base64') : Buffer.from(c.body, 'utf-8'); + +test('vectors: upload cases', () => { + for (const c of vectors.upload_cases) { + const bound = c.bound ?? UPLOAD_BOUND; + if ('error' in c) { + assert.throws(() => parseUpload(uploadBody(c), c.content_type, bound), (e: unknown) => { + assert.ok(e instanceof AppException, c.name); + assert.equal(e.status, c.status, c.name); + assert.equal(e.message, c.error, c.name); + return true; + }, c.name); + continue; + } + const { files, fields } = parseUpload(uploadBody(c), c.content_type, bound); + const found = files.map((f) => ({ + name: f.name, content_type: f.contentType, size: f.size, tag: f.tag, content_base64: f.content.toString('base64') + })); + assert.deepEqual(found, c.files, c.name); + assert.deepEqual(fields, c.fields, c.name); + } +}); + const sortedLines = (lines: Array<[string, string]>): Array<[string, string]> => lines.map(([n, v]) => [n.toLowerCase(), v] as [string, string]).sort((a, b) => `${a[0]}=${a[1]}`.localeCompare(`${b[0]}=${b[1]}`)); @@ -1122,6 +1151,67 @@ cors: - "Access-Control-Allow-Origin: *" `; +const NAMES_YAML = `rest: + - service: "names.view" + methods: ['GET', 'POST'] + url: "/names/{__proto__}/{constructor}" + authentication: "names.auth" + upload: true +`; +// what the function behind the entry sees of the requests of the test below, the same in both packs +const NAMES_SEEN: Json = JSON.parse(`{ + "path": {"__proto__": "one", "constructor": "two"}, + "query": {"__proto__": "q1", "constructor": ["q2", "q3"], "toString": "q4"}, + "cookies": {"__proto__": "k1", "constructor": "k2"}, + "session": {"__proto__": "s1", "constructor": "s2"}, + "header": "h1", + "absent": {"query": true, "cookie": true, "session": true, "path": true} +}`); + +test('a name every object carries is a name like any other', async () => { + // __proto__, constructor and toString - names every object here carries - as a query parameter, a + // form field, an upload's field, a cookie, a header, a path parameter and a session key reach the + // function as plain values, and one the request does not hold reads as any name it does not + // hold: the same request reads the same in both packs + const registry = new FunctionRegistry(); + registry.register('names.auth', async () => + new EventEnvelope().setHeader('__proto__', 's1').setHeader('constructor', 's2').setBody(true)); + registry.register('names.view', async (_headers, body) => { + const request = new AsyncHttpRequest(body); + return { + path: request.pathParameters, query: request.queryParametersMap, cookies: request.cookies, + session: request.session, header: request.header('__proto__'), + absent: { + query: request.queryParameter('valueOf') === undefined, cookie: request.cookie('toString') === undefined, + session: request.sessionInfo('toString') === undefined, path: request.pathParameter('toString') === undefined + } + }; + }); + // written as JSON, where __proto__ is a key like any other: in an object literal it is not + const sent: Record = JSON.parse('{"Cookie": "__proto__=k1; constructor=k2", "__proto__": "h1"}'); + const withQuery = (query: Json): Json => ({ ...NAMES_SEEN, query }); + configured(NAMES_YAML); + const served = await start(registry); + try { + const url = `${served.base}/names/one/two`; + let reply = await exchange(`${url}?__proto__=q1&constructor=q2&constructor=q3&toString=q4`, 'GET', sent); + assert.equal(reply.status, 200); + assert.deepEqual(json(reply.body), NAMES_SEEN); + // a form's fields, and an upload's, join the query parameters under the same names + reply = await exchange(url, 'POST', { ...sent, 'Content-Type': 'application/x-www-form-urlencoded' }, + '__proto__=q1&constructor=q2&constructor=q3&toString=q4'); + assert.equal(reply.status, 200); + assert.deepEqual(json(reply.body), withQuery({ ...NAMES_SEEN.query, constructor: 'q3' })); + const multipart = multipartBody(textField('__proto__', 'q1'), textField('toString', 'q4')); + reply = await exchange(url, 'POST', { ...sent, ...multipart.headers }, multipart.body); + assert.equal(reply.status, 200); + assert.deepEqual(json(reply.body), withQuery(JSON.parse('{"__proto__": "q1", "toString": "q4"}'))); + } finally { + await served.stop(); + loadConfig(); + } +}); + test('a user entry overrides a default and adds CORS', async () => { configured(DEFAULT_OVERRIDE_YAML); const served = await start(buildRegistry(new Probe())); @@ -1523,3 +1613,314 @@ test('a segment that cannot be rendered fails the stream in band and is traced', loadConfig(); } }); + +// ---- the loose ends: one rule for a setting, an upload, a refusal ---- + +test('the edge reads every upload case as the reader does', async () => { + // every upload case of the shared vectors through the edge over HTTP: the files and the fields a + // function receives, or the engines' error body with the reader's status and message + const byBound = new Map(); + for (const c of vectors.upload_cases as Json[]) { + const bound = c.bound ?? UPLOAD_BOUND; + byBound.set(bound, [...(byBound.get(bound) ?? []), c]); + } + for (const [bound, cases] of byBound) { + configured(REST_YAML, { 'rest.upload.max.bytes': bound }); + const served = await start(buildRegistry(new Probe())); + try { + for (const c of cases) { + const headers = { 'Content-Type': c.content_type, Accept: 'application/json' }; + const { status, body } = await exchange(`${served.base}/api/upload`, 'POST', headers, uploadBody(c)); + const reply = json(body); + if ('error' in c) { + assert.equal(status, c.status, c.name); + assert.deepEqual(reply, { status: c.status, message: c.error, type: 'error' }, c.name); + continue; + } + assert.equal(status, 200, c.name); + assert.deepEqual(reply.files, (c.files as Json[]).map((f) => ({ + name: f.name, type: f.content_type, size: f.size, tag: f.tag, + sha256: sha256(Buffer.from(f.content_base64, 'base64')) + })), c.name); + assert.deepEqual(reply.query, c.fields, c.name); + } + } finally { + await served.stop(); + loadConfig(); + } + } +}); + +test('an upload that outgrows its bound by more than its framing is refused unread', async () => { + // the body is read within the bound and the megabyte its delimiters and headers may take: one that + // outgrows that is the 413 of the bound, whatever its parts would have been + const headers = { 'Content-Type': `multipart/form-data; boundary=${BOUNDARY}`, Accept: 'application/json' }; + configured(REST_YAML, { 'rest.upload.max.bytes': 40 }); + const served = await start(buildRegistry(new Probe())); + try { + const over = await exchange(`${served.base}/api/upload`, 'POST', headers, Buffer.alloc(40 + 1024 * 1024 + 1, 'x')); + assert.equal(over.status, 413); + assert.deepEqual(json(over.body), { status: 413, message: 'Upload exceeds 40 bytes', type: 'error' }); + // a body that small is read, and refused for what it is + const within = await exchange(`${served.base}/api/upload`, 'POST', headers, Buffer.alloc(40 + 1024 * 1024, 'x')); + assert.equal(within.status, 400); + assert.equal(json(within.body).message, + 'Invalid multipart body - no part is delimited by the boundary the content type declares'); + } finally { + await served.stop(); + loadConfig(); + } +}); + +const OVERRIDE_YAML = `rest: + - service: "plain.text" + methods: ['POST'] + url: "/api/override" + tracing: \${rest.test.flag:false} + timeout: \${rest.test.timeout:10s} +`; + +/** The override entry's application folder: the rest.yaml beside an application.yml that turns the flag off. */ +function overrideConfigured(settings: Record = {}): void { + const folder = configured(OVERRIDE_YAML); + write(path.join(folder, 'resources', 'application.yml'), 'rest.test.flag: false\n'); + loadConfig(undefined, folder); + const config = appConfig(); + config.set('rest.automation', true); + for (const [key, value] of Object.entries(settings)) { + config.set(key, value); + } +} + +test('a reference in rest.yaml sees an override', () => { + // `tracing: ${flag:false}` with -Dflag=true is on, as in the Java engine: a reference reads the + // key as a key is read - an override before the file's value + try { + overrideConfigured(); + let api = new EventApiServer(buildRegistry(new Probe())); + let entry = api.rest?.table.find('POST', '/api/override'); + assert.ok(entry); + assert.equal(entry.info.tracing, false); + assert.equal(entry.info.timeoutMs, 10000); + overrideConfigured({ 'rest.test.flag': 'true', 'rest.test.timeout': '45s' }); + api = new EventApiServer(buildRegistry(new Probe())); + entry = api.rest?.table.find('POST', '/api/override'); + assert.ok(entry); + assert.equal(entry.info.tracing, true); + assert.equal(entry.info.timeoutMs, 45000); + } finally { + loadConfig(); + } +}); + +const KEEP_ALIVE_RULE = 'event.stream.keep.alive must be a duration such as 30s, 2m or 500ms' + + ' (seconds, ms, s, m, h, d), or 0 for none'; +const UPLOAD_BOUND_RULE = 'rest.upload.max.bytes must be a whole number >= 0'; +const TIMEOUT_RULE = "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)"; +const WRONG_SETTINGS: Array<[string, unknown, string]> = [ + ['rest.automation', 'maybe', 'rest.automation must be true or false'], + ['rest.automation', 'yes', 'rest.automation must be true or false'], + ['rest.automation', 1, 'rest.automation must be true or false'], + ['rest.automation', ' true ', 'rest.automation must be true or false'], + ['rest.upload.max.bytes', '12abc', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '1_000', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '0x10', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '1e3', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '40.9', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', 40.9, UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', -5, UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '-5', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', '', UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', true, UPLOAD_BOUND_RULE], + ['rest.upload.max.bytes', 9007199254740992, UPLOAD_BOUND_RULE], + ['event.stream.keep.alive', '1.5s', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '0.5s', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '1_0s', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '1e3ms', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '-1s', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', 'soon', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '', KEEP_ALIVE_RULE], + // longer than a timer of this pack holds: 2147483647 ms + ['event.stream.keep.alive', '2147483648ms', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', '25d', KEEP_ALIVE_RULE], + ['event.stream.keep.alive', 2147484, KEEP_ALIVE_RULE], + ['app.log.context', 'off', 'app.log.context must be true or false'], + ['app.log.context', 'yes', 'app.log.context must be true or false'], + ['app.log.context', 0, 'app.log.context must be true or false'], + ['rest.test.timeout', '1_0s', TIMEOUT_RULE], + ['rest.test.timeout', '\u0663s', TIMEOUT_RULE], + ['rest.test.timeout', '1e3', TIMEOUT_RULE] +]; + +test('a setting that is wrong stops the start by name', () => { + // a switch that is neither true nor false, a bound that is no whole number, a keep-alive and an + // entry's timeout that are no duration: none of them is read as off or as a default + for (const [key, value, message] of WRONG_SETTINGS) { + const label = `${key}=${JSON.stringify(value)}`; + try { + overrideConfigured({ [key]: value }); + assert.throws(() => new EventApiServer(buildRegistry(new Probe())), (e: unknown) => { + assert.ok(e instanceof AppException, label); + assert.equal(e.status, 400, label); + assert.equal(e.message, message, label); + return true; + }, label); + } finally { + loadConfig(); + } + } +}); + +test('a switch written yes or on in the file is refused', () => { + // yes, no, on and off are text in the packs - the Java engine's reader takes them for booleans, a + // spelling no guide documents - so a switch written that way in the file is refused by name: never + // read as on, and never as off + for (const word of ['yes', 'Yes', 'on', 'ON', 'no', 'off']) { + try { + const folder = configured(OVERRIDE_YAML); + write(path.join(folder, 'resources', 'application.yml'), `rest.automation: ${word}\n`); + loadConfig(undefined, folder); + assert.equal(appConfig().get('rest.automation'), word); + assert.throws(() => new EventApiServer(buildRegistry(new Probe())), (e: unknown) => { + assert.ok(e instanceof AppException, word); + assert.equal(e.message, 'rest.automation must be true or false', word); + return true; + }, word); + } finally { + loadConfig(); + } + } +}); + +const RIGHT_SETTINGS: Array<[Record, number, number]> = [ + [{}, 16 * 1024 * 1024, 30000], + [{ 'rest.upload.max.bytes': '40', 'event.stream.keep.alive': '500ms' }, 40, 500], + [{ 'rest.upload.max.bytes': 16000.0, 'event.stream.keep.alive': 2 }, 16000, 2000], + [{ 'rest.upload.max.bytes': ' 0 ', 'event.stream.keep.alive': '0' }, 0, 0], + [{ 'rest.upload.max.bytes': 9007199254740991, 'event.stream.keep.alive': '1h' }, 9007199254740991, 3600000], + [{ 'rest.automation': 'TRUE', 'event.stream.keep.alive': ' 2m ' }, 16 * 1024 * 1024, 120000], + [{ 'event.stream.keep.alive': '2147483647ms', 'app.log.context': 'FALSE' }, 16 * 1024 * 1024, 2147483647], + [{ 'event.stream.keep.alive': '24d', 'app.log.context': true }, 16 * 1024 * 1024, 2073600000] +]; + +test('a number and a duration are read by one rule', () => { + for (const [settings, bound, keepAlive] of RIGHT_SETTINGS) { + const label = JSON.stringify(settings); + try { + overrideConfigured(settings); + const api = new EventApiServer(buildRegistry(new Probe())); + assert.ok(api.rest, label); + assert.equal((api.rest as unknown as { uploadMaxBytes: number }).uploadMaxBytes, bound, label); + assert.equal(keepAliveMs(), keepAlive, label); + } finally { + loadConfig(); + } + } +}); + +test('the switch is off for false, no value and an empty one', () => { + for (const value of [false, 'false', 'FALSE', '', null, undefined]) { + try { + overrideConfigured({ 'rest.automation': value }); + assert.equal(new EventApiServer(buildRegistry(new Probe())).rest, undefined, String(value)); + } finally { + loadConfig(); + } + } +}); + +test("a head's x-ttl is a whole number of seconds", () => { + // the idle allowance a stream's head asks for: digits and nothing else, in both packs + const idle = (ttl: string): number => streamHead(new EventEnvelope().setHeader('x-ttl', ttl), 30000).idleMs; + assert.equal(idle('5'), 5000); + assert.equal(idle(' 5 '), 5000); + for (const ttl of ['0', '1_0', '+5', '-5', '5.0', '5e0', '\u0665', 'five', '']) { + assert.equal(idle(ttl), 30000, ttl); + } +}); + +const FILTER_FAILS_YAML = `rest: + - service: "plain.text" + methods: ['GET'] + url: "/api/text" +static-content: + filter: + path: ["*.html"] + service: "http.request.filter" +`; + +test("a filter reply that cannot be rendered is the engines' 500", async () => { + // a filter's own reply is the response when its status is not 200; one that cannot be rendered is + // answered as any other such reply - never with the host's catch-all + configured(FILTER_FAILS_YAML, {}, { 'about.html': '

about

' }); + const registry = buildRegistry(new Probe()); + registry.register('http.request.filter', async () => + new EventEnvelope().setStatus(401).setHeader('x-filter', 'demo').setBody({ when: 10n })); + const served = await start(registry); + try { + const { status, lines, body } = await exchange(`${served.base}/about.html`, 'GET', { Accept: 'application/json' }); + assert.equal(status, 500); + assert.equal(header(lines, 'content-type'), 'application/json'); + assert.equal(body.toString('utf-8'), UNRENDERABLE); + assert.equal(header(lines, 'x-filter'), undefined); + } finally { + await served.stop(); + loadConfig(); + } +}); + +const TRACED_UPLOAD_YAML = `rest: + - service: "upload.probe" + methods: ['POST'] + url: "/api/traced/upload" + upload: true + tracing: true +`; + +/** The edge's `http.request` records of the requests for `path`, once `count` are seen. */ +async function edgeRecords(probe: Probe, path: string, count: number): Promise { + const found = (): Json[] => probe.datasets.map((d) => d.trace) + .filter((trace) => trace.service === 'http.request' && trace.path === path); + await waitFor(() => found().length >= count); + return found(); +} + +test('a refusal while the request is read is traced', async () => { + // the engines record a traced request once its trace is resolved: a refusal raised while the body + // is read - a 400, a 413 - leaves the edge's record, under the caller's span + const traceId = '4bf92f3577b34da6a3ce929d0e0e4736'; + const callerSpan = '00f067aa0ba902b7'; + const route = 'POST /api/traced/upload'; + const probe = new Probe(); + configured(TRACED_UPLOAD_YAML, { 'rest.upload.max.bytes': 40 }); + const served = await start(buildRegistry(probe)); + try { + const nameless = multipartBody([['Content-Type: text/plain'], Buffer.from('x')]); + const refused = await exchange(`${served.base}/api/traced/upload`, 'POST', + { ...nameless.headers, traceparent: `00-${traceId}-${callerSpan}-01` }, nameless.body); + assert.equal(refused.status, 400); + const refusal = "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name"; + assert.equal(json(refused.body).message, refusal); + let records = await edgeRecords(probe, route, 1); + assert.equal(records[0].status, 400); + assert.equal(records[0].success, false); + assert.equal(records[0].exception, refusal); + assert.equal(records[0].id, traceId); + assert.equal(records[0].parent_span_id, callerSpan); + const large = multipartBody(filePart('doc', 'a.bin', Buffer.alloc(41, 1))); + const over = await exchange(`${served.base}/api/traced/upload`, 'POST', large.headers, large.body); + assert.equal(over.status, 413); + records = await edgeRecords(probe, route, 2); + assert.equal(records[1].status, 413); + assert.equal(records[1].exception, 'Upload exceeds 40 bytes'); + // an upload the edge takes is recorded as before, once + const fits = multipartBody(filePart('doc', 'a.bin', Buffer.alloc(40, 1))); + const taken = await exchange(`${served.base}/api/traced/upload`, 'POST', fits.headers, fits.body); + assert.equal(taken.status, 200); + records = await edgeRecords(probe, route, 3); + assert.deepEqual(records.map((r) => r.status), [400, 413, 200]); + } finally { + await served.stop(); + loadConfig(); + } +}); diff --git a/test/server.test.ts b/test/server.test.ts index 32d99485..a547da65 100644 --- a/test/server.test.ts +++ b/test/server.test.ts @@ -3,10 +3,13 @@ import { encode } from '@msgpack/msgpack'; import assert from 'node:assert/strict'; import type * as http from 'node:http'; import { after, before, test } from 'node:test'; +import { PostOffice } from '../src/client.js'; +import { AppConfig } from '../src/config.js'; import { EventEnvelope } from '../src/envelope.js'; +import { EventStreamWriter, SseParser } from '../src/event-stream.js'; import { AppException } from '../src/exceptions.js'; import { FunctionRegistry } from '../src/registry.js'; -import { EventApiServer } from '../src/server.js'; +import { EventApiServer, serverPort } from '../src/server.js'; import { annotateTrace, getTrace } from '../src/trace.js'; const OCTET = 'application/octet-stream'; @@ -187,3 +190,191 @@ test("a body over the host's limit is a transport failure 413", async () => { assert.equal(reply.getStatus(), 413); assert.equal(reply.body, 'Request body exceeds 16777216 bytes'); }); + +// ---- a reply the wire codec refuses ---- + +const UNRENDERABLE = 'Reply cannot be rendered'; +const TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'; +type Trace = Record; +// a function: a type MsgPack does not hold +const unencodable = (): Record => ({ when: () => 1 }); + +/** + * A host of functions whose reply holds a function - a type MsgPack does not hold - and of the + * forwarder that collects the trace records. + */ +async function unencodableHost(): Promise<{ base: string; datasets: Trace[]; stop: () => Promise }> { + const registry = new FunctionRegistry(); + const datasets: Trace[] = []; + registry.register('unit.unencodable', async () => unencodable()); + registry.register('unit.unencodable.manual', async (_headers, event) => { + registry.sendEvent(new EventEnvelope((event as EventEnvelope).replyTo, unencodable())); + }, { interceptor: true }); + registry.register('unit.unencodable.head', async (_headers, event) => { + const out = EventStreamWriter.fromRequest(event as EventEnvelope, registry); + out.first(200, 'text/event-stream'); + // the head carries the first segment's body: one the codec refuses, before anything is sent + out.write(unencodable()); + }, { interceptor: true }); + registry.register('unit.unencodable.segment', async (_headers, event) => { + const out = EventStreamWriter.fromRequest(event as EventEnvelope, registry); + out.first(200, 'text/event-stream'); + out.write('one'); + out.write('two'); + out.write(unencodable()); + out.write('four'); + out.close(); + }, { interceptor: true }); + registry.register('distributed.trace.forwarder', async (_headers, body) => { + const trace = (body as Record | null)?.trace; + if (trace !== null && typeof trace === 'object') { + datasets.push(trace as Trace); + } + }, { isPrivate: true }); + const host = new EventApiServer(registry).createServer(); + await new Promise((resolve) => host.listen(0, '127.0.0.1', resolve)); + const address = host.address() as { port: number }; + return { + base: `http://127.0.0.1:${address.port}`, + datasets, + stop: () => new Promise((resolve) => { + registry.bus.close(); + host.closeAllConnections(); + host.close(() => resolve()); + }) + }; +} + +/** The trace records of a service, once the edge's own record - the last one written - is in. */ +async function records(datasets: Trace[], service: string): Promise { + for (let i = 0; i < 100; i++) { + if (datasets.some((d) => d.service === 'http.request')) { + return datasets.filter((d) => d.service === service); + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } + throw new Error("the edge's record was not seen"); +} + +const traced = (route: string): EventEnvelope => new EventEnvelope(route, {}).setTrace(TRACE_ID, 'TEST /unencodable'); + +async function postTo(hostBase: string, event: EventEnvelope): Promise { + return fetch(`${hostBase}/api/event`, { + method: 'POST', + headers: { 'content-type': OCTET, 'x-ttl': '10000', accept: 'text/event-stream' }, + body: event.toBytes() + }); +} + +for (const route of ['unit.unencodable', 'unit.unencodable.manual', 'unit.unencodable.head']) { + test(`a reply the wire codec refuses is a 500 envelope and is recorded - ${route}`, async () => { + // an RPC reply, an interceptor's single-shot answer and a stream's head: a reply that cannot + // travel is answered with one message, in an envelope as every transport failure is, and the + // edge's record carries the status sent + const host = await unencodableHost(); + try { + const response = await postTo(host.base, traced(route)); + const reply = EventEnvelope.fromBytes(new Uint8Array(await response.arrayBuffer())); + assert.equal(response.status, 500); + assert.equal(reply.getStatus(), 500); + assert.equal(reply.body, UNRENDERABLE); + const edge = await records(host.datasets, 'http.request'); + assert.deepEqual(edge.map((d) => d.status), [500]); + assert.equal(edge[0].success, false); + assert.equal(edge[0].exception, UNRENDERABLE); + assert.equal(edge[0].id, TRACE_ID); + } finally { + await host.stop(); + } + }); +} + +test('the function of an unencodable reply keeps its own record', async () => { + const host = await unencodableHost(); + try { + const response = await postTo(host.base, traced('unit.unencodable')); + assert.equal(response.status, 500); + await response.arrayBuffer(); + await records(host.datasets, 'http.request'); + // the function answered: its round trip is the record of a success + const fn = host.datasets.filter((d) => d.service === 'unit.unencodable'); + assert.deepEqual(fn.map((d) => d.status), [200]); + assert.equal(fn[0].success, true); + assert.ok('round_trip' in fn[0]); + } finally { + await host.stop(); + } +}); + +test('a segment the wire codec refuses fails the stream in band', async () => { + const host = await unencodableHost(); + try { + const response = await postTo(host.base, traced('unit.unencodable.segment')); + assert.equal(response.status, 200); + const frames = new SseParser().feed(new Uint8Array(await response.arrayBuffer())); + // the head with the first segment, the segment before the fault, then the failure - nothing + // after it + assert.deepEqual(frames.map(([name]) => name), ['envelope', undefined, 'envelope']); + assert.equal(EventEnvelope.fromBytes(Buffer.from(frames[0][1], 'base64')).body, 'one'); + assert.equal(frames[1][1], 'two'); + const failure = EventEnvelope.fromBytes(Buffer.from(frames[2][1], 'base64')); + assert.equal(failure.getStatus(), 500); + assert.deepEqual(failure.body, { type: 'error', status: 500, message: UNRENDERABLE }); + const edge = await records(host.datasets, 'http.request'); + assert.deepEqual(edge.map((d) => d.status), [500]); + } finally { + await host.stop(); + } +}); + +// ---- settings and headers read by the one rule for a number ---- + +test('the port is a whole number up to 65535', () => { + const port = (value: unknown): number => { + const config = new AppConfig(undefined, [], '/nowhere'); + if (value !== undefined) { + config.set('rest.server.port', value); + } + return serverPort(config); + }; + assert.equal(port(undefined), 8085); + assert.equal(port(9000), 9000); + assert.equal(port('9000'), 9000); + assert.equal(port(' 9000 '), 9000); + assert.equal(port(9000.0), 9000); + assert.equal(port(0), 0); + assert.equal(port(65535), 65535); + for (const value of ['80_85', '8085.0', '+8085', '0x1F95', '\u0668\u0660\u0668\u0665', 'http', '', 8085.5, -1, 65536, true]) { + assert.throws(() => port(value), (e: unknown) => { + assert.ok(e instanceof AppException, String(value)); + assert.equal(e.message, 'rest.server.port must be a port number from 0 to 65535', String(value)); + return true; + }, String(value)); + } +}); + +test('a time to live longer than a timer holds waits for the reply', async () => { + // 3,000,000,000 ms is more than the 2,147,483,647 a timer holds here: the wait is capped at + // that, where it was a 408 at once; a caller's header is never refused for its length + for (const ttl of ['2147483648', '3000000000', '9007199254740991']) { + const { status, reply } = await postEvent(new EventEnvelope('unit.echo', { a: 1 }), ttl); + assert.equal(status, 200, ttl); + assert.deepEqual((reply.body as Record).body, { a: 1 }, ttl); + } + // and so does a remote call with a timeout of that length, where the request was aborted at once + const po = new PostOffice(`${base}/api/event`); + for (const timeoutMs of [3000000000, 5000000000, Infinity]) { + const reply = await po.request('unit.echo', { a: 2 }, { timeoutMs }); + assert.equal(reply.getStatus(), 200, String(timeoutMs)); + } +}); + +test('the x-ttl of an event is a whole number of milliseconds', async () => { + // a value that is no whole number counts as none - the floor of a second - where each runtime's + // own number reader took 5_000 (the Python twin) or 5000ms (this pack) for five seconds + for (const ttl of ['5_000', '5000ms']) { + const { status, reply } = await postEvent(new EventEnvelope('unit.slow', {}), ttl); + assert.equal(status, 408, ttl); + assert.equal(reply.body, 'Timeout for 1000 ms', ttl); + } +}); diff --git a/test/vectors/config-vectors.json b/test/vectors/config-vectors.json new file mode 100644 index 00000000..22e570ab --- /dev/null +++ b/test/vectors/config-vectors.json @@ -0,0 +1,2409 @@ +{ + "contract": "configuration", + "version": 2, + "description": "The configuration reader's shared vectors, run by mercury-python and mercury-nodejs against the same file. scalar_cases pin how a YAML file is read: each is the text written after 'k: ' in an application.yml, with the kind of value a setting's reader gets from get (null, boolean, integer, float, text) and the text it gets from get_property / getProperty - or kind error when the file does not load. A plain scalar is resolved by the core schema of YAML 1.2.2 (section 10.3.2 of the specification), its rows tried in order: nothing, ~ and null, also capitalized or in upper case, are no value; true and false, also capitalized or in upper case, a boolean; [-+]?[0-9]+ an integer in base 10, so 010 is ten; 0o[0-7]+ an integer in base 8; 0x[0-9a-fA-F]+ an integer in base 16; a decimal number with a point or an exponent, .inf and .nan a float; anything else, and anything in quotes, text. So yes, no, on and off, a number with an underscore, in base 2 or in base 60, a date, the lone = and << are text. The expected values are the reading of a reference written from the specification, not of either pack. Under an explicit tag a scalar is valid when the core schema has the tag (!!null, !!bool, !!int, !!float, !!str) and the content is one of the tag's rows; under the non-specific tag ! it is text; a document with any other tag does not load. As text, a boolean is true or false and a float keeps its point (16000.0), written as Python writes one. key_cases pin the dotted keys of a document whose mapping keys YAML read as something other than text - the text of that value - and that << is a key like any other, since the core schema has no merge key. reference_cases pin ${name:default}: the environment variable (env; unset names the ones that must be absent), then the key of that name as a key is read - a -D override (overrides) before the file's value - then the default; a reference that leads back to a key being resolved has no value, so its default stands; a value its references leave empty is no value either, as in the Java engine, while an empty text written as one stays one; expect gives get_property per key, null for no value, read with the default a case gives for the key (defaults) - get then returns the same - and kinds the kind of get where a case names it. default_cases pin a key written without a value (key:, a YAML null): it reads as a key that is not there, as in the Java engine, so get_property returns the default given (defaults) - also through a reference to such a key. whole_number_cases, duration_cases and switch_cases pin the one rule for a number, a duration and a switch: number, ms and switch are null for a value that is none - which a setting refuses by name.", + "scalar_cases": [ + { + "yaml": "true", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "True", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "TRUE", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "false", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "False", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "FALSE", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "yes", + "kind": "text", + "text": "yes" + }, + { + "yaml": "Yes", + "kind": "text", + "text": "Yes" + }, + { + "yaml": "YES", + "kind": "text", + "text": "YES" + }, + { + "yaml": "no", + "kind": "text", + "text": "no" + }, + { + "yaml": "No", + "kind": "text", + "text": "No" + }, + { + "yaml": "NO", + "kind": "text", + "text": "NO" + }, + { + "yaml": "on", + "kind": "text", + "text": "on" + }, + { + "yaml": "On", + "kind": "text", + "text": "On" + }, + { + "yaml": "ON", + "kind": "text", + "text": "ON" + }, + { + "yaml": "off", + "kind": "text", + "text": "off" + }, + { + "yaml": "Off", + "kind": "text", + "text": "Off" + }, + { + "yaml": "OFF", + "kind": "text", + "text": "OFF" + }, + { + "yaml": "y", + "kind": "text", + "text": "y" + }, + { + "yaml": "Y", + "kind": "text", + "text": "Y" + }, + { + "yaml": "n", + "kind": "text", + "text": "n" + }, + { + "yaml": "N", + "kind": "text", + "text": "N" + }, + { + "yaml": "tRue", + "kind": "text", + "text": "tRue" + }, + { + "yaml": "yEs", + "kind": "text", + "text": "yEs" + }, + { + "yaml": "oN", + "kind": "text", + "text": "oN" + }, + { + "yaml": "fALSE", + "kind": "text", + "text": "fALSE" + }, + { + "yaml": "~", + "kind": "null", + "text": null + }, + { + "yaml": "null", + "kind": "null", + "text": null + }, + { + "yaml": "Null", + "kind": "null", + "text": null + }, + { + "yaml": "NULL", + "kind": "null", + "text": null + }, + { + "yaml": "", + "kind": "null", + "text": null + }, + { + "yaml": "nULL", + "kind": "text", + "text": "nULL" + }, + { + "yaml": "none", + "kind": "text", + "text": "none" + }, + { + "yaml": "None", + "kind": "text", + "text": "None" + }, + { + "yaml": "nil", + "kind": "text", + "text": "nil" + }, + { + "yaml": "0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "1", + "kind": "integer", + "text": "1" + }, + { + "yaml": "16000", + "kind": "integer", + "text": "16000" + }, + { + "yaml": "-5", + "kind": "integer", + "text": "-5" + }, + { + "yaml": "+5", + "kind": "integer", + "text": "5" + }, + { + "yaml": "16_000", + "kind": "text", + "text": "16_000" + }, + { + "yaml": "1_000", + "kind": "text", + "text": "1_000" + }, + { + "yaml": "010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "0o10", + "kind": "integer", + "text": "8" + }, + { + "yaml": "0O10", + "kind": "text", + "text": "0O10" + }, + { + "yaml": "0x10", + "kind": "integer", + "text": "16" + }, + { + "yaml": "0X10", + "kind": "text", + "text": "0X10" + }, + { + "yaml": "0b101", + "kind": "text", + "text": "0b101" + }, + { + "yaml": "0B101", + "kind": "text", + "text": "0B101" + }, + { + "yaml": "08", + "kind": "integer", + "text": "8" + }, + { + "yaml": "09", + "kind": "integer", + "text": "9" + }, + { + "yaml": "00", + "kind": "integer", + "text": "0" + }, + { + "yaml": "-010", + "kind": "integer", + "text": "-10" + }, + { + "yaml": "+010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "0_", + "kind": "text", + "text": "0_" + }, + { + "yaml": "_1", + "kind": "text", + "text": "_1" + }, + { + "yaml": "1_", + "kind": "text", + "text": "1_" + }, + { + "yaml": "1__0", + "kind": "text", + "text": "1__0" + }, + { + "yaml": "9007199254740991", + "kind": "integer", + "text": "9007199254740991" + }, + { + "yaml": "9007199254740992", + "kind": "integer", + "text": "9007199254740992" + }, + { + "yaml": "9007199254740993", + "kind": "integer", + "text": "9007199254740993" + }, + { + "yaml": "-9007199254740993", + "kind": "integer", + "text": "-9007199254740993" + }, + { + "yaml": "12345678901234567890", + "kind": "integer", + "text": "12345678901234567890" + }, + { + "yaml": "-0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "+0", + "kind": "integer", + "text": "0" + }, + { + "yaml": "0x_10", + "kind": "text", + "text": "0x_10" + }, + { + "yaml": "0xFF_FF", + "kind": "text", + "text": "0xFF_FF" + }, + { + "yaml": "0xff", + "kind": "integer", + "text": "255" + }, + { + "yaml": "-0x10", + "kind": "text", + "text": "-0x10" + }, + { + "yaml": "0b1_0", + "kind": "text", + "text": "0b1_0" + }, + { + "yaml": "0x", + "kind": "text", + "text": "0x" + }, + { + "yaml": "0b", + "kind": "text", + "text": "0b" + }, + { + "yaml": "007", + "kind": "integer", + "text": "7" + }, + { + "yaml": "0_7", + "kind": "text", + "text": "0_7" + }, + { + "yaml": "1 000", + "kind": "text", + "text": "1 000" + }, + { + "yaml": "1:30", + "kind": "text", + "text": "1:30" + }, + { + "yaml": "1:30:00", + "kind": "text", + "text": "1:30:00" + }, + { + "yaml": "-1:30", + "kind": "text", + "text": "-1:30" + }, + { + "yaml": "+1:30", + "kind": "text", + "text": "+1:30" + }, + { + "yaml": "190:20:30", + "kind": "text", + "text": "190:20:30" + }, + { + "yaml": "1:60", + "kind": "text", + "text": "1:60" + }, + { + "yaml": "01:30", + "kind": "text", + "text": "01:30" + }, + { + "yaml": "1:5", + "kind": "text", + "text": "1:5" + }, + { + "yaml": "1:05", + "kind": "text", + "text": "1:05" + }, + { + "yaml": "1:30.5", + "kind": "text", + "text": "1:30.5" + }, + { + "yaml": "1:30.", + "kind": "text", + "text": "1:30." + }, + { + "yaml": "0:0", + "kind": "text", + "text": "0:0" + }, + { + "yaml": "1:30:", + "kind": "error", + "text": null + }, + { + "yaml": "1:2:3:4", + "kind": "text", + "text": "1:2:3:4" + }, + { + "yaml": "1.5", + "kind": "float", + "text": "1.5" + }, + { + "yaml": "16000.0", + "kind": "float", + "text": "16000.0" + }, + { + "yaml": "1.", + "kind": "float", + "text": "1.0" + }, + { + "yaml": ".5", + "kind": "float", + "text": "0.5" + }, + { + "yaml": "-.5", + "kind": "float", + "text": "-0.5" + }, + { + "yaml": "+.5", + "kind": "float", + "text": "0.5" + }, + { + "yaml": "1e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1E3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.0E+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e-3", + "kind": "float", + "text": "0.001" + }, + { + "yaml": "1.5e3", + "kind": "float", + "text": "1500.0" + }, + { + "yaml": ".5e3", + "kind": "float", + "text": "500.0" + }, + { + "yaml": ".5e+3", + "kind": "float", + "text": "500.0" + }, + { + "yaml": "1_000.5", + "kind": "text", + "text": "1_000.5" + }, + { + "yaml": "1_0.0_1", + "kind": "text", + "text": "1_0.0_1" + }, + { + "yaml": ".inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".Inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".INF", + "kind": "float", + "text": "inf" + }, + { + "yaml": "-.inf", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "+.inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": ".nan", + "kind": "float", + "text": "nan" + }, + { + "yaml": ".NaN", + "kind": "float", + "text": "nan" + }, + { + "yaml": ".NAN", + "kind": "float", + "text": "nan" + }, + { + "yaml": "inf", + "kind": "text", + "text": "inf" + }, + { + "yaml": "nan", + "kind": "text", + "text": "nan" + }, + { + "yaml": "Infinity", + "kind": "text", + "text": "Infinity" + }, + { + "yaml": "NaN", + "kind": "text", + "text": "NaN" + }, + { + "yaml": "0.0", + "kind": "float", + "text": "0.0" + }, + { + "yaml": "-0.0", + "kind": "float", + "text": "-0.0" + }, + { + "yaml": "1.0", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "1.10", + "kind": "float", + "text": "1.1" + }, + { + "yaml": "100000000000000000000.0", + "kind": "float", + "text": "1e+20" + }, + { + "yaml": "0.1", + "kind": "float", + "text": "0.1" + }, + { + "yaml": "1e400", + "kind": "float", + "text": "inf" + }, + { + "yaml": "1.0e+400", + "kind": "float", + "text": "inf" + }, + { + "yaml": "0.000001", + "kind": "float", + "text": "1e-06" + }, + { + "yaml": "0.00001", + "kind": "float", + "text": "1e-05" + }, + { + "yaml": "1.5E+10", + "kind": "float", + "text": "15000000000.0" + }, + { + "yaml": "+1.5", + "kind": "float", + "text": "1.5" + }, + { + "yaml": "1.e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1.e+3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "1e", + "kind": "text", + "text": "1e" + }, + { + "yaml": "1.5e", + "kind": "text", + "text": "1.5e" + }, + { + "yaml": ".", + "kind": "text", + "text": "." + }, + { + "yaml": "..", + "kind": "text", + "text": ".." + }, + { + "yaml": "-.", + "kind": "text", + "text": "-." + }, + { + "yaml": "1.2.3", + "kind": "text", + "text": "1.2.3" + }, + { + "yaml": "12345678901234567.0", + "kind": "float", + "text": "1.2345678901234568e+16" + }, + { + "yaml": "1e16", + "kind": "float", + "text": "1e+16" + }, + { + "yaml": "1.0e+16", + "kind": "float", + "text": "1e+16" + }, + { + "yaml": "0.1e+1", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "123456789012345680000.0", + "kind": "float", + "text": "1.2345678901234568e+20" + }, + { + "yaml": "1.0e-5", + "kind": "float", + "text": "1e-05" + }, + { + "yaml": "1.0e-7", + "kind": "float", + "text": "1e-07" + }, + { + "yaml": "4.0e+15", + "kind": "float", + "text": "4000000000000000.0" + }, + { + "yaml": "1.0e+15", + "kind": "float", + "text": "1000000000000000.0" + }, + { + "yaml": "9007199254740993.0", + "kind": "float", + "text": "9007199254740992.0" + }, + { + "yaml": "2026-11-30", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "2026-11-30T10:00:00Z", + "kind": "text", + "text": "2026-11-30T10:00:00Z" + }, + { + "yaml": "2026-11-30 10:00:00", + "kind": "text", + "text": "2026-11-30 10:00:00" + }, + { + "yaml": "2026-11-30T10:00:00+08:00", + "kind": "text", + "text": "2026-11-30T10:00:00+08:00" + }, + { + "yaml": "2026-11-30t10:00:00.5Z", + "kind": "text", + "text": "2026-11-30t10:00:00.5Z" + }, + { + "yaml": "2026-1-1", + "kind": "text", + "text": "2026-1-1" + }, + { + "yaml": "2026-13-45", + "kind": "text", + "text": "2026-13-45" + }, + { + "yaml": "2026-11-30T10:00:00", + "kind": "text", + "text": "2026-11-30T10:00:00" + }, + { + "yaml": "2026-11-30 10:00:00 +8", + "kind": "text", + "text": "2026-11-30 10:00:00 +8" + }, + { + "yaml": "2026-11-30T10:00:00.123456789Z", + "kind": "text", + "text": "2026-11-30T10:00:00.123456789Z" + }, + { + "yaml": "2026-02-30", + "kind": "text", + "text": "2026-02-30" + }, + { + "yaml": "10:00:00", + "kind": "text", + "text": "10:00:00" + }, + { + "yaml": "2026-11", + "kind": "text", + "text": "2026-11" + }, + { + "yaml": "20261130", + "kind": "integer", + "text": "20261130" + }, + { + "yaml": "'yes'", + "kind": "text", + "text": "yes" + }, + { + "yaml": "\"yes\"", + "kind": "text", + "text": "yes" + }, + { + "yaml": "'true'", + "kind": "text", + "text": "true" + }, + { + "yaml": "\"16000\"", + "kind": "text", + "text": "16000" + }, + { + "yaml": "'1e3'", + "kind": "text", + "text": "1e3" + }, + { + "yaml": "\"\"", + "kind": "text", + "text": "" + }, + { + "yaml": "''", + "kind": "text", + "text": "" + }, + { + "yaml": "'it''s'", + "kind": "text", + "text": "it's" + }, + { + "yaml": "\"tab\\t\"", + "kind": "text", + "text": "tab\t" + }, + { + "yaml": "\"\\u00e9\"", + "kind": "text", + "text": "é" + }, + { + "yaml": "' 5 '", + "kind": "text", + "text": " 5 " + }, + { + "yaml": "\"010\"", + "kind": "text", + "text": "010" + }, + { + "yaml": "'~'", + "kind": "text", + "text": "~" + }, + { + "yaml": "'null'", + "kind": "text", + "text": "null" + }, + { + "yaml": "'2026-11-30'", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "hello", + "kind": "text", + "text": "hello" + }, + { + "yaml": "hello world", + "kind": "text", + "text": "hello world" + }, + { + "yaml": "12abc", + "kind": "text", + "text": "12abc" + }, + { + "yaml": "1.5s", + "kind": "text", + "text": "1.5s" + }, + { + "yaml": "30s", + "kind": "text", + "text": "30s" + }, + { + "yaml": "1_0s", + "kind": "text", + "text": "1_0s" + }, + { + "yaml": "é", + "kind": "text", + "text": "é" + }, + { + "yaml": "a: b", + "kind": "error", + "text": null + }, + { + "yaml": "a:b", + "kind": "text", + "text": "a:b" + }, + { + "yaml": "http://x:80/y", + "kind": "text", + "text": "http://x:80/y" + }, + { + "yaml": "x # y", + "kind": "text", + "text": "x" + }, + { + "yaml": "x#y", + "kind": "text", + "text": "x#y" + }, + { + "yaml": "- x", + "kind": "error", + "text": null + }, + { + "yaml": "-x", + "kind": "text", + "text": "-x" + }, + { + "yaml": "?x", + "kind": "text", + "text": "?x" + }, + { + "yaml": ":x", + "kind": "text", + "text": ":x" + }, + { + "yaml": "=", + "kind": "text", + "text": "=" + }, + { + "yaml": "<<", + "kind": "text", + "text": "<<" + }, + { + "yaml": "*", + "kind": "error", + "text": null + }, + { + "yaml": "&a x", + "kind": "text", + "text": "x" + }, + { + "yaml": "!x", + "kind": "error", + "text": null + }, + { + "yaml": "%x", + "kind": "error", + "text": null + }, + { + "yaml": "@x", + "kind": "error", + "text": null + }, + { + "yaml": "`x", + "kind": "error", + "text": null + }, + { + "yaml": "|", + "kind": "text", + "text": "" + }, + { + "yaml": ">", + "kind": "text", + "text": "" + }, + { + "yaml": "a,b", + "kind": "text", + "text": "a,b" + }, + { + "yaml": "1,000", + "kind": "text", + "text": "1,000" + }, + { + "yaml": "$5", + "kind": "text", + "text": "$5" + }, + { + "yaml": "true ", + "kind": "boolean", + "text": "true" + }, + { + "yaml": " true", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "TRUE.", + "kind": "text", + "text": "TRUE." + }, + { + "yaml": "0xZZ", + "kind": "text", + "text": "0xZZ" + }, + { + "yaml": "1-2", + "kind": "text", + "text": "1-2" + }, + { + "yaml": "+", + "kind": "text", + "text": "+" + }, + { + "yaml": "-", + "kind": "error", + "text": null + }, + { + "yaml": "--", + "kind": "text", + "text": "--" + }, + { + "yaml": "0.5s", + "kind": "text", + "text": "0.5s" + }, + { + "yaml": "5 m", + "kind": "text", + "text": "5 m" + }, + { + "yaml": "!!str 123", + "kind": "text", + "text": "123" + }, + { + "yaml": "!!str yes", + "kind": "text", + "text": "yes" + }, + { + "yaml": "!!int \"123\"", + "kind": "integer", + "text": "123" + }, + { + "yaml": "!!int 1_0", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "!!float '1e3'", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "!!bool yes", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool \"true\"", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "!!null ''", + "kind": "null", + "text": null + }, + { + "yaml": "!!binary aGVsbG8=", + "kind": "error", + "text": null + }, + { + "yaml": "!!timestamp 2026-11-30", + "kind": "error", + "text": null + }, + { + "yaml": "!!set {a, b}", + "kind": "error", + "text": null + }, + { + "yaml": "!!omap [a: 1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!python/tuple [1]", + "kind": "error", + "text": null + }, + { + "yaml": "!custom x", + "kind": "error", + "text": null + }, + { + "yaml": "! 5", + "kind": "text", + "text": "5" + }, + { + "yaml": "0o17", + "kind": "integer", + "text": "15" + }, + { + "yaml": "0o", + "kind": "text", + "text": "0o" + }, + { + "yaml": "0o8", + "kind": "text", + "text": "0o8" + }, + { + "yaml": "0o1_0", + "kind": "text", + "text": "0o1_0" + }, + { + "yaml": "+0o10", + "kind": "text", + "text": "+0o10" + }, + { + "yaml": "-0o10", + "kind": "text", + "text": "-0o10" + }, + { + "yaml": "0x1f", + "kind": "integer", + "text": "31" + }, + { + "yaml": "0x1F", + "kind": "integer", + "text": "31" + }, + { + "yaml": "+0x10", + "kind": "text", + "text": "+0x10" + }, + { + "yaml": "0xG", + "kind": "text", + "text": "0xG" + }, + { + "yaml": "00x10", + "kind": "text", + "text": "00x10" + }, + { + "yaml": "0010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "-007", + "kind": "integer", + "text": "-7" + }, + { + "yaml": "1e+", + "kind": "text", + "text": "1e+" + }, + { + "yaml": "e3", + "kind": "text", + "text": "e3" + }, + { + "yaml": ".e3", + "kind": "text", + "text": ".e3" + }, + { + "yaml": "1.e-2", + "kind": "float", + "text": "0.01" + }, + { + "yaml": "-1.", + "kind": "float", + "text": "-1.0" + }, + { + "yaml": "+1.", + "kind": "float", + "text": "1.0" + }, + { + "yaml": "--1", + "kind": "text", + "text": "--1" + }, + { + "yaml": "+-1", + "kind": "text", + "text": "+-1" + }, + { + "yaml": "1+", + "kind": "text", + "text": "1+" + }, + { + "yaml": "1..0", + "kind": "text", + "text": "1..0" + }, + { + "yaml": "1e3.0", + "kind": "text", + "text": "1e3.0" + }, + { + "yaml": ".5.", + "kind": "text", + "text": ".5." + }, + { + "yaml": "+.Inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": "-.INF", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "-.nan", + "kind": "text", + "text": "-.nan" + }, + { + "yaml": "+.nan", + "kind": "text", + "text": "+.nan" + }, + { + "yaml": ".Nan", + "kind": "text", + "text": ".Nan" + }, + { + "yaml": ".iNF", + "kind": "text", + "text": ".iNF" + }, + { + "yaml": ".infinity", + "kind": "text", + "text": ".infinity" + }, + { + "yaml": "~~", + "kind": "text", + "text": "~~" + }, + { + "yaml": "Null ", + "kind": "null", + "text": null + }, + { + "yaml": "nUll", + "kind": "text", + "text": "nUll" + }, + { + "yaml": "tRUE", + "kind": "text", + "text": "tRUE" + }, + { + "yaml": "False.", + "kind": "text", + "text": "False." + }, + { + "yaml": "0b0", + "kind": "text", + "text": "0b0" + }, + { + "yaml": "1__0.5", + "kind": "text", + "text": "1__0.5" + }, + { + "yaml": "12:30:45", + "kind": "text", + "text": "12:30:45" + }, + { + "yaml": "0:30", + "kind": "text", + "text": "0:30" + }, + { + "yaml": "<<:", + "kind": "error", + "text": null + }, + { + "yaml": "= ", + "kind": "text", + "text": "=" + }, + { + "yaml": "2026-11-30 ", + "kind": "text", + "text": "2026-11-30" + }, + { + "yaml": "!!str 010", + "kind": "text", + "text": "010" + }, + { + "yaml": "!!str", + "kind": "text", + "text": "" + }, + { + "yaml": "!!int 010", + "kind": "integer", + "text": "10" + }, + { + "yaml": "!!int 0o10", + "kind": "integer", + "text": "8" + }, + { + "yaml": "!!int 0x10", + "kind": "integer", + "text": "16" + }, + { + "yaml": "!!int '0x1F'", + "kind": "integer", + "text": "31" + }, + { + "yaml": "!!int +7", + "kind": "integer", + "text": "7" + }, + { + "yaml": "!!int 1.0", + "kind": "error", + "text": null + }, + { + "yaml": "!!int 1:30", + "kind": "error", + "text": null + }, + { + "yaml": "!!int 0b11", + "kind": "error", + "text": null + }, + { + "yaml": "!!int", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1e3", + "kind": "float", + "text": "1000.0" + }, + { + "yaml": "!!float .inf", + "kind": "float", + "text": "inf" + }, + { + "yaml": "!!float -.INF", + "kind": "float", + "text": "-inf" + }, + { + "yaml": "!!float .NaN", + "kind": "float", + "text": "nan" + }, + { + "yaml": "!!float 0x10", + "kind": "error", + "text": null + }, + { + "yaml": "!!float 1_0", + "kind": "error", + "text": null + }, + { + "yaml": "!!float", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool True", + "kind": "boolean", + "text": "true" + }, + { + "yaml": "!!bool FALSE", + "kind": "boolean", + "text": "false" + }, + { + "yaml": "!!bool on", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool 1", + "kind": "error", + "text": null + }, + { + "yaml": "!!bool", + "kind": "error", + "text": null + }, + { + "yaml": "!!null", + "kind": "null", + "text": null + }, + { + "yaml": "!!null ~", + "kind": "null", + "text": null + }, + { + "yaml": "!!null Null", + "kind": "null", + "text": null + }, + { + "yaml": "!!null x", + "kind": "error", + "text": null + }, + { + "yaml": "!!null 0", + "kind": "error", + "text": null + }, + { + "yaml": "! true", + "kind": "text", + "text": "true" + }, + { + "yaml": "! 010", + "kind": "text", + "text": "010" + }, + { + "yaml": "! ~", + "kind": "text", + "text": "~" + }, + { + "yaml": "!", + "kind": "text", + "text": "" + }, + { + "yaml": "! 'x'", + "kind": "text", + "text": "x" + }, + { + "yaml": "!!merge <<", + "kind": "error", + "text": null + }, + { + "yaml": "!!value =", + "kind": "error", + "text": null + }, + { + "yaml": "!!pairs [a: 1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!seq x", + "kind": "error", + "text": null + }, + { + "yaml": "!!map x", + "kind": "error", + "text": null + }, + { + "yaml": "!!str [1]", + "kind": "error", + "text": null + }, + { + "yaml": "!!int [1]", + "kind": "error", + "text": null + }, + { + "yaml": "! 7", + "kind": "integer", + "text": "7" + }, + { + "yaml": "! 7", + "kind": "text", + "text": "7" + }, + { + "yaml": "! 7", + "kind": "float", + "text": "7.0" + }, + { + "yaml": "! 7", + "kind": "error", + "text": null + }, + { + "yaml": "!e!x 7", + "kind": "error", + "text": null + } + ], + "key_cases": [ + { + "name": "a key YAML read as a boolean, a number or null is the text of that value; a key written yes, no, on or off, with an underscore or in base 60 is that text", + "yaml": "True: a\n~: c\n8080: d\n1.0: e\n0x10: f\n010: o\n0o10: p\n1_0: q\n1:30: r\non: l\n\"quoted\": g\nplain.key: h\nFALSE:\n true: b\noff:\n yes: m\n No: n\nnested:\n 1e3: i\n 2026-11-30: j\n 12345678901234567890: k\n .inf: s\n", + "expect": { + "false.true": "b", + "off.yes": "m", + "off.No": "n", + "nested.1000.0": "i", + "nested.2026-11-30": "j", + "nested.12345678901234567890": "k", + "nested.inf": "s", + "true": "a", + "null": "c", + "8080": "d", + "1.0": "e", + "16": "f", + "10": "o", + "8": "p", + "1_0": "q", + "1:30": "r", + "on": "l", + "quoted": "g", + "plain.key": "h" + } + }, + { + "name": "a document that is not a mapping has no keys - a list", + "yaml": "- a\n- b\n", + "expect": {} + }, + { + "name": "a document that is not a mapping has no keys - a lone scalar", + "yaml": "hello\n", + "expect": {} + }, + { + "name": "a document that is not a mapping has no keys - an empty file", + "yaml": "", + "expect": {} + }, + { + "name": "a later key of a name replaces an earlier one", + "yaml": "a: 1\nb: 2\na: 3\n", + "expect": { + "a": "3", + "b": "2" + } + }, + { + "name": "two spellings of one number are one key: the later one stands", + "yaml": "8: a\n0o10: b\n0x8: c\n", + "expect": { + "8": "c" + } + }, + { + "name": "a tab is read as two spaces, as the Java engine reads a file: after a colon, as indentation", + "yaml": "a:\t1\nb:\n\tc: True\n\td:\n\t\te: 2.0\n", + "expect": { + "a": "1", + "b.c": "true", + "b.d.e": "2.0" + } + }, + { + "name": "the core schema has no merge key: << is a key like any other, and an alias is read as YAML reads it", + "yaml": "base: &base\n x: 1\n y: 2.5\nderived:\n <<: *base\n y: 3\ncopy: *base\n", + "expect": { + "base.x": "1", + "base.y": "2.5", + "derived.<<.x": "1", + "derived.<<.y": "2.5", + "derived.x": null, + "derived.y": "3", + "copy.x": "1", + "copy.y": "2.5" + } + }, + { + "name": "a %YAML 1.1 directive does not bring the older reading back", + "yaml": "%YAML 1.1\n---\na: yes\nb: 010\nc: 1_0\nd: 1:30\n", + "expect": { + "a": "yes", + "b": "10", + "c": "1_0", + "d": "1:30" + } + }, + { + "name": "a key named as something every object carries is a key like any other", + "yaml": "__proto__:\n x: 1\nconstructor: 2\ntoString: 3\n", + "expect": { + "__proto__.x": "1", + "constructor": "2", + "toString": "3" + } + } + ], + "reference_cases": [ + { + "name": "a reference sees the override of the key it names", + "file": "flag: false\nuses: ${flag:off}\ninside: 'is ${flag}'\n", + "overrides": { + "flag": "true" + }, + "expect": { + "flag": "true", + "uses": "true", + "inside": "is true" + }, + "kinds": { + "uses": "text" + } + }, + { + "name": "without an override, the file's value - as the value it is when the reference is the whole value", + "file": "flag: false\nuses: ${flag:off}\ninside: 'is ${flag}'\n", + "expect": { + "flag": "false", + "uses": "false", + "inside": "is false" + }, + "kinds": { + "uses": "boolean" + } + }, + { + "name": "an override names a key the file does not carry", + "file": "uses: ${only:none}\ninside: 'x-${only}'\n", + "overrides": { + "only": "o" + }, + "expect": { + "uses": "o", + "inside": "x-o" + } + }, + { + "name": "the environment variable wins over the override and the file", + "file": "MERCURY_VECTOR_NAME: file\nuses: ${MERCURY_VECTOR_NAME:none}\n", + "overrides": { + "MERCURY_VECTOR_NAME": "override" + }, + "env": { + "MERCURY_VECTOR_NAME": "environment" + }, + "expect": { + "uses": "environment", + "MERCURY_VECTOR_NAME": "override" + } + }, + { + "name": "the default when nothing carries the name; no value without a default", + "file": "uses: ${MERCURY_VECTOR_ABSENT:fallback}\nbare: ${MERCURY_VECTOR_ABSENT}\ninside: 'x-${MERCURY_VECTOR_ABSENT}-y'\ncolon: ${MERCURY_VECTOR_ABSENT:a:b}\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "uses": "fallback", + "bare": null, + "inside": "x--y", + "colon": "a:b" + } + }, + { + "name": "an override's own references are resolved, through the override of another key too", + "file": "b: 5\nuses: ${a}\n", + "overrides": { + "a": "${b}-${c:none}", + "c": "see" + }, + "expect": { + "a": "5-see", + "uses": "5-see" + } + }, + { + "name": "a referenced value inside a longer text is the text it reads as: a boolean, a float, a large integer", + "file": "flag: TRUE\nrate: 1.0\nbig: 12345678901234567890\nsmall: 1e-05\ninside: '${flag}/${rate}/${big}/${small}'\nwhole: ${rate}\n", + "expect": { + "inside": "true/1.0/12345678901234567890/1e-05", + "whole": "1.0" + }, + "kinds": { + "whole": "float" + } + }, + { + "name": "two keys that refer to each other: each ends at the other's default", + "file": "a: ${b:1}\nb: ${a:2}\n", + "expect": { + "a": "2", + "b": "1" + } + }, + { + "name": "a key that refers to itself has no value there: the default, or nothing", + "file": "a: ${a}\nb: ${b:d}\nc: 'x-${c}-y'\n", + "expect": { + "a": null, + "b": "d", + "c": "x--y" + } + }, + { + "name": "an override that refers to its own key takes its default, not the file's value", + "file": "port: 9000\n", + "overrides": { + "port": "${port:8080}" + }, + "expect": { + "port": "8080" + } + }, + { + "name": "a name every object carries is no environment variable and no key", + "file": "a: ${constructor:none}\nb: ${toString}\nc: ${__proto__:d}\nd: ${hasOwnProperty:e}\ne: 'x-${valueOf}-y'\n", + "unset": [ + "constructor", + "toString", + "__proto__", + "hasOwnProperty", + "valueOf" + ], + "expect": { + "a": "none", + "b": null, + "c": "d", + "d": "e", + "e": "x--y" + } + }, + { + "name": "a value its references leave empty is no value - the idiom for an optional setting - and an empty text written as one stays one", + "file": "effort: '${MERCURY_VECTOR_ABSENT:}'\nbare: ${MERCURY_VECTOR_ABSENT:}\ntwo: '${MERCURY_VECTOR_ABSENT:}${MERCURY_VECTOR_ABSENT:}'\nliteral: ''\naround: 'x${MERCURY_VECTOR_ABSENT:}'\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "effort": null, + "bare": null, + "two": null, + "literal": "", + "around": "x" + } + }, + { + "name": "a key its references leave empty reads as its default; an empty text written as one does not", + "file": "effort: '${MERCURY_VECTOR_ABSENT:}'\ntwo: '${MERCURY_VECTOR_ABSENT:}${MERCURY_VECTOR_ABSENT:}'\nliteral: ''\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "defaults": { + "effort": "medium", + "two": "dflt", + "literal": "dflt" + }, + "expect": { + "effort": "medium", + "two": "dflt", + "literal": "" + } + }, + { + "name": "a reference to a key its references leave empty takes its own default, else nothing", + "file": "inner: '${MERCURY_VECTOR_ABSENT:}'\nunset: ${MERCURY_VECTOR_ABSENT}\nuses: ${inner:fallback}\nbare: ${inner}\ninside: 'x-${inner}-y'\nthrough: ${unset:other}\n", + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "expect": { + "inner": null, + "uses": "fallback", + "bare": null, + "inside": "x--y", + "through": "other" + } + }, + { + "name": "an environment variable that is set and empty leaves the value empty: no value, and the reference's own default is not taken", + "file": "uses: ${MERCURY_VECTOR_NAME:fallback}\ninside: 'x-${MERCURY_VECTOR_NAME:fallback}'\n", + "env": { + "MERCURY_VECTOR_NAME": "" + }, + "defaults": { + "uses": "dflt", + "inside": "dflt" + }, + "expect": { + "uses": "dflt", + "inside": "x-" + } + }, + { + "name": "an override its references leave empty is no value either, and does not uncover the file's", + "file": "a: text\n", + "overrides": { + "a": "${MERCURY_VECTOR_ABSENT:}" + }, + "unset": [ + "MERCURY_VECTOR_ABSENT" + ], + "defaults": { + "a": "dflt" + }, + "expect": { + "a": "dflt" + } + } + ], + "default_cases": [ + { + "name": "a key written without a value reads as a key that is not there: its default", + "file": "a:\nb: ~\nc: null\nd: ''\ne: text\n", + "defaults": { + "a": "dflt", + "b": "dflt", + "c": "dflt", + "d": "dflt", + "e": "dflt", + "f": "dflt" + }, + "expect": { + "a": "dflt", + "b": "dflt", + "c": "dflt", + "d": "", + "e": "text", + "f": "dflt" + } + }, + { + "name": "a reference to a key without a value takes its own default, else the default of the key that holds it", + "file": "empty:\nuses: ${empty:fallback}\nbare: ${empty}\ninside: 'x-${empty}-y'\n", + "defaults": { + "uses": "dflt", + "bare": "dflt", + "inside": "dflt" + }, + "expect": { + "uses": "fallback", + "bare": "dflt", + "inside": "x--y" + } + }, + { + "name": "an override with an empty value is an empty text, not the default", + "file": "a: text\n", + "overrides": { + "a": "" + }, + "defaults": { + "a": "dflt" + }, + "expect": { + "a": "" + } + } + ], + "whole_number_cases": [ + { + "value": 0, + "number": 0 + }, + { + "value": 1, + "number": 1 + }, + { + "value": 16000, + "number": 16000 + }, + { + "value": 16000.0, + "number": 16000 + }, + { + "value": 1000.0, + "number": 1000 + }, + { + "value": "16000", + "number": 16000 + }, + { + "value": " 16000 ", + "number": 16000 + }, + { + "value": "\t16000 ", + "number": 16000 + }, + { + "value": "  7

", + "number": 7 + }, + { + "value": "007", + "number": 7 + }, + { + "value": "0", + "number": 0 + }, + { + "value": 9007199254740991, + "number": 9007199254740991 + }, + { + "value": "9007199254740991", + "number": 9007199254740991 + }, + { + "value": "0000000000000000000000009007199254740991", + "number": 9007199254740991 + }, + { + "value": 9007199254740992, + "number": null + }, + { + "value": "9007199254740992", + "number": null + }, + { + "value": "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", + "number": null + }, + { + "value": 1.5, + "number": null + }, + { + "value": -5, + "number": null + }, + { + "value": -0.0, + "number": 0 + }, + { + "value": true, + "number": null + }, + { + "value": false, + "number": null + }, + { + "value": null, + "number": null + }, + { + "value": "", + "number": null + }, + { + "value": " ", + "number": null + }, + { + "value": "12 000", + "number": null + }, + { + "value": "16_000", + "number": null + }, + { + "value": "+5", + "number": null + }, + { + "value": "-5", + "number": null + }, + { + "value": "1e3", + "number": null + }, + { + "value": "16000.0", + "number": null + }, + { + "value": "0x10", + "number": null + }, + { + "value": "12abc", + "number": null + }, + { + "value": "٣", + "number": null + }, + { + "value": "12", + "number": null + }, + { + "value": "16000…", + "number": null + }, + { + "value": "16000", + "number": null + }, + { + "value": "16000\u001c", + "number": null + }, + { + "value": [ + 1 + ], + "number": null + }, + { + "value": { + "a": 1 + }, + "number": null + } + ], + "duration_cases": [ + { + "value": "30s", + "ms": 30000 + }, + { + "value": "2m", + "ms": 120000 + }, + { + "value": "1500ms", + "ms": 1500 + }, + { + "value": "1h", + "ms": 3600000 + }, + { + "value": "2d", + "ms": 172800000 + }, + { + "value": 30, + "ms": 30000 + }, + { + "value": 30.0, + "ms": 30000 + }, + { + "value": "30", + "ms": 30000 + }, + { + "value": "0", + "ms": 0 + }, + { + "value": "0ms", + "ms": 0 + }, + { + "value": 0, + "ms": 0 + }, + { + "value": " 5s ", + "ms": 5000 + }, + { + "value": "9007199254740991ms", + "ms": 9007199254740991 + }, + { + "value": "9007199254740s", + "ms": 9007199254740000 + }, + { + "value": "9007199254741s", + "ms": null + }, + { + "value": "9007199254740991s", + "ms": null + }, + { + "value": "5 s", + "ms": null + }, + { + "value": "5S", + "ms": null + }, + { + "value": "5sec", + "ms": null + }, + { + "value": "5 ms", + "ms": null + }, + { + "value": "1_0s", + "ms": null + }, + { + "value": "٣s", + "ms": null + }, + { + "value": "1.5s", + "ms": null + }, + { + "value": "0.5s", + "ms": null + }, + { + "value": 1.5, + "ms": null + }, + { + "value": "1e3", + "ms": null + }, + { + "value": "1e3ms", + "ms": null + }, + { + "value": "-5s", + "ms": null + }, + { + "value": "+5s", + "ms": null + }, + { + "value": -1, + "ms": null + }, + { + "value": "s", + "ms": null + }, + { + "value": "ms", + "ms": null + }, + { + "value": "", + "ms": null + }, + { + "value": true, + "ms": null + }, + { + "value": null, + "ms": null + }, + { + "value": "12abc", + "ms": null + } + ], + "switch_cases": [ + { + "value": true, + "default": false, + "switch": true + }, + { + "value": false, + "default": true, + "switch": false + }, + { + "value": "true", + "default": false, + "switch": true + }, + { + "value": "TRUE", + "default": false, + "switch": true + }, + { + "value": "tRuE", + "default": false, + "switch": true + }, + { + "value": "false", + "default": true, + "switch": false + }, + { + "value": "False", + "default": true, + "switch": false + }, + { + "value": null, + "default": false, + "switch": false + }, + { + "value": null, + "default": true, + "switch": true + }, + { + "value": "", + "default": false, + "switch": false + }, + { + "value": "", + "default": true, + "switch": true + }, + { + "value": "yes", + "default": false, + "switch": null + }, + { + "value": "on", + "default": true, + "switch": null + }, + { + "value": "no", + "default": true, + "switch": null + }, + { + "value": "off", + "default": false, + "switch": null + }, + { + "value": "1", + "default": false, + "switch": null + }, + { + "value": 1, + "default": false, + "switch": null + }, + { + "value": 0, + "default": true, + "switch": null + }, + { + "value": " true ", + "default": false, + "switch": null + }, + { + "value": "true\n", + "default": false, + "switch": null + }, + { + "value": "maybe", + "default": false, + "switch": null + }, + { + "value": [ + true + ], + "default": false, + "switch": null + }, + { + "value": { + "on": true + }, + "default": false, + "switch": null + } + ] +} diff --git a/test/vectors/rest-automation-vectors.json b/test/vectors/rest-automation-vectors.json index 0ee6efb8..4f9d7542 100644 --- a/test/vectors/rest-automation-vectors.json +++ b/test/vectors/rest-automation-vectors.json @@ -1,11 +1,12 @@ { "contract": "rest-automation", - "version": 3, - "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). A flag of an entry (tracing, stream, upload) is true or false as the Java engine reads it - the boolean, or the text in any letter case, which is what a ${NAME:default} reference resolves to; no value and an empty one are off; any other value is refused by name. timeout_cases pin the duration grammar and its clamp. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", + "version": 5, + "description": "REST automation's shared vectors (RFC-0018 in mercury-composable): the pure half of the HTTP edge, run by mercury-python and mercury-nodejs against the same file. load_cases pin the rest.yaml parser - the entries, cors, headers and static-content blocks it accepts and the exact message of every refusal, the engines' messages plus the pack's own refusals of a flow binding, the HTTP relay and the A/B dual service; an upload entry is accepted and its files ride the request map (the engines' keys plus the bytes in contents, the pack's bounded form). A flag of an entry (tracing, stream, upload) is true or false as the Java engine reads it - the boolean, or the text in any letter case, which is what a ${NAME:default} reference resolves to; no value and an empty one are off; any other value is refused by name. A rest.yaml is read as application.yml is, by the core schema of YAML 1.2.2: a boolean is true or false, also capitalized or in upper case - yes, no, on and off are text, so a flag written that way is refused - 1e3, 0x1E and 0o17 are numbers and 010 is ten, 1_0, 1:30 and 0b1010 are text, and a date is the text as written. timeout_cases pin an entry's timeout - a whole number of seconds or such a number and, right after it, one of ms, s, m, h, d, clamped to 1 s - 5 min - with ms null for a value that is no duration, which fails the load by name. match_cases pin the URL matching and its precedence over the 'basic' table (404 when no entry matches, 405 when the path matches under another method). header_transform_cases pin keep, drop and add. body_cases pin the request-body dispatch by content type, query_cases and cookie_cases the request parsing, negotiation_cases and stream_negotiation_cases the Accept rules, request_model_cases the AsyncHttpRequest map an edge builds and request_read_cases and upload_read_cases its accessors (file bytes travel as contents_base64 in this file), a name every object of the Node.js twin carries (__proto__, constructor, toString) being a name like any other in every map of a request and of a reply, upload_cases the pack's own reader of a multipart/form-data body - the files and the text fields it takes of a body (body as text, or body_base64 where it is not UTF-8) within a bound (16777216 when a case names none), a name or a filename in the extended form of RFC 5987 (name*, filename*) included, or the status and the message of its refusal - response_cases the mapping of a reply envelope to the status, header lines and body of the HTTP response, render_cases and stream_text_cases the payload rendering, error_body_cases the error shape. Header names are compared case-insensitively and header lines as a sorted list. No server is started by these cases; the edge is tested by each pack over HTTP.", "tables": { "basic": "rest:\n - service: \"greeting.api\"\n methods: ['GET']\n url: \"/api/greeting/{user}\"\n timeout: 10s\n cors: cors_1\n headers: header_1\n tracing: true\n - service: \"catch.all\"\n methods: ['GET', 'POST']\n url: \"/api/files/*\"\n - service: \"exact.match\"\n methods: ['GET']\n url: \"/api/greeting/system\"\n - service: \"version.ping\"\n methods: ['GET']\n url: \"/api/v*/ping\"\n - service: \"mid.any\"\n methods: ['GET']\n url: \"/api/mid/*/end\"\n - service: \"secure.api\"\n methods: ['POST']\n url: \"/api/secure\"\n authentication: \"api.key.check\"\n stream: true\n trace.id.header: 'X-Legacy-Trace'\n correlation.id.header: 'X-Legacy-Cid'\n traceparent.header: 'X-Trace-Context'\ncors:\n - id: cors_1\n options:\n - \"Access-Control-Allow-Origin: *\"\n - \"Access-Control-Allow-Methods: GET, POST, OPTIONS\"\n headers:\n - \"Access-Control-Allow-Origin: *\"\nheaders:\n - id: header_1\n request:\n drop: ['x-secret']\n response:\n add: [\"x-served-by: mercury\"]\nstatic-content:\n no-cache-pages: [\"/\", \"/index.html\", \"/app/*\"]\n filter:\n path: [\"/\", \"/assets/*\", \"*.html\"]\n exclusion: [\"*.css\"]\n service: \"http.request.filter\"\n", "defaults": "rest:\n - service: \"event.api.service\"\n methods: ['POST']\n url: \"/api/event\"\n timeout: 60s\n tracing: true\n - service: \"info.actuator.service\"\n methods: ['GET']\n url: \"/info\"\n timeout: 10s\n - service: \"routes.actuator.service\"\n methods: ['GET']\n url: \"/info/routes\"\n timeout: 10s\n - service: \"env.actuator.service\"\n methods: ['GET']\n url: \"/env\"\n timeout: 10s\n - service: \"health.actuator.service\"\n methods: ['GET']\n url: \"/health\"\n timeout: 30s\n - service: \"liveness.actuator.service\"\n methods: ['GET']\n url: \"/livenessprobe\"\n timeout: 10s\n", - "minimal": "rest:\n - service: x.y\n methods: ['get', 'Post']\n url: /a\n" + "minimal": "rest:\n - service: x.y\n methods: ['get', 'Post']\n url: /a\n", + "names": "rest:\n - service: \"names.api\"\n methods: ['GET']\n url: \"/names/{__proto__}/{constructor}/{toString}\"\n" }, "load_cases": [ { @@ -514,8 +515,8 @@ } }, { - "name": "the YAML 1.1 booleans turn a flag on and off: yes and on, no and off", - "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: yes\n stream: on\n upload: Yes\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: no\n stream: off\n upload: OFF\n", + "name": "a boolean is true or false, also capitalized or in upper case", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: True\n stream: TRUE\n upload: true\n - service: x.z\n methods: ['POST']\n url: /b\n tracing: False\n stream: FALSE\n upload: false\n", "routes": [ { "service": "x.y", @@ -560,6 +561,26 @@ "filter": null } }, + { + "name": "yes is text, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: yes\n", + "error": "rest[0] 'tracing' must be true or false" + }, + { + "name": "on is text, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n stream: on\n", + "error": "rest[0] 'stream' must be true or false" + }, + { + "name": "no is text, in any letter case, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: No\n", + "error": "rest[0] 'upload' must be true or false" + }, + { + "name": "off is text, in any letter case, never a boolean - so a flag written that way is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: OFF\n", + "error": "rest[0] 'tracing' must be true or false" + }, { "name": "a flag with no value, or an empty one, is off", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing:\n stream: \"\"\n upload: ~\n", @@ -621,12 +642,12 @@ "error": "rest[0] 'tracing' must be true or false" }, { - "name": "the letter y is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "name": "the letter y is text, never a boolean - so it is refused", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: y\n", "error": "rest[0] 'tracing' must be true or false" }, { - "name": "the letter n is text, as PyYAML and SnakeYAML read it, never a boolean - so it is refused", + "name": "the letter n is text, never a boolean - so it is refused", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n upload: n\n", "error": "rest[0] 'upload' must be true or false" }, @@ -644,6 +665,219 @@ "name": "an unknown cors id is found before a flag at fault", "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: maybe\n cors: nope\n", "error": "rest[0] unknown cors id 'nope'" + }, + { + "name": "a timeout that is no duration is refused by name", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: soon\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a reference that did not resolve", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: ${TIMEOUT}\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - text with an underscore between its digits", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: '1_0s'\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a fraction", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1.5\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout that is no duration is refused by name - a boolean", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: true\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "the index tells which entry's timeout is at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 10s\n - service: x.z\n methods: ['GET']\n url: /b\n timeout: 10 s\n", + "error": "rest[1] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "an unknown headers id is found before a timeout at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: soon\n headers: nope\n", + "error": "rest[0] unknown headers id 'nope'" + }, + { + "name": "a timeout at fault is found before a flag at fault", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n tracing: maybe\n timeout: soon\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a timeout with no value is the default; one with a unit the engines take is clamped as they clamp it", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout:\n - service: x.z\n methods: ['GET']\n url: /b\n timeout: 2h\n", + "routes": [ + { + "service": "x.y", + "methods": [ + "POST" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.z", + "methods": [ + "GET" + ], + "url": "/b", + "timeout_ms": 300000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "the file is read by the core schema of YAML 1.2.2: 1e3 is a number, 0x1E is thirty, 0o17 is fifteen and 010 is ten", + "yaml": "rest:\n - service: x.s0\n methods: ['GET']\n url: /n0\n timeout: 1e3\n - service: x.s1\n methods: ['GET']\n url: /n1\n timeout: 0x1E\n - service: x.s2\n methods: ['GET']\n url: /n2\n timeout: 0o17\n - service: x.s3\n methods: ['GET']\n url: /n3\n timeout: 010\n", + "routes": [ + { + "service": "x.s0", + "methods": [ + "GET" + ], + "url": "/n0", + "timeout_ms": 300000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s1", + "methods": [ + "GET" + ], + "url": "/n1", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s2", + "methods": [ + "GET" + ], + "url": "/n2", + "timeout_ms": 15000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + }, + { + "service": "x.s3", + "methods": [ + "GET" + ], + "url": "/n3", + "timeout_ms": 10000, + "cors": null, + "headers": null, + "authentication": null, + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } + }, + { + "name": "a number with an underscore between its digits is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1_0\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a number in base 60 is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 1:30\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a number in base 2 is text in YAML 1.2.2, and no duration", + "yaml": "rest:\n - service: x.y\n methods: ['POST']\n url: /a\n timeout: 0b1010\n", + "error": "rest[0] 'timeout' must be a duration such as 30s, 2m or 1500ms (seconds, ms, s, m, h, d)" + }, + { + "name": "a date is the text as written", + "yaml": "rest:\n - service: 2026-11-30\n methods: ['GET']\n url: /a\n authentication: 2026-11-30T10:00:00Z\n", + "routes": [ + { + "service": "2026-11-30", + "methods": [ + "GET" + ], + "url": "/a", + "timeout_ms": 30000, + "cors": null, + "headers": null, + "authentication": "2026-11-30T10:00:00Z", + "tracing": false, + "stream": false, + "upload": false, + "trace_id_header": null, + "correlation_id_header": null, + "traceparent_header": null + } + ], + "static": { + "no_cache_pages": [ + "/", + "/index.html" + ], + "filter": null + } } ], "timeout_cases": [ @@ -667,13 +901,21 @@ "value": "0s", "ms": 1000 }, + { + "value": "0", + "ms": 1000 + }, { "value": "30m", "ms": 300000 }, { - "value": "garbage", - "ms": 30000 + "value": "1h", + "ms": 300000 + }, + { + "value": "1d", + "ms": 300000 }, { "value": null, @@ -684,16 +926,124 @@ "ms": 10000 }, { - "value": " 5 s ", + "value": "30", + "ms": 30000 + }, + { + "value": 30.0, + "ms": 30000 + }, + { + "value": 1000.0, + "ms": 300000 + }, + { + "value": " 5s ", + "ms": 5000 + }, + { + "value": "\t5s ", "ms": 5000 }, + { + "value": "9007199254740991ms", + "ms": 300000 + }, + { + "value": "garbage", + "ms": null + }, + { + "value": "", + "ms": null + }, + { + "value": " 5 s ", + "ms": null + }, + { + "value": "5 s", + "ms": null + }, + { + "value": "5S", + "ms": null + }, + { + "value": "5sec", + "ms": null + }, { "value": "-5s", - "ms": 30000 + "ms": null + }, + { + "value": "+5s", + "ms": null + }, + { + "value": -5, + "ms": null + }, + { + "value": "1_0s", + "ms": null + }, + { + "value": "٣s", + "ms": null + }, + { + "value": "10s", + "ms": null + }, + { + "value": "1e3", + "ms": null + }, + { + "value": "1.5s", + "ms": null + }, + { + "value": 10.5, + "ms": null + }, + { + "value": "5s…", + "ms": null + }, + { + "value": "5s", + "ms": null }, { "value": true, - "ms": 30000 + "ms": null + }, + { + "value": false, + "ms": null + }, + { + "value": [ + 30 + ], + "ms": null + }, + { + "value": { + "seconds": 30 + }, + "ms": null + }, + { + "value": 9007199254740992, + "ms": null + }, + { + "value": "9007199254740991s", + "ms": null } ], "match_cases": [ @@ -801,6 +1151,18 @@ "path": "/api/secure", "service": "secure.api", "params": {} + }, + { + "table": "names", + "name": "a path parameter named as something every object of the Node.js twin carries is a parameter like any other", + "method": "GET", + "path": "/names/one/two/three", + "service": "names.api", + "params": { + "__proto__": "one", + "constructor": "two", + "toString": "three" + } } ], "header_transform_cases": [ @@ -887,8 +1249,55 @@ "expect": { "accept": "*/*" } - } - ], + }, + { + "name": "a header named as something every object of the Node.js twin carries is dropped and added like any other", + "transform": { + "drop": [ + "toString" + ], + "add": [ + [ + "valueOf", + "v" + ], + [ + "__proto__", + "added" + ] + ] + }, + "headers": { + "__proto__": "p", + "constructor": "c", + "tostring": "t" + }, + "expect": { + "constructor": "c", + "valueOf": "v", + "__proto__": "added" + } + }, + { + "name": "a header named as something every object of the Node.js twin carries is kept like any other", + "transform": { + "keep": [ + "__PROTO__", + "Constructor" + ] + }, + "headers": { + "__proto__": "p", + "constructor": "c", + "tostring": "t", + "x-noise": "1" + }, + "expect": { + "__proto__": "p", + "constructor": "c" + } + } + ], "body_cases": [ { "name": "json object, charset ignored", @@ -989,6 +1398,33 @@ "body": "{\"a\":1}", "kind": "bytes", "value": "{\"a\":1}" + }, + { + "name": "a form field named as something every object of the Node.js twin carries is a field like any other", + "content_type": "application/x-www-form-urlencoded", + "body": "__proto__=p&constructor=c&toString=t&hasOwnProperty=h&valueOf=v&a=1", + "kind": "form", + "value": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } + }, + { + "name": "a JSON key named as something every object of the Node.js twin carries is a key like any other", + "content_type": "application/json", + "body": "{\"__proto__\": {\"x\": 1}, \"constructor\": \"c\", \"toString\": null}", + "kind": "value", + "value": { + "__proto__": { + "x": 1 + }, + "constructor": "c", + "toString": null + } } ], "query_cases": [ @@ -1041,6 +1477,31 @@ "c" ] } + }, + { + "query": "__proto__=p&constructor=c&toString=t&hasOwnProperty=h&valueOf=v&a=1", + "expect": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } + }, + { + "query": "constructor=c1&constructor=c2&__proto__=p1&__proto__=p2&__proto__=p3", + "expect": { + "constructor": [ + "c1", + "c2" + ], + "__proto__": [ + "p1", + "p2", + "p3" + ] + } } ], "cookie_cases": [ @@ -1068,6 +1529,17 @@ "expect": { "a": "b=c" } + }, + { + "header": "__proto__=p; constructor=c; toString=t; hasOwnProperty=h; valueOf=v; a=1", + "expect": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v", + "a": "1" + } } ], "negotiation_cases": [ @@ -1290,6 +1762,95 @@ "path": {} } } + }, + { + "name": "a header, a path and a query parameter, a cookie and a session key named as something every object of the Node.js twin carries", + "build": { + "method": "GET", + "url": "/x", + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + }, + "map": { + "method": "GET", + "url": "/x", + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "parameters": { + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + } + } } ], "request_read_cases": [ @@ -1325,129 +1886,1052 @@ "user": "eric" } } - }, - "expect": { - "method": "GET", - "url": "/api/greeting/eric", - "path_parameter.user": "eric", - "query_parameter.q": "a", - "query_parameters.q": [ - "a", - "b" - ], - "query_parameter.lang": "fr", - "query_parameters.missing": [], - "header.accept": "*/*", - "header.ACCEPT": "*/*", - "cookie.first": "alpha", - "session_info.user": "demo", - "remote_ip": "127.0.0.1", - "is_secure": true, - "timeout_seconds": 10, - "query_string": "lang=fr&q=a&q=b", - "body": null + }, + "expect": { + "method": "GET", + "url": "/api/greeting/eric", + "path_parameter.user": "eric", + "query_parameter.q": "a", + "query_parameters.q": [ + "a", + "b" + ], + "query_parameter.lang": "fr", + "query_parameters.missing": [], + "header.accept": "*/*", + "header.ACCEPT": "*/*", + "cookie.first": "alpha", + "session_info.user": "demo", + "remote_ip": "127.0.0.1", + "is_secure": true, + "timeout_seconds": 10, + "query_string": "lang=fr&q=a&q=b", + "body": null + } + }, + { + "name": "x-ttl wins over the entry's timeout; defaults for what is absent", + "map": { + "headers": { + "x-ttl": "1500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "method": "GET", + "url": "/", + "timeout_seconds": 1, + "is_secure": false, + "path_parameter.user": null, + "query_parameter.q": null, + "header.accept": null, + "cookie.first": null, + "session_info.user": null, + "remote_ip": null, + "query_string": null, + "body": null + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - an underscore between digits", + "map": { + "headers": { + "x-ttl": "1_500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - a sign", + "map": { + "headers": { + "x-ttl": "+1500" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl that is no whole number leaves the entry's timeout - a digit of another script", + "map": { + "headers": { + "x-ttl": "١٥٠٠" + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 10 + } + }, + { + "name": "an x-ttl with white space around its digits is that number", + "map": { + "headers": { + "x-ttl": " 2500 " + }, + "timeout": 10, + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "timeout_seconds": 2 + } + }, + { + "name": "the accessors read a name that is something every object of the Node.js twin carries as any other name", + "map": { + "headers": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "cookies": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "session": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "parameters": { + "query": { + "__proto__": "p", + "constructor": [ + "c1", + "c2" + ], + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + }, + "path": { + "__proto__": "p", + "constructor": "c", + "toString": "t", + "hasOwnProperty": "h", + "valueOf": "v" + } + } + }, + "expect": { + "header.__proto__": "p", + "header.constructor": "c", + "header.TOSTRING": "t", + "cookie.__proto__": "p", + "cookie.constructor": "c", + "session_info.__proto__": "p", + "session_info.valueOf": "v", + "query_parameter.__proto__": "p", + "query_parameter.constructor": "c1", + "query_parameters.constructor": [ + "c1", + "c2" + ], + "query_parameters.__proto__": [ + "p" + ], + "path_parameter.__proto__": "p", + "path_parameter.hasOwnProperty": "h" + } + }, + { + "name": "a name every object of the Node.js twin carries, which a request does not hold, reads as any name it does not hold", + "map": { + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "header.constructor": null, + "header.__proto__": null, + "cookie.constructor": null, + "cookie.__proto__": null, + "session_info.valueOf": null, + "session_info.__proto__": null, + "query_parameter.constructor": null, + "query_parameter.__proto__": null, + "query_parameters.toString": [], + "query_parameters.__proto__": [], + "path_parameter.hasOwnProperty": null, + "path_parameter.__proto__": null + } + } + ], + "upload_read_cases": [ + { + "name": "the files of an upload through the accessors", + "map": { + "method": "POST", + "url": "/api/upload", + "filename": [ + "a.pdf", + "b.png" + ], + "file_type": [ + "application/pdf", + "image/png" + ], + "file_length": [ + 9, + 8 + ], + "size": 17, + "upload": [ + "doc", + "image" + ], + "contents_base64": [ + "JVBERi0xLjQg", + "iVBORw0KGgo=" + ], + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "is_file": true, + "content_length": 17, + "upload_tags": [ + "doc", + "image" + ], + "files": [ + { + "name": "a.pdf", + "content_type": "application/pdf", + "size": 9, + "tag": "doc", + "content_base64": "JVBERi0xLjQg" + }, + { + "name": "b.png", + "content_type": "image/png", + "size": 8, + "tag": "image", + "content_base64": "iVBORw0KGgo=" + } + ] + } + }, + { + "name": "no upload: no files, no size", + "map": { + "method": "GET", + "url": "/x", + "parameters": { + "query": {}, + "path": {} + } + }, + "expect": { + "is_file": false, + "content_length": null, + "upload_tags": [], + "files": [] + } + } + ], + "upload_cases": [ + { + "name": "a browser's form: text fields and a file with its type", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nQuarterly report\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé ☕\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.pdf\"\r\nContent-Type: application/pdf\r\n\r\n%PDF-1.4 data\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "report.pdf", + "content_type": "application/pdf", + "size": 13, + "tag": "doc", + "content_base64": "JVBERi0xLjQgZGF0YQ==" + } + ], + "fields": { + "title": "Quarterly report", + "note": "café ☕" + } + }, + { + "name": "a file's bytes are the bytes that arrived, line ends and all", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImltYWdlIjsgZmlsZW5hbWU9ImEucG5nIg0KQ29udGVudC1UeXBlOiBpbWFnZS9wbmcNCg0KiVBORw0KGgoA/w0KLS1YYk91TmRBcll4LS0NCg==", + "files": [ + { + "name": "a.png", + "content_type": "image/png", + "size": 10, + "tag": "image", + "content_base64": "iVBORw0KGgoA/w==" + } + ], + "fields": {} + }, + { + "name": "a file without a content type is application/octet-stream", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"notes.txt\"\r\n\r\nplain words\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "notes.txt", + "content_type": "application/octet-stream", + "size": 11, + "tag": "doc", + "content_base64": "cGxhaW4gd29yZHM=" + } + ], + "fields": {} + }, + { + "name": "a file input left empty is a file with an empty name and no bytes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nnone attached\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" + } + ], + "fields": { + "title": "none attached" + } + }, + { + "name": "a field named _charset_ is a field like any other, also when it comes first", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"_charset_\"\r\n\r\nutf-8\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "_charset_": "utf-8", + "note": "café" + } + }, + { + "name": "a quote and the line ends in a field name and a filename arrive as %22, %0A and %0D", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a%22b%0D%0Ac\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"say %22hi%22.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "say \"hi\".txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "a\"b\r\nc": "x" + } + }, + { + "name": "no other percent sequence is unescaped, and a backslash is a backslash", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a%20b\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"C:\\dir\\my%2Ffile.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "C:\\dir\\my%2Ffile.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "a%20b": "x" + } + }, + { + "name": "a parameter value may be bare, up to the next semicolon", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=note\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=doc; filename=a.txt\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": { + "note": "x" + } + }, + { + "name": "blanks around the parameters, a trailing semicolon, parameters in any order and of any case", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\ncontent-disposition: FORM-DATA ; FileName=\"a.txt\" ;NAME=\"doc\" ; \r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a parameter the reader does not know is passed over, and the first of a name stands", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; size=3; name=\"one\"; name=\"two\"\r\n\r\nabc\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "one": "abc" + } + }, + { + "name": "a header the reader does not know is passed over, and the first of a name stands", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nX-Custom: 1\r\nContent-Disposition: form-data; name=\"one\"\r\nContent-Disposition: form-data; name=\"two\"\r\n\r\nabc\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "one": "abc" + } + }, + { + "name": "a later field of a name replaces an earlier one", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"tag\"\r\n\r\nfirst\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"tag\"\r\n\r\nsecond\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "tag": "second" + } + }, + { + "name": "a field and a file named as something every object of the Node.js twin carries are a field and a file like any other", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"__proto__\"\r\n\r\np\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"constructor\"\r\n\r\nc\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"toString\"\r\n\r\nt\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"__proto__\"; filename=\"valueOf\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "valueOf", + "content_type": "application/octet-stream", + "size": 1, + "tag": "__proto__", + "content_base64": "eQ==" + } + ], + "fields": { + "__proto__": "p", + "constructor": "c", + "toString": "t" + } + }, + { + "name": "an empty name is taken: the field is named with the empty text, the file's tag is 'file'", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"\"\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"\"; filename=\"a.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "file", + "content_base64": "eQ==" + } + ], + "fields": { + "": "x" + } + }, + { + "name": "a file's type is its Content-Type as written", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.bin\"\r\nContent-Type: Image/PNG; q=1 \r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.bin", + "content_type": "Image/PNG; q=1", + "size": 1, + "tag": "doc", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a preamble before the first delimiter and an epilogue after the closing one are passed over", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "This is a preamble.\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\nThis is an epilogue.\r\n--XbOuNdArYx\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "blanks after a delimiter are passed over", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx \t\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "an upload without a part: the closing delimiter alone", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx--\r\n", + "files": [], + "fields": {} + }, + { + "name": "a field's content may hold line ends, dashes and another boundary", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\none\r\n--other\r\n\r\ntwo--\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "note": "one\r\n--other\r\n\r\ntwo--" + } + }, + { + "name": "a boundary in quotes, with the punctuation a boundary may hold", + "content_type": "multipart/form-data; boundary=\"a'()+_,-./:=? b\"", + "body": "--a'()+_,-./:=? b\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a'()+_,-./:=? b--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a boundary of seventy characters, after another parameter", + "content_type": "Multipart/Form-Data; charset=utf-8; BOUNDARY=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "body": "--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a field in UTF-8 keeps a byte order mark as the character it is", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "note": "x" + } + }, + { + "name": "a field may declare UTF-8, in any letter case, in quotes or bare", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"\r\nContent-Type: text/plain; charset=\"utf8\"\r\n\r\ncafé\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "a": "café", + "b": "café" + } + }, + { + "name": "a field may declare ISO-8859-1 or US-ASCII", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImEiDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9SVNPLTg4NTktMQ0KDQpjYWbpDQotLVhiT3VOZEFyWXgNCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTsgbmFtZT0iYiINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbjsgY2hhcnNldD11cy1hc2NpaQ0KDQpwbGFpbg0KLS1YYk91TmRBcll4LS0NCg==", + "files": [], + "fields": { + "a": "café", + "b": "plain" + } + }, + { + "name": "a field in another charset is refused by the charset's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=Windows-1252\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a text field in UTF-8, ISO-8859-1 or US-ASCII, not in 'Windows-1252'" + }, + { + "name": "a field that is not the UTF-8 it is taken for is refused by the field's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5vdGUiDQoNCmNhZukNCi0tWGJPdU5kQXJZeC0tDQo=", + "status": 400, + "error": "Upload text field 'note' is not UTF-8" + }, + { + "name": "a field that is not the US-ASCII it declares is refused by the field's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5vdGUiDQpDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9VVMtQVNDSUkNCg0KY2Fm6Q0KLS1YYk91TmRBcll4LS0NCg==", + "status": 400, + "error": "Upload text field 'note' is not US-ASCII" + }, + { + "name": "a file is never read as text: bytes that are no UTF-8 pass", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImRvYyI7IGZpbGVuYW1lPSJhLnR4dCINCg0KY2Fm6Q0KLS1YYk91TmRBcll4LS0NCg==", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 4, + "tag": "doc", + "content_base64": "Y2Fm6Q==" + } + ], + "fields": {} + }, + { + "name": "a transfer encoding that leaves the bytes as they are is taken: 7bit, 8bit, binary", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"\r\nContent-Transfer-Encoding: 8bit\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"\r\ncontent-transfer-encoding: BINARY\r\n\r\ny\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\nz\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"c\"\r\nContent-Encoding: identity\r\n\r\nw\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eg==" + } + ], + "fields": { + "a": "x", + "b": "y", + "c": "w" + } + }, + { + "name": "a transfer encoding that changes the bytes is refused by name - base64", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Transfer-Encoding: base64\r\n\r\naGVsbG8=\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Transfer-Encoding of 'base64'" + }, + { + "name": "a transfer encoding that changes the bytes is refused by name - quoted-printable, on a file", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\nContent-Transfer-Encoding: Quoted-Printable\r\n\r\ncaf=E9\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Transfer-Encoding of 'Quoted-Printable'" + }, + { + "name": "a content encoding is refused by name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.gz\"\r\nContent-Encoding: gzip\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes the bytes of a part as they are, not a Content-Encoding of 'gzip'" + }, + { + "name": "a part that is multipart itself is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"files\"\r\nContent-Type: multipart/mixed; boundary=inner\r\n\r\n--inner\r\n\r\nx\r\n--inner--\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes text fields and files, not a nested multipart part" + }, + { + "name": "a part that is multipart itself is refused, with no boundary of its own and ahead of a faulty disposition", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: Multipart/Mixed\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes text fields and files, not a nested multipart part" + }, + { + "name": "a part without a Content-Disposition is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a part without a name is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; filename=\"a.txt\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a part that is not form-data is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name=\"doc\"; filename=\"a.txt\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a filename in the extended form is taken: UTF-8, its bytes percent-encoded", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''caf%C3%A9%20%E4%B8%AD.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "café 中.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "doc", + "content_base64": "eA==" + } + ], + "fields": {} + }, + { + "name": "the extended form wins over the plain parameter of its name, whichever comes first", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename=\"plain.txt\"; filename*=UTF-8''star.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"; filename*=UTF-8''star.txt; filename=\"plain.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "star.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" + }, + { + "name": "star.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "b", + "content_base64": "eQ==" + } + ], + "fields": {} + }, + { + "name": "a field's name in the extended form is taken too, alone or beside a plain one", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''caf%C3%A9\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"plain\"; name*=utf-8'en'd%C3%A9j%C3%A0\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [], + "fields": { + "café": "x", + "déjà": "y" } }, { - "name": "x-ttl wins over the entry's timeout; defaults for what is absent", - "map": { - "headers": { - "x-ttl": "1500" + "name": "the extended form in ISO-8859-1, with a language, in any letter case and in quotes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename*=iso-8859-1'fr'caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"b\"; FileName*=\"Utf-8''in%20quotes.txt\"\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "café.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" }, - "timeout": 10, - "parameters": { - "query": {}, - "path": {} + { + "name": "in quotes.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "b", + "content_base64": "eQ==" } - }, - "expect": { - "method": "GET", - "url": "/", - "timeout_seconds": 1, - "is_secure": false, - "path_parameter.user": null, - "query_parameter.q": null, - "header.accept": null, - "cookie.first": null, - "session_info.user": null, - "remote_ip": null, - "query_string": null, - "body": null + ], + "fields": {} + }, + { + "name": "in the extended form a character that is not percent-encoded stands for itself, a plus sign and an apostrophe too, and nothing is unescaped twice", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"a\"; filename*=UTF-8''a+b'c%25d.txt\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''q%2522r\r\n\r\ny\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "a+b'c%d.txt", + "content_type": "application/octet-stream", + "size": 1, + "tag": "a", + "content_base64": "eA==" + } + ], + "fields": { + "q%22r": "y" } - } - ], - "upload_read_cases": [ + }, { - "name": "the files of an upload through the accessors", - "map": { - "method": "POST", - "url": "/api/upload", - "filename": [ - "a.pdf", - "b.png" - ], - "file_type": [ - "application/pdf", - "image/png" - ], - "file_length": [ - 9, - 8 - ], - "size": 17, - "upload": [ - "doc", - "image" - ], - "contents_base64": [ - "JVBERi0xLjQg", - "iVBORw0KGgo=" - ], - "parameters": { - "query": {}, - "path": {} + "name": "an empty filename in the extended form is a file with an empty name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''\r\n\r\n\r\n--XbOuNdArYx--\r\n", + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" } - }, - "expect": { - "is_file": true, - "content_length": 17, - "upload_tags": [ - "doc", - "image" - ], - "files": [ - { - "name": "a.pdf", - "content_type": "application/pdf", - "size": 9, - "tag": "doc", - "content_base64": "JVBERi0xLjQg" - }, - { - "name": "b.png", - "content_type": "image/png", - "size": 8, - "tag": "image", - "content_base64": "iVBORw0KGgo=" - } - ] + ], + "fields": {} + }, + { + "name": "an extended parameter that is not charset'language'value is refused - no apostrophe", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=x.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's filename* is not charset'language'value" + }, + { + "name": "an extended parameter that is not charset'language'value is refused - one apostrophe", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8'x\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's name* is not charset'language'value" + }, + { + "name": "an extended parameter in another charset is refused by the charset's name", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=Windows-1252''caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a part's filename* in UTF-8 or ISO-8859-1, not in 'Windows-1252'" + }, + { + "name": "an extended parameter without a charset is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=''x\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload takes a part's name* in UTF-8 or ISO-8859-1, not in ''" + }, + { + "name": "a percent sign that two hexadecimal digits do not follow is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''bad%ZZ.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's filename* holds a % that two hexadecimal digits do not follow" + }, + { + "name": "a percent sign that two hexadecimal digits do not follow is refused - at the end", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''cut%4\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's name* holds a % that two hexadecimal digits do not follow" + }, + { + "name": "an extended parameter whose bytes are not the charset it declares is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename*=UTF-8''caf%E9.txt\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter filename* of a part is not UTF-8" + }, + { + "name": "an extended parameter whose bytes are not the charset it declares is refused - a sequence cut short", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name*=UTF-8''trunc%C3\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter name* of a part is not UTF-8" + }, + { + "name": "a name at fault is told ahead of a filename at fault and of a part that is not form-data", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name*=UTF-8''%FF; filename*=nope\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Upload parameter name* of a part is not UTF-8" + }, + { + "name": "a part that is not form-data is told ahead of a filename at fault", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: attachment; name=\"doc\"; filename*=nope\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a quote left open in a parameter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a parameter without a value is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"; draft\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a malformed parameter of a field's content type is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nContent-Type: text/plain; charset=\"utf-8\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header parameters are malformed" + }, + { + "name": "a header line without a colon is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\nnot a header\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a part's header line is not 'name: value'" + }, + { + "name": "a header that is not UTF-8 is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body_base64": "LS1YYk91TmRBcll4DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImNhZukiDQoNCngNCi0tWGJPdU5kQXJZeC0tDQo=", + "status": 400, + "error": "Invalid multipart body - a part's headers are not UTF-8" + }, + { + "name": "a content type without a boundary is refused", + "content_type": "multipart/form-data", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary of more than seventy characters is refused", + "content_type": "multipart/form-data; boundary=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "body": "--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary that ends with a space is refused", + "content_type": "multipart/form-data; boundary=\"a b \"", + "body": "--a b \r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a b --\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a boundary with a character a boundary may not hold is refused", + "content_type": "multipart/form-data; boundary=\"a;b\"", + "body": "--a;b\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--a;b--\r\n", + "status": 400, + "error": "Invalid multipart body - the content type declares no boundary" + }, + { + "name": "a body with no delimiter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "just text\r\n", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "an empty body is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "a body delimited by another boundary than the one declared is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--other\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--other--\r\n", + "status": 400, + "error": "Invalid multipart body - no part is delimited by the boundary the content type declares" + }, + { + "name": "line ends that are not carriage return and line feed are refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\nContent-Disposition: form-data; name=\"note\"\n\nx\n--XbOuNdArYx--\n", + "status": 400, + "error": "Invalid multipart body - a delimiter is followed by neither a line end nor the closing dashes" + }, + { + "name": "a delimiter followed by other text is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYxxyz\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - a delimiter is followed by neither a line end nor the closing dashes" + }, + { + "name": "a body that ends inside a part's headers is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "a body that ends inside a part's content is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "a part whose content has no line end before the next delimiter is refused", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\n--XbOuNdArYx--\r\n", + "status": 400, + "error": "Invalid multipart body - the closing delimiter is missing" + }, + { + "name": "the parts' contents together may reach the bound: files and fields, counted in bytes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "files": [ + { + "name": "a.txt", + "content_type": "application/octet-stream", + "size": 5, + "tag": "doc", + "content_base64": "MTIzNDU=" + } + ], + "fields": { + "note": "café" } }, { - "name": "no upload: no files, no size", - "map": { - "method": "GET", - "url": "/x", - "parameters": { - "query": {}, - "path": {} + "name": "one byte more than the bound is a 413 - a field's bytes count, not its characters", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\ncafé\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n123456\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 413, + "error": "Upload exceeds 10 bytes" + }, + { + "name": "the bound is told where it is passed, ahead of a later part at fault", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345678901\r\n--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 413, + "error": "Upload exceeds 10 bytes" + }, + { + "name": "a part at fault is told ahead of the bound a later part passes", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Type: text/plain\r\n\r\nx\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\n12345678901\r\n--XbOuNdArYx--\r\n", + "bound": 10, + "status": 400, + "error": "Invalid multipart body - a part is not 'Content-Disposition: form-data' with a name" + }, + { + "name": "a bound of nothing takes no content at all", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nx\r\n--XbOuNdArYx--\r\n", + "bound": 0, + "status": 413, + "error": "Upload exceeds 0 bytes" + }, + { + "name": "a bound of nothing takes parts without content", + "content_type": "multipart/form-data; boundary=XbOuNdArYx", + "body": "--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\n\r\n--XbOuNdArYx\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"\"\r\n\r\n\r\n--XbOuNdArYx--\r\n", + "bound": 0, + "files": [ + { + "name": "", + "content_type": "application/octet-stream", + "size": 0, + "tag": "doc", + "content_base64": "" } - }, - "expect": { - "is_file": false, - "content_length": null, - "upload_tags": [], - "files": [] + ], + "fields": { + "note": "" } } ], @@ -1807,6 +3291,50 @@ ], "body": "too many" } + }, + { + "name": "a reply's key and a reply's header named as something every object of the Node.js twin carries are a key and a header like any other", + "status": 200, + "reply_headers": { + "__proto__": "p", + "constructor": "c" + }, + "body": { + "__proto__": { + "x": 1, + "y": null + }, + "constructor": "c", + "toString": null + }, + "accept": "application/json", + "head": false, + "transform": null, + "cors": null, + "cid": "cid-1", + "cid_header": "x-correlation-id", + "expect": { + "status": 200, + "headers": [ + [ + "__proto__", + "p" + ], + [ + "constructor", + "c" + ], + [ + "content-type", + "application/json" + ], + [ + "x-correlation-id", + "cid-1" + ] + ], + "body": "{\n \"__proto__\": {\n \"x\": 1\n },\n \"constructor\": \"c\"\n}" + } } ], "render_cases": [ From 4381a8b1c300439871a1fdc86252ca25c5fb3395 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:17 -0800 Subject: [PATCH 2/6] fix(agent-tools): one reader of a URL and of robots.txt in both packs, a regex search that ends at a bound, settings by one rule The web tools take a URL apart by one set of rules, write it back in one form, refuse anything else by name and ask a site for exactly what was checked; a URL is at most 8192 characters. robots.txt is read by the tools' own RFC 9309 reader, a rule matched part by part between its stars, so its time is its length plus the path's. file.search with regex: true runs outside the host and ends at tools.file.search.timeout.ms with a 408; a literal is a substring test. A walk looks at 20,000 entries at most and says truncated. A tools.* setting that is no number or no switch stops the start by name. graph.ingest keeps a property named __proto__. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-tools/README.md | 63 +- extensions/agent-tools/agent-tools.mjs | 925 ++++++++++++++---- .../agent-tools/resources/application.yml | 3 + test/agent-tools.test.mjs | 829 +++++++++++++++- 4 files changed, 1607 insertions(+), 213 deletions(-) diff --git a/extensions/agent-tools/README.md b/extensions/agent-tools/README.md index a5042367..a79717c7 100644 --- a/extensions/agent-tools/README.md +++ b/extensions/agent-tools/README.md @@ -52,9 +52,9 @@ Without `tools.file.root` the file tools stay out (`File tools not registered - `tools.web.allow` the web tools stay out; without `tools.graph.uri` the graph tools stay out, and the two graph writers need `tools.graph.write=true` as well; `file.extract` registers with the file tools when `mammoth` and `pdfjs-dist` are installed; `time.now` registers unless `tools.time=false`. A root that is not a directory, an allowlist entry that is -not a host pattern, a graph URI that is not a Bolt URI or without the driver installed, or a limit that is not a number -stops the application by name. A graph database that does not answer at boot is logged, and its tools answer 503 until -it does. +not a host pattern, a graph URI that is not a Bolt URI or without the driver installed, a limit that is not a number +or a switch that is neither `true` nor `false` stops the application by name. A graph database that does not answer +at boot is logged, and its tools answer 503 until it does. ## The tools @@ -82,7 +82,20 @@ names folders only. Names are matched with their case. A symbolic link is an ent workspace and something is there - and a pattern never goes through it. A pattern that is absolute, holds `..` or names no entry is refused. A name is matched item by item, so the time a pattern takes is bounded by its length times the length of the path, however many stars it has, and the walk reads only the folders the pattern can still match -in. +in. A list or a search looks at 20 000 directory entries at most, whether they match or not, and says in `truncated` +that it stopped there. + +A search for a literal looks for it as a part of each line - of the line's lower-case form, the literal in lower case +too, unless `case_sensitive` is true - which takes a time bounded by the line's length: a literal of more than 64 +units is looked for by the tools' own matcher, since the runtime's search may compare a long literal with a line at +every place of it. A search by regular expression takes the expression as the runtime reads one (JavaScript's +`RegExp` here, Python's `re` in the Python twin) and never runs it in the host: a worker thread compiles and runs it, +the host stays responsive whatever the expression does, and the worker is ended when the search is over, and at +`tools.file.search.timeout.ms` (10 s, counted from the start of the search) at the latest. A search that has not +finished by then is a 408 that names the key, and nothing is left running after it; an expression the runtime cannot +compile is a 400. The worker costs a thread start for each search by regular expression, a few milliseconds; a +literal starts none. A byte-order mark at the start of a file is no part of its text: `file.read`, `file.search` and +`file.extract` leave it out. `file.write` carries the write mark, so under the node's default mode a person approves it; the other file tools are reads and run unasked. @@ -103,6 +116,23 @@ shared address space (`100.64.0.0/10`). An IPv6 address is reached only inside t `tools.web.max.bytes` (1 MiB), the request at `tools.web.timeout.ms` (10 s), cookies are never kept, the body is requested without compression, and the tool identifies itself as `Mercury-Composable-AgentTools/`. +**How a URL is read.** A URL - the `url` argument, the `Location` of a redirect, a link of a page - is taken apart by +the tools' own rules, the same in both packs, and written back in one form: a page is one page however its links +spell it, and what is asked of a site is what was checked. What a browser strips is stripped first: the controls and +the space at the ends, every tab and line break inside. The scheme is `http` or `https`, followed by two slashes, and +credentials are refused. The host is a name in letters, digits, hyphens, dots and underscores (an internationalized +name in its `xn--` form), written in lower case; or an IPv4 address in dotted decimal, four numbers from 0 to 255 +without leading zeros - a host whose last label spells a number any other way (`0177.0.0.1`, `2130706433`, `0x7f.1`, +`127.1`) is refused by name; or an IPv6 address in brackets, without a zone, written in its short form. The port is +the digits 0 to 9, from 1 to 65535, and is left out when it is the scheme's own. In the path and the query a +character a URI does not carry as it is - a space, a backslash, a letter outside ASCII - becomes its UTF-8 bytes +percent-encoded; an escape keeps its two digits in upper case, or becomes the letter, digit, hyphen, dot, underscore +or tilde it stands for; and the path loses its `.` and `..` segments. An empty path is `/`, an empty query is none, +and the fragment is dropped. An address longer than 8192 characters in that form is refused (`url is longer than +8192 characters`): a page may write a link of any length, and every link is asked of a `robots.txt` and of a +server. A link is read at the address of its page by the same rules, and one that names no web address +(`mailto:`, `javascript:`, another scheme) is not followed. + | Route | Row | Arguments | Result | | --- | --- | --- | --- | | `web.fetch` | `web_fetch` | `url` (required); `as`: `text` (default), `markdown`, `raw` | `{url, status, content_type, title, text, bytes, truncated}`; HTML is reduced to its readable text (scripts, styles, `nav`, `header` and `footer` dropped; headings, lists, code and links kept as text or as Markdown); a text resource (`text/*`, JSON, XML) is returned as is; `raw` returns the body as received; a binary response is a 400; the page's own status (a 404, a 500) is a result, not an error | @@ -112,8 +142,14 @@ The crawl is a bounded reader of a documentation section or a small site, not a include prefix and the delay are all limits, and a model that needs more asks again with a narrower start. HTML is read by a small in-house tokenizer (no dependency) that decodes the common named character references and every numeric one, enough for documentation and articles; an installation whose pages need main-content extraction may put a -library behind the same route. `robots.txt` is read by an in-house parser too: the group for `MercuryComposable`, -else `*`; the longest matching rule wins, `Allow` over `Disallow` on a tie. +library behind the same route. + +`robots.txt` is read by the tools' own reader, by RFC 9309, the same in both packs: the rules of the groups that name +`MercuryComposable`, in any letter case - or, when none does, of the groups for `*`; `Allow` and `Disallow`, with `*` +for any run of characters and a `$` at the end of a pattern for the end of the path, matched against the path and the +query in the form above; the longest pattern that matches decides, and `Allow` wins a tie. A site without a +`robots.txt`, or with one that cannot be read, allows all. A rule is matched part by part between its stars, so the +time it takes is bounded by its length plus the path's, however many stars it has. ### The knowledge graph, inside one database @@ -189,6 +225,7 @@ the time zone database. | `tools.file.hidden` | `false` | expose hidden entries (a name starting with `.`) to the file tools | | `tools.file.write.extensions` | any | the suffixes `file.write` accepts, comma-separated (`.md, .txt`) | | `tools.file.line.max.chars` | `500` | the longest line `file.search` returns | +| `tools.file.search.timeout.ms` | `10000` | how long a search by regular expression may take, 100 ms at least; the search is ended there | | `tools.web.allow` | empty | the host patterns the web tools may reach, comma-separated: `docs.example.com`, `*.example.org`, `http://intranet.example`, `host:8443`; `*` is any run of characters and `[seq]` one character of a class (`[ab].example.com`), and brackets that hold an address are that address (`[::1]:8443`); empty, the web tools do not register | | `tools.web.allow.private` | `false` | allow addresses in loopback, private, link-local and multicast ranges | | `tools.web.max.bytes` | `1048576` | the most bytes read from one response | @@ -211,6 +248,13 @@ Limits are defaults a deployment lowers, never raises past the tool's caps (a `t logged and capped). The shipped `application.yml` takes the root and the allowlist from `${TOOLS_FILE_ROOT:}` and `${TOOLS_WEB_ALLOW:}`, so a deployment sets two environment variables or two `-D` flags. +A number and a switch are read the same way in both packs. A number is a number of the configuration with a whole +value, or a text of the digits 0 to 9 with white space around it at most, up to 9007199254740991; a time in +milliseconds is at most 2147483647 (about 24.8 days, the longest wait both packs' timers hold). A switch is the +configuration's `true` or `false`, or that word as text in any letter case. Any other value - a sign, an underscore, +an exponent, a decimal point in text, a digit of another script; `1` or `enabled` for a switch - stops the +application by name, and is never read as something near it. + ## The function contract | | | @@ -219,7 +263,7 @@ logged and capped). The shipped `application.yml` takes the root and the allowli | Reply | The result map of the table above. | | 400 | A refusal by rule: a path outside the workspace, a hidden entry, a binary file, a site that is not allowed, a private address, a bad argument, too many redirects, a response that is not text, a write clause in a read-only query, a deletion without the gate, an ingest with a bad label or a missing endpoint; or the graph database's own client error, by its code. The message names the rule and the key that governs it. | | 404 | The file or folder does not exist. | -| 408 | The site or the graph database did not answer within its timeout. | +| 408 | The site or the graph database did not answer within its timeout, or a search by regular expression did not finish within its own. | | 409 | `file.write` in `create` mode found the file. | | 502 | The host cannot be resolved, the connection failed, or the graph database failed in a way that is not the caller's. | | 503 | The graph database is not reachable or refused this process's credential. | @@ -312,5 +356,6 @@ the clause scan, the ingest plan, the error mapping on the driver's own exceptio a Word fixture; the boot, the health route, the `describe` output and the catalog files complete the suite. The live graph test runs when `TOOLS_GRAPH_TEST_URI` names a database. -Four texts in the test file are the same, line for line, in the other pack's test file: the probes of the address -classification, the URL probes, and the tree and the probes of the glob grammar. A change to one goes into both. +Ten texts in the test file are the same, line for line, in the other pack's test file: the probes of the address +classification, the URL probes, the tree and the probes of the glob grammar, and the probes of a number, a switch, a +link, an allowlist entry, the reading of a URL and `robots.txt`. A change to one goes into both. diff --git a/extensions/agent-tools/agent-tools.mjs b/extensions/agent-tools/agent-tools.mjs index c46c0def..60e87687 100644 --- a/extensions/agent-tools/agent-tools.mjs +++ b/extensions/agent-tools/agent-tools.mjs @@ -12,11 +12,12 @@ * - `tools.file.root` names the one directory tree the file tools may touch (`file.read`, * `file.write`, `file.list`, `file.search`, and `file.extract` when mammoth and pdfjs-dist are * installed). Every path is relative to it, resolved with symbolic links followed, and refused - * when the result is outside the root. + * when the result is outside the root. A search by regular expression runs in a worker thread, + * ended at `tools.file.search.timeout.ms`. * - `tools.web.allow` names the host patterns the two web tools may reach (`web.fetch`, `web.crawl`), * over https unless a host is listed with `http://`; an address in a loopback, private, link-local * or multicast range is refused unless `tools.web.allow.private=true`, and every redirect is - * checked again. + * checked again. A URL is read by the tools' own rules, the same in both packs. * - `tools.graph.uri` names the one graph database the four knowledge-graph tools reach over the Bolt * protocol (`graph.schema`, `graph.query` in a read transaction; `graph.write` and `graph.ingest` * only when `tools.graph.write=true`, deletion only when `tools.graph.delete=true`); neo4j-driver @@ -41,12 +42,13 @@ * Python twin (mercury-python extensions/agent-tools) carries. */ import { lookup as dnsLookup } from 'node:dns/promises'; -import { mkdir, open, readdir, readFile, realpath, stat, writeFile } from 'node:fs/promises'; +import { mkdir, open, opendir, readFile, realpath, stat, writeFile } from 'node:fs/promises'; import http from 'node:http'; import https from 'node:https'; import { BlockList, isIP } from 'node:net'; import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { Worker } from 'node:worker_threads'; import { AppException, appConfig, defaultRegistry, getLogger, isoUtc, loadConfig, platform, preload, VERSION } from 'mercury-composable'; const defaultLog = getLogger('agent-tools'); @@ -58,23 +60,41 @@ export const USER_AGENT = `Mercury-Composable-AgentTools/${VERSION} (+https://gi // the token robots.txt rules are matched against export const ROBOTS_AGENT = 'MercuryComposable'; +// how a number is read, the same in both packs: the largest whole number both hold exactly +// (2**53 - 1) - above it this pack's numbers round, and the twins would read two different numbers +// from one value +export const MAX_WHOLE = Number.MAX_SAFE_INTEGER; +// the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): this +// pack's timers keep a delay in 32 bits with a sign and fire at once on a longer one +export const MAX_TIMER_MS = 2147483647; +// the white space ignored around a number, a switch and an entry of a list: the characters +// JavaScript's trim() and Python's str.strip() both take for white space, so neither pack accepts +// a character the other refuses +const BLANKS = '\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000'; +// a run of the digits 0 to 9 and nothing else: \d is those only here +const DIGITS = /^\d+$/; + // files: the workspace and its limits export const FILE_ROOT = 'tools.file.root'; export const FILE_MAX_BYTES = 'tools.file.max.bytes'; export const FILE_HIDDEN = 'tools.file.hidden'; export const FILE_WRITE_EXTENSIONS = 'tools.file.write.extensions'; export const FILE_LINE_MAX_CHARS = 'tools.file.line.max.chars'; +export const FILE_SEARCH_TIMEOUT_MS = 'tools.file.search.timeout.ms'; export const FILE_EXTRACT_MAX_CHARS = 'tools.file.extract.max.chars'; export const DEFAULT_FILE_MAX_BYTES = 256 * 1024; export const DEFAULT_LINE_MAX_CHARS = 500; +export const DEFAULT_SEARCH_TIMEOUT_MS = 10000; export const DEFAULT_EXTRACT_MAX_CHARS = 60000; export const LIST_DEFAULT = 200; export const LIST_CAP = 2000; export const SEARCH_DEFAULT = 100; export const SEARCH_CAP = 1000; export const CONTEXT_CAP = 3; -// how many directory entries a list or a search walks before it gives up - the tool's own bound +// how many directory entries a list or a search looks at before it gives up - the tool's own bound export const SCAN_LIMIT = 20000; +// the bound a walk runs with: the constant, until a test lowers it (setScanLimit) +let scanLimit = SCAN_LIMIT; export const WRITE_MODES = ['create', 'overwrite', 'append']; export const DOCUMENTS_EXTRA = 'npm install --save-dev mammoth pdfjs-dist'; @@ -576,23 +596,59 @@ export function rowJson(row) { // --- configuration helpers --------------------------------------------------------------------- +// a text without the white space both packs take for it, at its start and at its end - read from +// the ends, so a text of any length costs its length once +function trimBlanks(text) { + let start = 0; + let end = text.length; + while (start < end && BLANKS.includes(text[start])) start++; + while (end > start && BLANKS.includes(text[end - 1])) end--; + return text.slice(start, end); +} + +/** The whole number a run of ASCII digits spells, or undefined above MAX_WHOLE. */ +function whole(digits) { + const number = Number(digits); + return Number.isSafeInteger(number) ? number : undefined; +} + +/** + * The whole number a value is: a number with a whole value - which is all this pack sees of a float + * such as 5.0 - or a text of ASCII digits with white space around them at most. Undefined for + * anything else: a boolean, a fraction, a sign, an exponent, a digit of another script, a number + * beyond MAX_WHOLE. + */ +function wholeNumber(value) { + if (typeof value === 'string') { + const text = trimBlanks(value); + return DIGITS.test(text) ? whole(text) : undefined; + } + return typeof value === 'number' && Number.isSafeInteger(value) ? value : undefined; +} + function setting(key, defaultValue = undefined) { const value = appConfig().get(key, defaultValue); - if (value === undefined || value === null || (typeof value === 'string' && !value.trim())) { + if (value === undefined || value === null || (typeof value === 'string' && !trimBlanks(value))) { return defaultValue; } return value; } -function intSetting(key, defaultValue, { floor = 1, cap = undefined, log = defaultLog } = {}) { - const raw = setting(key, defaultValue); - const value = Number(String(raw).trim()); - if (!Number.isInteger(value)) { - throw new ToolsError(`${key} must be an integer, not ${JSON.stringify(raw)}`); +/** + * A setting that is a whole number, inside its bounds: under the floor or over the most it stops the + * boot by name, over the tool's cap it is lowered to the cap with a warning. + */ +function intSetting(key, defaultValue, { floor = 1, cap = undefined, most = MAX_WHOLE, log = defaultLog } = {}) { + const value = wholeNumber(setting(key, defaultValue)); + if (value === undefined) { + throw new ToolsError(`${key} must be an integer`); } if (value < floor) { throw new ToolsError(`${key} must be at least ${floor}`); } + if (value > most) { + throw new ToolsError(`${key} must be at most ${most}`); + } if (cap !== undefined && value > cap) { log.warn(`${key}=${value} is over the tool's cap ${cap} - a deployment lowers a limit, never raises it; using ${cap}`); return cap; @@ -600,20 +656,25 @@ function intSetting(key, defaultValue, { floor = 1, cap = undefined, log = defau return value; } +/** + * A setting that is a switch: true or false, the boolean or the text in any letter case. Any other + * value stops the boot by name - it is never read as on or as off. + */ function boolSetting(key, defaultValue) { const raw = setting(key, defaultValue); if (typeof raw === 'boolean') return raw; - const text = String(raw).trim().toLowerCase(); - if (['true', 'yes', 'on', '1'].includes(text)) return true; - if (['false', 'no', 'off', '0'].includes(text)) return false; - throw new ToolsError(`${key} must be true or false, not ${JSON.stringify(raw)}`); + const text = typeof raw === 'string' ? trimBlanks(raw).toLowerCase() : ''; + if (text !== 'true' && text !== 'false') { + throw new ToolsError(`${key} must be true or false`); + } + return text === 'true'; } function listSetting(key) { const raw = setting(key); if (raw === undefined) return []; const items = Array.isArray(raw) ? raw : String(raw).split(','); - return items.map((item) => String(item).trim()).filter(Boolean); + return items.map((item) => trimBlanks(String(item))).filter(Boolean); } // --- argument helpers - a tool's body is a map of the row's properties ------------------------ @@ -648,7 +709,8 @@ function stringArg(args, name, { defaultValue = undefined } = {}) { function integerArg(args, name, { defaultValue, floor, cap }) { const value = args[name]; if (value === undefined || value === null) return Math.min(defaultValue, cap); - if (typeof value !== 'number' || !Number.isInteger(value)) { + // the row says integer: a number with a whole value, never a text of digits + if (typeof value !== 'number' || wholeNumber(value) === undefined) { throw new AppException(400, `${name} must be an integer`); } if (value < floor) { @@ -701,7 +763,8 @@ export async function loadFileSandbox({ log = defaultLog } = {}) { hidden: boolSetting(FILE_HIDDEN, false), writeExtensions: extensions, lineMaxChars: intSetting(FILE_LINE_MAX_CHARS, DEFAULT_LINE_MAX_CHARS, { floor: 20, log }), - extractMaxChars: intSetting(FILE_EXTRACT_MAX_CHARS, DEFAULT_EXTRACT_MAX_CHARS, { floor: 100, log }) + extractMaxChars: intSetting(FILE_EXTRACT_MAX_CHARS, DEFAULT_EXTRACT_MAX_CHARS, { floor: 100, log }), + searchTimeoutMs: intSetting(FILE_SEARCH_TIMEOUT_MS, DEFAULT_SEARCH_TIMEOUT_MS, { floor: MIN_WEB_TIMEOUT_MS, most: MAX_TIMER_MS, log }) }; } @@ -925,63 +988,227 @@ export function compileGlob(pattern) { /** * One entry of a walk, in the directory the walk is at: it joins `found` when the glob matches it, - * and the queue when it is a directory the glob reaches into. True when the scan limit is passed. + * and the queue when it is a directory the glob reaches into. */ function scanEntry(entry, { dir, relativeDir, level }, matcher, found, queue) { const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name; if (matcher.test(relativePath)) found.push(join(dir, entry.name)); - if (found.length > SCAN_LIMIT) return true; if (entry.isDirectory() && !entry.isSymbolicLink() && matcher.enters(entry.name, level)) { queue.push({ dir: join(dir, entry.name), relativeDir: relativePath, level: level + 1 }); } - return false; } -/** Every entry under a directory that matches a compiled glob, as absolute paths, bounded by the scan limit; a symbolic link is an entry, never descended into. */ +/** + * Every entry under a directory that matches a compiled glob, as absolute paths, and whether the walk + * was cut: it looks at the scan limit's entries at most, whether they match or not. A symbolic link is + * an entry, never descended into. + */ async function globWalk(base, matcher) { const found = []; + let looked = 0; const queue = [{ dir: base, relativeDir: '', level: 1 }]; - while (queue.length && found.length <= SCAN_LIMIT) { + while (queue.length) { const here = queue.shift(); - let entries; - try { - entries = await readdir(here.dir, { withFileTypes: true }); - } catch { - continue; + for await (const entry of entriesOf(here.dir)) { // NOSONAR - sequential: a folder is read as far as the walk goes, after the one before it + if (looked >= scanLimit) return { found, bounded: true }; + looked += 1; + scanEntry(entry, here, matcher, found, queue); } - for (const entry of entries) { - if (scanEntry(entry, here, matcher, found, queue)) break; + } + return { found, bounded: false }; +} + +/** + * The entries of a directory of a walk, one at a time, and none for one that cannot be read. The + * directory is read as far as the walk asks, never as a whole, and closed when the walk leaves it. + */ +async function* entriesOf(dir) { + try { + yield* await opendir(dir); + } catch { + // a directory that cannot be read has no entries for the walk + } +} + +/** The direct entries of a directory, as absolute paths, the scan limit's at most, and whether one was left. */ +async function listing(base) { + const found = []; + for await (const entry of await opendir(base)) { + if (found.length >= scanLimit) return { found, bounded: true }; + found.push(join(base, entry.name)); + } + return { found, bounded: false }; +} + +// What the worker thread of a search by regular expression runs. It compiles the expression it is +// given and says whether it could; then it answers each block of lines - the lines, and how many +// matches are wanted at most - with the numbers of the lines that match. The engine compiles an +// expression when it first runs it, so the one run on an empty text finds out an expression it +// cannot compile, and a later one finds out what only a longer text shows. +const SEARCH_WORKER = ` +const { parentPort, workerData } = require('node:worker_threads'); +let matcher; +try { + matcher = new RegExp(workerData.pattern, workerData.flags); + matcher.test(''); + parentPort.postMessage({}); +} catch (e) { + parentPort.postMessage({ invalid: e.message }); +} +parentPort.on('message', ({ lines, most }) => { + const hits = []; + try { + for (let number = 0; number < lines.length && hits.length < most; number++) { + if (matcher.test(lines[number])) hits.push(number); } + parentPort.postMessage({ hits }); + } catch (e) { + parentPort.postMessage({ invalid: e.message }); } - return found; +}); +`; + +// A literal of more units than this is looked for by the tools' own matcher. The engine's search +// may compare a literal with a line at every place of the line, as far as the literal goes: for a +// literal this short that is a bounded number of comparisons a place, for a longer one it is not. +const LONG_LITERAL = 64; + +/** A text as its UTF-16 units, the form in which a literal is a part of a line. */ +function unitsOf(text) { + const units = new Uint16Array(text.length); + Buffer.from(units.buffer).write(text, 'utf16le'); + return units; } -/** The pattern of a search as a regular expression: a literal unless it is said to be one, case-insensitive unless told otherwise. */ -function searchMatcher(pattern, { regex, caseSensitive }) { - if (!pattern) { - throw new AppException(400, 'pattern must not be empty'); +/** For each place in a literal, how many units before it repeat the literal's start (Knuth, Morris and Pratt). */ +function repeatsOf(needle) { + const repeats = new Int32Array(needle.length); + let matched = 0; + for (let at = 1; at < needle.length; at++) { + while (matched > 0 && needle[at] !== needle[matched]) matched = repeats[matched - 1]; + if (needle[at] === needle[matched]) matched += 1; + repeats[at] = matched; } + return repeats; +} + +/** Whether a line holds a long literal: a unit of the line is never looked at again once it is passed. */ +function holdsLong(line, needle, repeats) { + if (line.length < needle.length) return false; + let matched = 0; + for (const unit of unitsOf(line)) { + while (matched > 0 && unit !== needle[matched]) matched = repeats[matched - 1]; + if (unit === needle[matched]) matched += 1; + if (matched === needle.length) return true; + } + return false; +} + +/** What says whether a line holds a literal, in a time bounded by the line's length. */ +function holderOf(needle) { + if (needle.length <= LONG_LITERAL) return (line) => line.includes(needle); + const units = unitsOf(needle); + const repeats = repeatsOf(units); + return (line) => holdsLong(line, units, repeats); +} + +/** + * A search for a literal, made in the host: a line holds the literal when the literal is a part of + * it - of its lower-case form, for a search that ignores case. That takes a time bounded by the + * line's length, whatever the literal, so a literal needs no worker. + */ +function literalSearch(pattern, { caseSensitive }) { + const holds = holderOf(caseSensitive ? pattern : pattern.toLowerCase()); + const hits = (lines, most) => { + const found = []; + for (let number = 0; number < lines.length && found.length < most; number++) { + if (holds(caseSensitive ? lines[number] : lines[number].toLowerCase())) found.push(number); + } + return found; + }; + return { hits, close: () => undefined }; +} + +/** + * A search by regular expression, made in a worker thread: the host never compiles or runs the + * model's expression, so it stays responsive whatever the expression does. The worker is ended at + * the bound, counted from the start of the search, and at the end of the search at the latest - + * nothing is left running after it. + */ +async function expressionSearch(pattern, { caseSensitive, timeoutMs }) { + const worker = new Worker(SEARCH_WORKER, { eval: true, workerData: { pattern, flags: caseSensitive ? '' : 'i' } }); + let waiting; + let gone; + // the worker is gone, at the bound or of itself: the answer that is awaited fails, and every later one + const end = (failure) => { + gone ??= failure; + waiting?.reject(gone); + }; + const early = () => new AppException(500, 'the search by regular expression ended before it answered'); + worker.on('message', (answer) => waiting?.resolve(answer)); + worker.on('error', () => end(early())); + worker.on('exit', () => end(early())); + const timer = setTimeout(() => { + end(new AppException(408, `the search did not finish within ${timeoutMs} ms (${FILE_SEARCH_TIMEOUT_MS}) - ` + + 'a simpler regular expression, or a narrower path or glob, finishes sooner')); + worker.terminate(); + }, timeoutMs); + /** One request to the worker - none for what it says of itself when it starts - and its answer. */ + const ask = async (request) => { + const answer = await new Promise((resolve, reject) => { + waiting = { resolve, reject }; + if (gone) reject(gone); + else if (request) worker.postMessage(request); + }); + if (answer.invalid !== undefined) { + throw new AppException(400, `pattern is not a valid regular expression (${answer.invalid})`); + } + return answer; + }; + /** End the worker at once, whether it has finished or not, and wait until it is gone. */ + const close = async () => { + clearTimeout(timer); + await worker.terminate(); + }; try { - return new RegExp(regex ? pattern : pattern.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`), caseSensitive ? '' : 'i'); + await ask(); } catch (e) { - throw new AppException(400, `pattern is not a valid regular expression (${e.message})`); + await close(); + throw e; } + return { hits: async (lines, most) => (lines.length ? (await ask({ lines, most })).hits : []), close }; +} + +/** What finds the lines a pattern is in: a literal in the host, a regular expression in a worker that can be ended. */ +function lineSearch(pattern, { regex, caseSensitive, timeoutMs }) { + return regex ? expressionSearch(pattern, { caseSensitive, timeoutMs }) : literalSearch(pattern, { caseSensitive }); } -// the lines of a text file; the newline that ends the file starts no line +// the lines of a text file, without a byte-order mark at its start - the decoder drops it; the +// newline that ends the file starts no line function linesOf(data) { const lines = new TextDecoder('utf-8').decode(data).split(/\r?\n/); if (lines.length && lines.at(-1) === '') lines.pop(); return lines; } +// the lines of a file when it can be read and its first bytes are text; undefined for a file a search skips +async function textLines(path) { + let data; + try { + data = await readFile(path); + } catch { + return undefined; + } + return binaryKind(data.subarray(0, 8192)) === undefined ? linesOf(data) : undefined; +} + /** - * The lines of one file that match, added to the matches with the lines around them, each cut to - * the width. True when a match was left out because the result is full. + * The lines of one file that match - the ones the hits number, from 0 - added to the matches with the + * lines around them, each cut to the width. True when a match was left out because the result is full. */ -function matchLines(lines, matcher, shown, matches, { context, width, maxResults }) { - for (let index = 0; index < lines.length; index++) { - if (!matcher.test(lines[index])) continue; +function matchLines(lines, hits, shown, matches, { context, width, maxResults }) { + for (const index of hits) { if (matches.length >= maxResults) return true; matches.push({ path: shown, @@ -1060,26 +1287,16 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin /** * The entries under a directory, sorted by their workspace-relative path; hidden entries and - * entries that escape the workspace are left out. `bounded` says the walk hit the scan bound. + * entries that escape the workspace are left out. `bounded` says the walk was cut at the scan + * bound: it had looked at that many entries and there were more. */ async function walk(base, pattern, { filesOnly }) { const found = []; - let bounded = false; - let foldersOnly = false; - let candidates; - if (pattern) { - const matcher = compileGlob(pattern); - foldersOnly = matcher.foldersOnly; - candidates = await globWalk(base, matcher); - } else { - candidates = (await readdir(base)).map((entry) => join(base, entry)); - } + const matcher = pattern ? compileGlob(pattern) : undefined; + const foldersOnly = matcher?.foldersOnly ?? false; + const { found: candidates, bounded } = await (matcher ? globWalk(base, matcher) : listing(base)); for (const entry of candidates) { - if (found.length >= SCAN_LIMIT) { - bounded = true; - break; - } - const exposed = await exposedEntry(entry, { filesOnly, foldersOnly }); // NOSONAR - sequential: the scan bound counts the entries found so far + const exposed = await exposedEntry(entry, { filesOnly, foldersOnly }); // NOSONAR - sequential: one entry at a time, in the order the walk found them if (exposed) found.push(exposed); } found.sort((a, b) => byCodeUnit(a.shown, b.shown)); @@ -1211,25 +1428,30 @@ export function createFileTools(sandbox, { log = defaultLog, documents = undefin const caseSensitive = flagArg(args, 'case_sensitive', { defaultValue: false }); const context = integerArg(args, 'context', { defaultValue: 0, floor: 0, cap: CONTEXT_CAP }); const maxResults = integerArg(args, 'max_results', { defaultValue: SEARCH_DEFAULT, floor: 1, cap: SEARCH_CAP }); - const matcher = searchMatcher(pattern, { regex, caseSensitive }); - const { base } = await directoryOf(args, FILE_SEARCH_ROW); - const { found, bounded } = await walk(base, fileGlob, { filesOnly: true }); + if (!pattern) { + throw new AppException(400, 'pattern must not be empty'); + } + const lineSearcher = await lineSearch(pattern, { regex, caseSensitive, timeoutMs: sandbox.searchTimeoutMs }); const limits = { context, width: sandbox.lineMaxChars, maxResults }; const matches = []; let searched = 0; - let truncated = bounded; - for (const { shown, resolved } of found) { - if (truncated && matches.length >= maxResults) break; - let data; - try { - data = await readFile(resolved); - } catch { - continue; + let truncated = false; + try { + const { base } = await directoryOf(args, FILE_SEARCH_ROW); + const { found, bounded } = await walk(base, fileGlob, { filesOnly: true }); + truncated = bounded; + for (const { shown, resolved } of found) { + if (truncated && matches.length >= maxResults) break; + const lines = await textLines(resolved); + if (lines === undefined) continue; + searched += 1; + // one match more than the result has room for says that the result was cut + const hits = await lineSearcher.hits(lines, maxResults - matches.length + 1); + if (matchLines(lines, hits, shown, matches, limits)) truncated = true; + if (truncated && matches.length >= maxResults) break; } - if (binaryKind(data.subarray(0, 8192)) !== undefined) continue; - searched += 1; - if (matchLines(linesOf(data), matcher, shown, matches, limits)) truncated = true; - if (truncated && matches.length >= maxResults) break; + } finally { + await lineSearcher.close(); } log.info(`file.search 200 ${matches.length} matches in ${searched} files${truncated ? ' (cut)' : ''}`); return { matches, files_searched: searched, truncated }; @@ -1315,14 +1537,17 @@ function everyPage(total) { return Array.from({ length: total }, (_, i) => i + 1); } -/** One part of a page selection, `7` or `1-3`, as its first and its last page. */ +/** + * One part of a page selection, `7` or `1-3`, as its first and its last page. A page number is a + * whole number as both packs read one, MAX_WHOLE at most. + */ function pageSpan(part) { const match = /^(\d+)(?:-(\d+))?$/.exec(part); - if (!match) { + const start = match ? whole(match[1]) : undefined; + const end = match?.[2] === undefined ? start : whole(match[2]); + if (start === undefined || end === undefined) { throw new AppException(400, 'pages must be page numbers and ranges such as 1-3,7'); } - const start = Number(match[1]); - const end = match[2] === undefined ? start : Number(match[2]); if (start < 1 || end < start) { throw new AppException(400, 'pages must be page numbers and ranges such as 1-3,7, counted from 1'); } @@ -1334,10 +1559,10 @@ export function pageRange(spec, total) { if (total <= 0) return []; // no selection, or a blank one, is every page if (spec === undefined || spec === null) return everyPage(total); - if (!spec.trim()) return everyPage(total); + if (!trimBlanks(spec)) return everyPage(total); const wanted = []; for (const token of spec.split(',')) { - const part = token.trim(); + const part = trimBlanks(token); if (!part) continue; const [start, end] = pageSpan(part); for (let number = start; number <= Math.min(end, total); number++) { @@ -1391,6 +1616,240 @@ async function docxText(documents, data, relativePath) { } } +// --- how a web address is read: the same in both packs ------------------------------------------- +// +// A URL - the url argument, the Location of a redirect, a link of a page - is taken apart by the +// rules below and written back in one form, so both packs take the same text for the same address, +// compare it and ask for it in the same words, and neither depends on its runtime's own reader: +// +// - what a browser strips is stripped first: the controls and the space at the ends, and every tab +// and line break inside; +// - the scheme is http or https, in any letter case, followed by two slashes; +// - no credentials; the host is a name in letters, digits, hyphens, dots and underscores, written +// in lower case, or an IPv4 address in dotted decimal - four numbers from 0 to 255 without leading +// zeros, and no other spelling of a number - or an IPv6 address in brackets, without a zone, +// written in its one short form; the port is ASCII digits from 1 to 65535, left out when it is +// the scheme's own; +// - in the path and the query a character a URI does not carry as it is becomes its UTF-8 bytes +// percent-encoded, an escape keeps its two digits in upper case - or becomes the letter, digit, +// hyphen, dot, underscore or tilde it stands for - and the path loses its . and .. segments; +// - an empty path is /, an empty query is none, and the fragment is no part of the address; +// - an address longer than 8192 characters in that form is refused. + +// a map: a scheme comes from a URL's text, and matches the table's own keys only +const DEFAULT_PORTS = new Map([['http', 80], ['https', 443]]); +// what a URL is told when it is no http(s) address, or none the reader can take apart +const NOT_A_WEB_ADDRESS = 'url must start with https:// (or http:// for a host listed with it)'; +const INVALID_PORT = 'url has an invalid port'; +const INVALID_HOST = 'url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores)'; +const NOT_DOTTED_DECIMAL = 'is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros)'; +// the longest address the tools take, counted in its one form: about what a server's request line +// holds. A page may write a link of any length, and a robots.txt is asked about every one of them +export const MAX_URL_LENGTH = 8192; +const TOO_LONG = `url is longer than ${MAX_URL_LENGTH} characters`; +const SCHEME = /^([A-Za-z][A-Za-z0-9+.-]*):/; +const HOST_NAME = /^[A-Za-z0-9._-]+$/; +// a host whose last label spells a number - digits, or 0x and hexadecimal digits - is an address +const NUMBER_LABEL = /(?:^|\.)(?:\d+|0x[0-9a-f]*)$/; +const DOTTED_DECIMAL = /^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/; +// what an address is rewritten at: an escape, and a character a URI does not carry as it is +const REWRITTEN = /%[0-9A-Fa-f]{2}|[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=]/gu; +const UNRESERVED = /^[A-Za-z0-9\-._~]$/; +const UTF8 = new TextEncoder(); + +// a URL without what a browser strips before it reads one: the controls and the space at its ends, +// and every tab and line break inside +function stripped(text) { + let start = 0; + let end = text.length; + while (start < end && text.codePointAt(start) <= 0x20) start++; + while (end > start && text.codePointAt(end - 1) <= 0x20) end--; + return text.slice(start, end).replace(/[\t\n\r]/g, ''); +} + +// an escape in its one form - the character itself when a URI never needs it escaped, else its two +// digits in upper case - and any other character as its UTF-8 bytes, percent-encoded; half of a +// surrogate pair is the replacement character, as the encoder writes it +function rewritten(text) { + if (text.length === 3) { + const char = String.fromCodePoint(Number.parseInt(text.slice(1), 16)); + return UNRESERVED.test(char) ? char : text.toUpperCase(); + } + return Array.from(UTF8.encode(text), (byte) => `%${byte.toString(16).toUpperCase().padStart(2, '0')}`).join(''); +} + +/** A path, a query or a fragment in its one form: what a URI carries as it is stays, and the rest is percent-encoded. */ +function escaped(text) { + return text.replace(REWRITTEN, rewritten); +} + +/** + * A path in its one form, without its . and .. segments (RFC 3986, 5.2.4): a .. takes the segment + * before it and never the root, and a path that ends in one ends in a slash. + */ +function pathOf(text) { + const kept = []; + const segments = escaped(text || '/').split('/').slice(1); + segments.forEach((segment, index) => { + if (segment === '..' && kept.length) kept.pop(); + if (segment !== '.' && segment !== '..') kept.push(segment); + else if (index === segments.length - 1) kept.push(''); + }); + return `/${kept.join('/')}`; +} + +/** + * An IPv6 address in its one short form: its groups in lower-case hexadecimal without leading zeros, + * and the first of its longest runs of two or more zero groups as a double colon - the form the URL + * standard writes, which the runtime gives of a text that is such an address. Undefined for a text + * the runtime's reader does not take. + */ +function ipv6Text(text) { + try { + return new URL(`http://[${text}]/`).hostname.slice(1, -1); + } catch { + return undefined; + } +} + +// the port a URL names - ASCII digits, from 1 to 65535 - or the scheme's own for none +function urlPort(text, defaultPort) { + if (!text) return defaultPort; + const port = DIGITS.test(text) ? whole(text) : undefined; + if (port === undefined || port < 1 || port > 65535) { + throw new AppException(400, INVALID_PORT); + } + return port; +} + +// what the brackets of a URL hold, as the short form of the IPv6 address it is; a zone, an IPv4 +// address and anything else is no address the tools read +function bracketedAddress(inside) { + const address = inside.includes('%') || isIP(inside) !== 6 ? undefined : ipv6Text(inside); + if (address === undefined) { + throw new AppException(400, NOT_A_WEB_ADDRESS); + } + return address; +} + +// the host a URL names outside brackets, in lower case: a name, or an IPv4 address in dotted decimal - +// which a host is as soon as its last label spells a number - without the dots at its end +function urlHost(name) { + const host = name.toLowerCase(); + const bare = withoutTrailingDots(host); + if (!bare) { + throw new AppException(400, 'url has no host'); + } + if (!HOST_NAME.test(name)) { + throw new AppException(400, INVALID_HOST); + } + if (!NUMBER_LABEL.test(bare)) return host; + if (!DOTTED_DECIMAL.test(bare) || bare.split('.').some((part) => Number(part) > 255)) { + throw new AppException(400, `${name} ${NOT_DOTTED_DECIMAL}`); + } + return bare; +} + +// the host and the port of a URL's authority: an address in brackets and what follows them, or a +// name up to its first colon +function urlHostAndPort(authority, defaultPort) { + if (!authority.startsWith('[')) { + const colon = authority.indexOf(':'); + const name = colon < 0 ? authority : authority.slice(0, colon); + return { host: urlHost(name), port: urlPort(colon < 0 ? '' : authority.slice(colon + 1), defaultPort) }; + } + const close = authority.indexOf(']'); + const rest = authority.slice(close + 1); + if (close < 0 || (rest && !rest.startsWith(':'))) { + throw new AppException(400, NOT_A_WEB_ADDRESS); + } + return { host: bracketedAddress(authority.slice(1, close)), port: urlPort(rest.slice(1), defaultPort) }; +} + +// a URL or a reference as its part before the query, its query - undefined for none - and its fragment +function splitReference(text) { + const hash = text.indexOf('#'); + const rest = hash < 0 ? text : text.slice(0, hash); + const mark = rest.indexOf('?'); + return { + head: mark < 0 ? rest : rest.slice(0, mark), + query: mark < 0 ? undefined : rest.slice(mark + 1), + fragment: hash < 0 ? '' : text.slice(hash + 1) + }; +} + +/** + * A web address taken apart, each part in its one form - the scheme, the host (an IPv6 address + * without its brackets), the port it means, the path, the query and the fragment, empty for none - + * with what is made of them: the authority (the host, in brackets when it is an IPv6 address, and + * the port when it is not the scheme's own), the target (the path and the query, as a request names + * them), the url (the address in its one form, without its fragment) and the href (with it). + */ +function webAddress(scheme, host, port, path, query, fragment = '') { + const bracketed = host.includes(':') ? `[${host}]` : host; + const authority = port === DEFAULT_PORTS.get(scheme) ? bracketed : `${bracketed}:${port}`; + const target = query ? `${path}?${query}` : path; + const url = `${scheme}://${authority}${target}`; + const href = fragment ? `${url}#${fragment}` : url; + // an address the tools take: a longer one is a 400, so what is asked of a robots.txt and of a server has a bound + if (href.length > MAX_URL_LENGTH) { + throw new AppException(400, TOO_LONG); + } + return { scheme, host, port, path, query, fragment, authority, target, url, href }; +} + +/** A URL taken apart by the rules above; one they do not take is a 400 that names the rule. */ +export function readUrl(text) { + const { head, query, fragment } = splitReference(stripped(text)); + const scheme = SCHEME.exec(head); + const name = scheme ? scheme[1].toLowerCase() : ''; + if (!scheme || !DEFAULT_PORTS.has(name) || !head.startsWith('//', scheme[0].length)) { + throw new AppException(400, NOT_A_WEB_ADDRESS); + } + const rest = head.slice(scheme[0].length + 2); + const slash = rest.indexOf('/'); + const authority = slash < 0 ? rest : rest.slice(0, slash); + if (authority.includes('@')) { + throw new AppException(400, 'url must not carry credentials'); + } + const { host, port } = urlHostAndPort(authority, DEFAULT_PORTS.get(name)); + return webAddress(name, host, port, pathOf(slash < 0 ? '' : rest.slice(slash)), escaped(query ?? ''), escaped(fragment)); +} + +/** + * A reference as the address it names when it is read at a base address (RFC 3986, 5.2): an address + * of its own, one that starts at the base's scheme, at its host or at its path, or the base itself + * with another query or fragment. A reference that names the base's own scheme and no host is read + * as what follows the scheme, the loose reading of 5.2.2. + */ +function resolved(base, text) { + const { head: written, query, fragment } = splitReference(text); + const scheme = SCHEME.exec(written); + if (scheme && (scheme[1].toLowerCase() !== base.scheme || written.startsWith('//', scheme[0].length))) return readUrl(text); + const head = scheme ? written.slice(scheme[0].length) : written; + if (head.startsWith('//')) return readUrl(`${base.scheme}:${text}`); + let path = base.path; + if (head.startsWith('/')) path = head; + else if (head) path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + head; + const ownQuery = !head && query === undefined ? base.query : query ?? ''; + return webAddress(base.scheme, base.host, base.port, pathOf(path), escaped(ownQuery), escaped(fragment)); +} + +/** + * A reference found at an address - a link of a page, the Location of a redirect - as the address it + * names, in its one form and with its fragment. A reference that names no web address stays as it + * is written, without what a browser strips from it. + */ +export function resolveUrl(base, reference) { + const text = stripped(reference); + try { + return resolved(readUrl(base), text).href; + } catch (e) { + if (!(e instanceof AppException)) throw e; + return text; + } +} + // --- HTML to text, in-house ---------------------------------------------------------------------- const DROP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'svg', 'nav', 'header', 'footer']); @@ -1589,12 +2048,16 @@ class HtmlText { if (BLOCK_TAGS.has(tag)) this.openBlock(); } - /** Open a link when the element has a target a reader can follow; the link that was open is closed first. */ + /** + * Open a link when the element has a target a reader can follow - not a fragment, a script, a mail + * or a phone link, told once what a browser strips from a target is gone; the link that was open + * is closed first. + */ startLink(attrs) { - const href = attrs.find(([name]) => name === 'href')?.[1]; - if (href && !/^(#|javascript:|mailto:|tel:)/i.test(href)) { + const target = stripped(attrs.find(([name]) => name === 'href')?.[1] ?? ''); + if (target && !/^(#|javascript:|mailto:|tel:)/i.test(target)) { this.endLink(); - this.href = this.baseUrl ? safeJoin(this.baseUrl, href) : href; + this.href = this.baseUrl ? resolveUrl(this.baseUrl, target) : target; this.linkText = []; } } @@ -1666,15 +2129,6 @@ class HtmlText { } } -// a reference joined to the address it was read at; one that cannot be read as an address stays as written -function safeJoin(base, href) { - try { - return new URL(href, base).href; - } catch { - return href; - } -} - // how a tag starts: `<`, a slash when it closes an element, and the name const TAG_START = /^<(\/?)([A-Za-z][A-Za-z0-9:-]*)/; @@ -1806,7 +2260,7 @@ export function parseHostRules(entries) { // one entry as a rule: its scheme - https unless it names one - its host pattern in lower case, and its port function hostRule(entry) { - let text = entry.trim(); + let text = trimBlanks(entry); let scheme = 'https'; if (text.includes('://')) { [scheme, text] = [text.slice(0, text.indexOf('://')).toLowerCase(), text.slice(text.indexOf('://') + 3)]; @@ -1834,25 +2288,34 @@ function hostAndPort(entry, text) { if (text.startsWith('[')) { const close = text.indexOf(']'); if (close < 0) throw notAHostPattern(entry); - const inside = text.slice(1, close); + const address = addressText(text.slice(1, close)); const rest = text.slice(close + 1); - if (isIP(inside)) { + if (address !== undefined) { if (rest && !rest.startsWith(':')) throw notAHostPattern(entry); - return { host: inside, port: rest ? portOf(entry, rest.slice(1)) : undefined }; + return { host: address, port: rest ? portOf(entry, rest.slice(1)) : undefined }; } } if ((text.match(/:/g) ?? []).length === 1) { return { host: text.slice(0, text.indexOf(':')), port: portOf(entry, text.slice(text.indexOf(':') + 1)) }; } - return { host: text, port: undefined }; + return { host: addressText(text) ?? text, port: undefined }; } +// an address as a URL's host names it - an IPv6 address in its one short form - or undefined for a +// text that is no address, or one with a zone, which no URL the tools read can name +function addressText(text) { + const family = text.includes('%') ? 0 : isIP(text); + if (!family) return undefined; + return family === 6 ? ipv6Text(text) : text; +} + +// the port an entry names: ASCII digits, from 1 to 65535 function portOf(entry, text) { - const port = /^\d+$/.test(text) ? Number(text) : Number.NaN; - if (Number.isNaN(port)) { + if (!DIGITS.test(text)) { throw new ToolsError(`${WEB_ALLOW}: ${entry} - the port must be a number`); } - if (port < 1 || port > 65535) { + const port = whole(text); + if (port === undefined || port < 1 || port > 65535) { throw new ToolsError(`${WEB_ALLOW}: ${entry} - the port must be between 1 and 65535`); } return port; @@ -1933,11 +2396,6 @@ export function addressKind(address) { return ADDRESS_RANGES.find((range) => range.family === family && range.subnet.check(text, `ipv${family}`))?.kind; } -// the port a URL means when it names none -function defaultPortOf(scheme) { - return scheme === 'https' ? 443 : 80; -} - /** The allowlist and the limits of the web tools. */ export class WebSandbox { constructor({ rules, allowPrivate = false, maxBytes = DEFAULT_WEB_MAX_BYTES, timeoutMs = DEFAULT_WEB_TIMEOUT_MS, @@ -1969,27 +2427,12 @@ export class WebSandbox { /** * The URL a tool may fetch, by the allowlist alone (no network): an http(s) URL without * credentials, whose host is listed for its scheme and port. Anything else is a 400 that names - * the rule; the fragment is dropped. + * the rule. The URL comes back in its one form, the fragment dropped. */ checkUrl(url) { - let parsed; - try { - parsed = new URL(url.trim()); - } catch { - throw new AppException(400, 'url must start with https:// (or http:// for a host listed with it)'); - } - const scheme = parsed.protocol.replace(/:$/, '').toLowerCase(); - if (scheme !== 'http' && scheme !== 'https') { - throw new AppException(400, 'url must start with https:// (or http:// for a host listed with it)'); - } - if (parsed.username || parsed.password) { - throw new AppException(400, 'url must not carry credentials'); - } - const host = withoutTrailingDots(parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase()); - if (!host) { - throw new AppException(400, 'url has no host'); - } - const port = parsed.port ? Number(parsed.port) : defaultPortOf(scheme); + const address = readUrl(trimBlanks(url)); + const { scheme, port } = address; + const host = withoutTrailingDots(address.host); const { listed, allowed } = this.matches(host, scheme, port); if (!allowed) { if (listed && scheme === 'http') { @@ -2000,10 +2443,8 @@ export class WebSandbox { } throw new AppException(400, `${host} is not one of the sites this agent may reach (${WEB_ALLOW})`); } - parsed.hash = ''; - parsed.username = ''; - parsed.password = ''; - return { url: parsed.href, scheme, host, port, hostname: parsed.hostname, pathname: parsed.pathname, search: parsed.search }; + const hostname = address.host.includes(':') ? `[${address.host}]` : address.host; + return { url: address.url, scheme, host, port, hostname, pathname: address.path, search: address.query ? `?${address.query}` : '' }; } /** @@ -2045,9 +2486,9 @@ export function loadWebSandbox({ log = defaultLog } = {}) { rules: parseHostRules(entries), allowPrivate: boolSetting(WEB_ALLOW_PRIVATE, false), maxBytes: intSetting(WEB_MAX_BYTES, DEFAULT_WEB_MAX_BYTES, { floor: 1024, log }), - timeoutMs: intSetting(WEB_TIMEOUT_MS, DEFAULT_WEB_TIMEOUT_MS, { floor: MIN_WEB_TIMEOUT_MS, log }), + timeoutMs: intSetting(WEB_TIMEOUT_MS, DEFAULT_WEB_TIMEOUT_MS, { floor: MIN_WEB_TIMEOUT_MS, most: MAX_TIMER_MS, log }), crawlMaxPages: intSetting(WEB_CRAWL_MAX_PAGES, CRAWL_PAGES_CAP, { cap: CRAWL_PAGES_CAP, log }), - crawlDelayMs: intSetting(WEB_CRAWL_DELAY_MS, DEFAULT_CRAWL_DELAY_MS, { floor: 0, log }), + crawlDelayMs: intSetting(WEB_CRAWL_DELAY_MS, DEFAULT_CRAWL_DELAY_MS, { floor: 0, most: MAX_TIMER_MS, log }), pageMaxChars: intSetting(WEB_PAGE_MAX_CHARS, DEFAULT_PAGE_MAX_CHARS, { floor: 100, log }) }); } @@ -2156,52 +2597,137 @@ function requestOnce(target, pinned, { timeoutMs, maxBytes }) { }); } +// --- robots.txt, read by RFC 9309 - the same reader in both packs -------------------------------- + +// a text without the spaces and the tabs at its start and at its end - read from the ends, so a +// line of any length costs its length once +function trimSpaces(text) { + let start = 0; + let end = text.length; + while (start < end && (text[start] === ' ' || text[start] === '\t')) start++; + while (end > start && (text[end - 1] === ' ' || text[end - 1] === '\t')) end--; + return text.slice(start, end); +} + +// one line of robots.txt as its field, in lower case, and its value; undefined for a line without a +// colon. A comment runs from a # to the end of the line. +function robotsLine(line) { + const hash = line.indexOf('#'); + const text = hash < 0 ? line : line.slice(0, hash); + const colon = text.indexOf(':'); + if (colon < 0) return undefined; + return { field: trimSpaces(text.slice(0, colon)).toLowerCase(), value: trimSpaces(text.slice(colon + 1)) }; +} + /** - * A line of robots.txt without its comment, which runs from a `#` to the end of the line. A `#` that a - * line break of another kind follows - a lone carriage return, a Unicode separator - starts none. + * The groups of a robots.txt, each as the agents it names and its rules - whether a rule allows, and + * its path pattern. A group starts at a user-agent line, takes the user-agent lines that follow it, + * and then the Allow and Disallow lines up to the next user-agent line; any other line counts for + * nothing. A line ends at a carriage return, a line feed, or the two together, and a user-agent line + * names the product token it starts with: letters, hyphens and underscores. */ -function withoutComment(line) { - const lastBreak = Math.max(line.lastIndexOf('\n'), line.lastIndexOf('\r'), line.lastIndexOf('\u2028'), line.lastIndexOf('\u2029')); - const hash = line.indexOf('#', lastBreak + 1); - return hash < 0 ? line : line.slice(0, hash); +function robotsGroups(text) { + const groups = []; + for (const line of text.split(/\r\n?|\n/)) { + const { field, value } = robotsLine(line) ?? {}; + if (field === 'user-agent') { + if (!groups.length || groups.at(-1).rules.length) groups.push({ agents: [], rules: [] }); + groups.at(-1).agents.push(value === '*' ? '*' : /^[A-Za-z_-]*/.exec(value)[0].toLowerCase()); + } else if ((field === 'allow' || field === 'disallow') && groups.length) { + groups.at(-1).rules.push({ allow: field === 'allow', written: value }); + } + } + return groups; +} + +/** + * A part of a robots pattern - what stands between two of its stars - with what a long part is + * looked for by. The engine's own search may compare a part with the path at every place of the + * path, as far as the part goes: for a short part that is a bounded number of comparisons a place, + * for a long one it is not. + */ +function partOf(text) { + if (text.length <= LONG_LITERAL) return { text }; + const units = unitsOf(text); + return { text, units, repeats: repeatsOf(units) }; } -/** A minimal robots.txt: the rules of the group for our token, else the `*` group; the longest matching rule wins, Allow over Disallow on a tie. */ +/** Where a long part starts in a subject's units at or after a place, or -1: a unit is never looked at again once it is passed. */ +function placeOfLong(subject, { units, repeats }, from) { + let matched = 0; + for (let at = from; at < subject.length; at++) { + while (matched > 0 && subject[at] !== units[matched]) matched = repeats[matched - 1]; + if (subject[at] === units[matched]) matched += 1; + if (matched === units.length) return at - matched + 1; + } + return -1; +} + +/** + * Whether a subject is the parts of a pattern in their order, with any run of characters where a + * star stood between two of them: the first part starts the subject, the last one ends it, and each + * part between them is looked for once, from where the part before it ended. So the time is bounded + * by the subject's length plus the pattern's, never by their product - a robots.txt is another + * site's text, and it is asked about every page. + */ +function inOrder(parts, subject) { + const first = parts[0].text; + const last = parts.at(-1).text; + if (parts.length === 1) return subject === first; + let at = first.length; + const end = subject.length - last.length; + if (end < at || !subject.startsWith(first) || !subject.endsWith(last)) return false; + let units; // the subject as its units, made once and only when a part is long + for (let index = 1; index < parts.length - 1; index++) { + const part = parts[index]; + let found; + if (part.units) { + units ??= unitsOf(subject); + found = placeOfLong(units, part, at); + } else { + found = subject.indexOf(part.text, at); + } + if (found < 0 || found + part.text.length > end) return false; + at = found + part.text.length; + } + return true; +} + +/** + * The rules of a robots.txt for the tools, by RFC 9309: the rules of every group that names the + * tools' product token, in any letter case - or, when no group names it, of every group for `*`. A + * rule without a pattern says nothing. A pattern is compared in the form the tools give a path, and + * matched part by part between its stars - with a star added at its end unless a $ ends it there - + * so a rule takes a time bounded by its length plus the path's, however many stars it has. + * + * canFetch says whether a path - with its query, as an address names the two - may be fetched: the + * rule with the longest pattern that matches decides, an Allow before a Disallow of the same length; + * a path no rule matches is allowed, and so is /robots.txt itself. + */ export function parseRobots(text) { - const groups = []; - let current; - for (const rawLine of text.split(/\r?\n/)) { - const line = withoutComment(rawLine).trim(); - if (!line) continue; - const colon = line.indexOf(':'); - if (colon < 0) continue; - const field = line.slice(0, colon).trim().toLowerCase(); - const value = line.slice(colon + 1).trim(); - if (field === 'user-agent') { - if (!current || current.rules.length) { - current = { agents: [], rules: [] }; - groups.push(current); + const groups = robotsGroups(text); + const token = ROBOTS_AGENT.toLowerCase(); + const agent = groups.some((group) => group.agents.includes(token)) ? token : '*'; + const rules = []; + for (const group of groups.filter((candidate) => candidate.agents.includes(agent))) { + for (const { allow, written } of group.rules) { + const pattern = escaped(written); + if (pattern) { + const matched = pattern.endsWith('$') ? pattern.slice(0, -1) : `${pattern}*`; + rules.push({ allow, length: pattern.length, parts: matched.split('*').map(partOf) }); } - current.agents.push(value.toLowerCase()); - } else if ((field === 'allow' || field === 'disallow') && current) { - current.rules.push({ allow: field === 'allow', path: value }); } } - const token = ROBOTS_AGENT.toLowerCase(); - const group = groups.find((g) => g.agents.some((a) => a !== '*' && token.includes(a))) ?? groups.find((g) => g.agents.includes('*')); return { canFetch(path) { - if (!group) return true; - let best; - for (const rule of group.rules) { - if (!rule.path) continue; - const pattern = '^' + rule.path.split('*').map((p) => p.replace(/[.+?^${}()|[\]\\]/g, String.raw`\$&`)).join('.*').replace(/\\\$$/, '$'); - if (!new RegExp(pattern).test(path)) continue; - if (!best || rule.path.length > best.path.length || (rule.path.length === best.path.length && rule.allow && !best.allow)) { - best = rule; - } + const subject = escaped(path); + if (subject === '/robots.txt') return true; + let best = { length: 0, allow: true }; + for (const rule of rules) { + const better = rule.length > best.length || (rule.length === best.length && rule.allow && !best.allow); + if (better && inOrder(rule.parts, subject)) best = rule; } - return best ? best.allow : true; + return best.allow; } }; } @@ -2211,29 +2737,34 @@ function under(path, include) { return include.startsWith('/') ? path.startsWith(include) : path.includes(include); } -// the site a URL is on, as a crawl compares it: its scheme, its host as the URL names it and its port, the scheme's own when it names none -function siteOf(parsed) { - const scheme = parsed.protocol.replace(/:$/, '').toLowerCase(); - const port = parsed.port ? Number(parsed.port) : defaultPortOf(scheme); - return `${scheme}://${parsed.hostname.toLowerCase()}:${port}`; +// the site an address is on, as a crawl compares it: its scheme, its host and the port it means - the scheme's own when it names none +function siteOf(address) { + return `${address.scheme}://${address.host}:${address.port}`; } -/** The links of a page that a crawl goes on to: on its own site and inside its include, each once and without its fragment, one link deeper. */ +// a link as the address it is, or undefined for one that is no web address the tools read +function linkAddress(link) { + try { + return readUrl(link); + } catch (e) { + if (!(e instanceof AppException)) throw e; + return undefined; + } +} + +/** + * The links of a page that a crawl goes on to, one link deeper: the ones on its own site and inside + * its include, each once, in its one form and without its fragment. A link that is no web address + * the tools read is passed over. + */ function followLinks(links, depth, crawl) { for (const link of links) { - let candidate; - try { - candidate = new URL(link); - } catch { - continue; - } - if (siteOf(candidate) !== crawl.site) continue; - if (crawl.include && !under(candidate.pathname, crawl.include)) continue; - candidate.hash = ''; - const normalized = candidate.href; - if (!crawl.seen.has(normalized)) { - crawl.seen.add(normalized); - crawl.queue.push([normalized, depth + 1]); + const address = linkAddress(link); + if (address === undefined || siteOf(address) !== crawl.site) continue; + if (crawl.include && !under(address.path, crawl.include)) continue; + if (!crawl.seen.has(address.url)) { + crawl.seen.add(address.url); + crawl.queue.push([address.url, depth + 1]); } } } @@ -2260,7 +2791,7 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { } const location = response.headers.location; if (REDIRECT_STATUSES.includes(response.status) && location) { - current = safeJoin(target.url, location); + current = resolveUrl(target.url, location); continue; } const [type, ...params] = String(response.headers['content-type'] ?? '').split(';'); @@ -2279,7 +2810,7 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { const url = stringArg(args, 'url'); const mode = choiceArg(args, 'as', FETCH_MODES, { defaultValue: 'text' }); const fetched = await fetch(url); - const host = new URL(fetched.url).hostname; + const host = readUrl(fetched.url).host; if (!isHtmlType(fetched.contentType) && !isTextType(fetched.contentType)) { log.info(`web.fetch ${host} ${fetched.status} ${fetched.data.length} bytes - not text`); throw new AppException(400, `the response is ${fetched.contentType || 'of an unknown type'}, not text`); @@ -2299,7 +2830,7 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { }; } - /** The site's robots.txt, read through the same checks; a site without one allows all. */ + /** The site's robots.txt, read through the same checks; a site without one, or with one that cannot be read, allows all. */ async function robots(start) { const robotsUrl = `${start.scheme}://${hostHeader(start)}/robots.txt`; let fetched; @@ -2363,15 +2894,17 @@ export function createWebTools(sandbox, { log = defaultLog } = {}) { throw new AppException(400, 'include must be a string'); } const start = sandbox.checkUrl(url); - const site = siteOf(new URL(start.url)); + const site = siteOf(readUrl(start.url)); const rules = await robots(start); + // the include is compared with a link's path, so it is put in the form a path is given + if (typeof include === 'string') include = escaped(include); const crawl = { host: start.host, site, include, maxDepth, queue: [[start.url, 0]], seen: new Set([start.url]), pages: [], visited: 0, truncated: false, budget: crawlResultMaxChars }; while (crawl.queue.length && crawl.pages.length < maxPages) { const [current, depth] = crawl.queue.shift(); - if (rules && !rules.canFetch(new URL(current).pathname)) continue; + if (rules && !rules.canFetch(readUrl(current).target)) continue; const spent = await visitPage(crawl, current, depth); if (spent) break; } @@ -2432,7 +2965,7 @@ export async function loadGraphSandbox({ log = defaultLog, driver = undefined } write: boolSetting(GRAPH_WRITE, false), delete: boolSetting(GRAPH_DELETE, false), maxRows: intSetting(GRAPH_MAX_ROWS, ROWS_DEFAULT, { cap: ROWS_CAP, log }), - timeoutMs: intSetting(GRAPH_TIMEOUT_MS, DEFAULT_GRAPH_TIMEOUT_MS, { floor: MIN_WEB_TIMEOUT_MS, log }), + timeoutMs: intSetting(GRAPH_TIMEOUT_MS, DEFAULT_GRAPH_TIMEOUT_MS, { floor: MIN_WEB_TIMEOUT_MS, most: MAX_TIMER_MS, log }), ingestMaxNodes: intSetting(GRAPH_INGEST_MAX_NODES, DEFAULT_INGEST_MAX_NODES, { log }), neo4j }; @@ -2617,12 +3150,13 @@ function propertiesOf(value, where) { if (!isMap(value)) { throw new AppException(400, `${where}.properties must be a map`); } - const checked = {}; + const checked = []; for (const [name, item] of Object.entries(value)) { checkProperty(name, item, where); - if (item !== null && item !== undefined) checked[name] = item; + if (item !== null && item !== undefined) checked.push([name, item]); } - return checked; + // made of its entries, so a property named __proto__ is one of them like any other + return Object.fromEntries(checked); } function keyOf(value, where) { @@ -3305,3 +3839,8 @@ if (isMain) { export function setCrawlResultMaxChars(value) { crawlResultMaxChars = value; } + +/** A test hook: the scan bound of a walk (the module constant, until this is called) may be lowered to prove the cut. */ +export function setScanLimit(value) { + scanLimit = value; +} diff --git a/extensions/agent-tools/resources/application.yml b/extensions/agent-tools/resources/application.yml index 610ea333..7ec0bcbc 100644 --- a/extensions/agent-tools/resources/application.yml +++ b/extensions/agent-tools/resources/application.yml @@ -37,6 +37,9 @@ tools.file.hidden: false tools.file.write.extensions: '' # a line file.search returns is cut to this many characters tools.file.line.max.chars: 500 +# how long a file.search by regular expression may take, in milliseconds (100 at least): the search +# is ended there and answers a 408 +tools.file.search.timeout.ms: 10000 # the most characters file.extract returns of a document (PDF and Word need the documents extra: # npm install --save-dev mammoth pdfjs-dist; without them file.extract does not register) tools.file.extract.max.chars: 60000 diff --git a/test/agent-tools.test.mjs b/test/agent-tools.test.mjs index a8388838..e110e970 100644 --- a/test/agent-tools.test.mjs +++ b/test/agent-tools.test.mjs @@ -21,6 +21,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, relative } from 'node:path'; import { after, before, test } from 'node:test'; import { fileURLToPath } from 'node:url'; +import workerThreads from 'node:worker_threads'; import neo4j from 'neo4j-driver'; import { AppException, appConfig, FunctionRegistry, Platform, PostOffice } from 'mercury-composable'; import * as tools from '../extensions/agent-tools/agent-tools.mjs'; @@ -81,6 +82,25 @@ function includes(text, part) { function probes(block) { return block.split('\n').filter((line) => line && !line.startsWith('#')).map((line) => line.trim().split(/\s+/)); } +/** The rows of a block that says `probe => answer`: every line that is not a comment. */ +function answers(block) { + const lines = block.split('\n').filter((line) => line && !line.startsWith('#')); + return lines.map((line) => [line.slice(0, line.indexOf(' => ')), line.slice(line.indexOf(' => ') + 4)]); +} +/** A probe's text with every \uXXXX in it as the character it names. */ +function decoded(text) { + return text.replace(/\\u([0-9a-f]{4})/g, (_, digits) => String.fromCodePoint(Number.parseInt(digits, 16))); +} +/** What a call answers, as the probes write it: the answer as JSON, the status and the message of a refusal, or the message the boot stops with. */ +async function told(call) { + try { + return JSON.stringify(await call()); + } catch (e) { + if (e instanceof tools.ToolsError) return e.message; + if (e instanceof AppException) return `${e.status} ${e.message}`; + throw e; + } +} // --- the workspace ------------------------------------------------------------------------------- @@ -181,6 +201,101 @@ test('arguments are checked against the row', async () => { } }); +// The probes of the number rule and of the switch rule. The Python twin's test file carries the +// same two texts, line for line: a value is a number, or a switch, to both packs or to neither. +const NUMBER_PROBES = String.raw` +# a value as JSON, what an argument that is a whole number makes of it - max_bytes of file_read, on a file of 20 +# characters: how many it read, or the refusal - and what a setting makes of it - tools.file.max.bytes: the +# number it is, or why the boot stops +5 => 5 | 5 +5.0 => 5 | 5 +1 => 1 | 1 +9007199254740991 => 20 | 9007199254740991 +null => 20 | 262144 +5.5 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +0 => 400 max_bytes must be at least 1 | tools.file.max.bytes must be at least 1 +-1 => 400 max_bytes must be at least 1 | tools.file.max.bytes must be at least 1 +9007199254740992 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +1e20 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +1e400 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +-1e400 => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +true => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +false => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +[5] => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +{} => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +# a text of digits is a number to a setting, with white space around it at most, and never to an argument +"5" => 400 max_bytes must be an integer | 5 +" 5 " => 400 max_bytes must be an integer | 5 +"\u00a05\u3000" => 400 max_bytes must be an integer | 5 +"00000000000000000000005" => 400 max_bytes must be an integer | 5 +"9007199254740991" => 400 max_bytes must be an integer | 9007199254740991 +"9007199254740992" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"" => 400 max_bytes must be an integer | 262144 +"5 0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\ufeff5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"+5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"-5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"1_0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\u0665" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"\uff15" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"5.0" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"1e1" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"0x5" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +"true" => 400 max_bytes must be an integer | tools.file.max.bytes must be an integer +`; + +const SWITCH_PROBES = String.raw` +# a value as JSON, what an argument that is a switch makes of it - regex of file_search: the switch it is, or +# the refusal - and what a setting makes of it - tools.file.hidden: the switch it is, or why the boot stops +true => true | true +false => false | false +null => false | false +"" => 400 regex must be true or false | false +"true" => 400 regex must be true or false | true +"TRUE" => 400 regex must be true or false | true +"False" => 400 regex must be true or false | false +" true " => 400 regex must be true or false | true +"yes" => 400 regex must be true or false | tools.file.hidden must be true or false +"no" => 400 regex must be true or false | tools.file.hidden must be true or false +"on" => 400 regex must be true or false | tools.file.hidden must be true or false +"off" => 400 regex must be true or false | tools.file.hidden must be true or false +"1" => 400 regex must be true or false | tools.file.hidden must be true or false +"0" => 400 regex must be true or false | tools.file.hidden must be true or false +"maybe" => 400 regex must be true or false | tools.file.hidden must be true or false +1 => 400 regex must be true or false | tools.file.hidden must be true or false +0 => 400 regex must be true or false | tools.file.hidden must be true or false +5 => 400 regex must be true or false | tools.file.hidden must be true or false +[] => 400 regex must be true or false | tools.file.hidden must be true or false +`; + +test('numbers and switches are read by one rule in both packs', async () => { + const root = mkdtempSync(join(tmpdir(), 'agent-tools-numbers-')); + writeFileSync(join(root, 'twenty.txt'), 'abcdefghijklmnopqrst'); + writeFileSync(join(root, 'lines.txt'), 'abc\na.c\n'); + const { files } = await fileTools(root); + const setting = async (key, value, field) => { + configure({ [tools.FILE_ROOT]: root, [key]: value }); + const answer = await told(async () => (await tools.loadFileSandbox({ log: ledger() }))[field]); + configure({ [key]: undefined }); + return answer; + }; + const read = async (value) => (await files.read({}, { path: 'twenty.txt', max_bytes: value })).text.length; + // as an expression a.c is in both lines, as a literal in one + const isExpression = async (value) => (await files.search({}, { pattern: 'a.c', regex: value, glob: 'lines.txt' })).matches.length === 2; + const wrong = []; + for (const [written, expected] of answers(NUMBER_PROBES)) { + const value = JSON.parse(written); + const got = `${await told(() => read(value))} | ${await setting(tools.FILE_MAX_BYTES, value, 'maxBytes')}`; + if (got !== expected) wrong.push([written, expected, got]); + } + for (const [written, expected] of answers(SWITCH_PROBES)) { + const value = JSON.parse(written); + const got = `${await told(() => isExpression(value))} | ${await setting(tools.FILE_HIDDEN, value, 'hidden')}`; + if (got !== expected) wrong.push([written, expected, got]); + } + assert.deepEqual(wrong, [], 'an argument is what its row says; a setting is a number or a switch'); +}); + test('file.write creates, refuses an existing file, overwrites and appends', async () => { const root = workspace(); const { files } = await fileTools(root); @@ -469,19 +584,21 @@ test('a search walks the files its glob names', async () => { 'a pattern that ends in a slash names folders, and a search reads files'); }); -/** The folders a call reads, relative to a root: the directory reader is wrapped for the time of the call. */ +/** The folders a call reads, relative to a root: the directory readers are wrapped for the time of the call. */ async function foldersRead(root, call) { const read = []; - const readdir = fsPromises.readdir; - fsPromises.readdir = (path, ...rest) => { - read.push(relative(root, String(path)) || '.'); - return readdir(path, ...rest); - }; + const readers = { opendir: fsPromises.opendir, readdir: fsPromises.readdir }; + for (const [name, reader] of Object.entries(readers)) { + fsPromises[name] = (path, ...rest) => { + read.push(relative(root, String(path)) || '.'); + return reader(path, ...rest); + }; + } syncBuiltinESMExports(); try { await call(); } finally { - fsPromises.readdir = readdir; + Object.assign(fsPromises, readers); syncBuiltinESMExports(); } return read.sort(); @@ -538,6 +655,163 @@ test('file.search counts lines by the line feed', async () => { assert.deepEqual(await found('four'), [[1, first]], 'the carriage return before a line feed ends the line'); }); +/** The worker threads started during a call, in the order they were started: the class is wrapped for the time of the call. */ +async function workersOf(call) { + const started = []; + const Worker = workerThreads.Worker; + workerThreads.Worker = class extends Worker { + constructor(...args) { + super(...args); + started.push(this); + } + }; + syncBuiltinESMExports(); + try { + await call(); + } finally { + workerThreads.Worker = Worker; + syncBuiltinESMExports(); + } + return started; +} + +test('a search by regular expression ends at its bound', async () => { + const root = workspace(); + writeFileSync(join(root, 'long.txt'), `${'a'.repeat(40)}b\n`); + const { files } = await fileTools(root, { 'tools.file.search.timeout.ms': 400 }); + let ticks = 0; + const ticking = setInterval(() => { ticks += 1; }, 10); + const began = performance.now(); + let outcome; + const workers = await workersOf(async () => { + outcome = await refusal(files.search({}, { pattern: '(a+)+$', regex: true, glob: 'long.txt' })); + }); + const took = performance.now() - began; + clearInterval(ticking); + assert.deepEqual(outcome, { status: 408, message: 'the search did not finish within 400 ms (tools.file.search.timeout.ms) - a simpler ' + + 'regular expression, or a narrower path or glob, finishes sooner' }); + assert.ok(took < 3000, 'the search ends at its bound, whatever the expression'); + assert.ok(ticks >= 10, 'the host went on while the expression ran'); + assert.deepEqual(workers.map((worker) => worker.threadId), [-1], 'the worker was ended and waited for: nothing is left running'); +}); + +test('a search by regular expression runs outside the host and leaves nothing running', async () => { + const { files } = await fileTools(workspace()); + const workers = await workersOf(async () => { + const found = await files.search({}, { pattern: String.raw`def \w+\(`, regex: true }); + assert.deepEqual(found.matches.map((m) => [m.path, m.line]), [['src/app.py', 1], ['src/app.py', 5]]); + const cased = await files.search({}, { pattern: 'TODO|later', regex: true, case_sensitive: true, context: 1 }); + assert.deepEqual(cased.matches.map((m) => [m.line, m.before, m.after]), + [[1, [], ['value = 1']], [3, ['value = 1'], ['TODO_COUNT = 2']], [4, ['# todo: later'], []]]); + const cut = await files.search({}, { pattern: 't.d.', regex: true, max_results: 2 }); + assert.deepEqual([cut.matches.length, cut.truncated], [2, true]); + for (const body of [{ pattern: '(', regex: true }, { pattern: '(', regex: true, path: 'empty' }, + { pattern: `${'('.repeat(30000)}a${')'.repeat(30000)}`, regex: true }]) { + const got = await refusal(files.search({}, body)); + assert.equal(got.status, 400, 'an expression that cannot be compiled is refused, files or none'); + assert.ok(got.message.startsWith('pattern is not a valid regular expression ('), got.message.slice(0, 80)); + } + assert.equal((await files.search({}, { pattern: 'todo' })).files_searched, 5); + }); + assert.equal(workers.length, 6, 'a worker for each search by regular expression, none for a literal'); + assert.deepEqual(workers.map((worker) => worker.threadId), Array(6).fill(-1), 'each worker was ended and waited for'); +}); + +test('a literal is searched in the host, in a time bounded by the line', async () => { + const root = workspace(); + writeFileSync(join(root, 'wide.txt'), `${'a'.repeat(300_000)}\nNeedle In The Hay\n`); + // a line of one letter, a line that repeats its own start, and a line with a character of two units + const repeated = `${'aab'.repeat(31)}aac`; + const said = `A Long Line of plain words, with one sign ${String.fromCodePoint(0x1f600)} in the middle of it, goes on past 64 units`; + writeFileSync(join(root, 'wider.txt'), `${'a'.repeat(600_000)}\n${repeated}\n${said}\n`); + const { files } = await fileTools(root); + const workers = await workersOf(async () => { + // literals that nearly match at every place of a line + for (const [pattern, glob] of [ + [`${'a'.repeat(40_000)}b`, 'wide.txt'], + [`${'a'.repeat(150_000)}b${'a'.repeat(150_000)}`, 'wider.txt'], + [`ab${'a'.repeat(299_998)}`, 'wider.txt'] + ]) { + const began = performance.now(); + assert.deepEqual((await files.search({}, { pattern, glob })).matches, []); + assert.ok(performance.now() - began < 5000, 'a literal of any length costs the length of the line'); + } + const found = await files.search({}, { pattern: 'needle in the HAY', glob: 'wide.txt' }); + assert.deepEqual(found.matches.map((m) => [m.line, m.text]), [[2, 'Needle In The Hay']]); + assert.deepEqual((await files.search({}, { pattern: 'needle in the HAY', glob: 'wide.txt', case_sensitive: true })).matches, []); + // literals of 64 units and of more: the same answers on either side of that length + for (const [pattern, lines] of [ + [repeated.slice(3), [2]], + [repeated.slice(3, 67), [2]], + [repeated.slice(3, 68), [2]], + [said.slice(2).toUpperCase(), [3]], + [`${said.slice(2)}!`, []] + ]) { + const long = await files.search({}, { pattern, glob: 'wider.txt' }); + assert.deepEqual(long.matches.map((m) => m.line), lines, pattern); + } + const cased = { pattern: said.slice(2).toUpperCase(), glob: 'wider.txt', case_sensitive: true }; + assert.deepEqual((await files.search({}, cased)).matches, []); + }); + assert.deepEqual(workers, [], 'a literal needs no worker'); +}); + +test('a byte-order mark is no part of a text', async () => { + const root = workspace(); + const mark = Buffer.from([0xef, 0xbb, 0xbf]); + writeFileSync(join(root, 'bom.txt'), Buffer.concat([mark, Buffer.from('# title\nbody\n')])); + writeFileSync(join(root, 'bom.html'), Buffer.concat([mark, Buffer.from('

hello

')])); + writeFileSync(join(root, 'two.txt'), Buffer.concat([mark, mark, Buffer.from('x\n')])); + const { files } = await fileTools(root); + assert.deepEqual(await files.read({}, { path: 'bom.txt' }), { path: 'bom.txt', bytes: 16, text: '# title\nbody\n', truncated: false }); + assert.equal((await files.read({}, { path: 'bom.txt', max_bytes: 4 })).text, '#'); + assert.equal((await files.read({}, { path: 'bom.txt', max_bytes: 2 })).text, ''); + assert.equal((await files.read({}, { path: 'two.txt' })).text, '\ufeffx\n', 'the mark at the start, once'); + const first = (await files.search({}, { pattern: '^#', regex: true, glob: 'bom.txt' })).matches; + assert.deepEqual(first.map((m) => [m.line, m.text]), [[1, '# title']]); + assert.equal((await files.search({}, { pattern: 'title', glob: 'bom.txt' })).matches[0].text, '# title'); + assert.equal((await files.extract({}, { path: 'bom.txt' })).text, '--- page 1 ---\n# title\nbody'); + assert.equal((await files.extract({}, { path: 'bom.html' })).text, '--- page 1 ---\nhello'); + for (const [charset, data, text] of [ + [undefined, Buffer.concat([mark, Buffer.from('User-agent: *\n')]), 'User-agent: *\n'], + ['utf-8', Buffer.concat([mark, Buffer.from('hi')]), 'hi'], + ['utf-16le', Buffer.from([0xff, 0xfe, 0x68, 0x00, 0x69, 0x00]), 'hi'], + ['iso-8859-1', Buffer.concat([mark, Buffer.from('hi')]), '\u00ef\u00bb\u00bfhi'] + ]) { + assert.equal(tools.decodeBody({ url: 'http://h/x', status: 200, contentType: 'text/plain', charset, data, truncated: false }), text, charset); + } +}); + +test('a walk looks at the scan limit and says that it was cut', async () => { + const files = await globFiles(); + try { + tools.setScanLimit(5); + let cut; + const read = await foldersRead(files.root, async () => { cut = await files.list({}, { glob: '**/nothing-is-named-so' }); }); + assert.deepEqual(cut, { entries: [], truncated: true }, 'the walk stopped, and the result says so'); + assert.deepEqual(read, ['.'], 'five entries of the root were looked at, and no folder beneath it'); + const listed = await files.list({}, {}); + assert.equal(listed.truncated, true); + assert.ok(listed.entries.length <= 5); + const searched = await files.search({}, { pattern: 'leaf', glob: '**/leaf.*' }); + assert.equal(searched.truncated, true); + assert.ok(searched.files_searched <= 5); + // a folder of two entries: the walk is cut only when an entry is left + tools.setScanLimit(2); + for (const body of [{ path: 'src/pkg/deep' }, { path: 'src/pkg/deep', glob: '*' }]) { + const whole = await files.list({}, body); + assert.deepEqual([whole.entries.map((e) => e.path), whole.truncated], [['src/pkg/deep/leaf.py', 'src/pkg/deep/leaf.txt'], false], JSON.stringify(body)); + } + tools.setScanLimit(1); + for (const body of [{ path: 'src/pkg/deep' }, { path: 'src/pkg/deep', glob: '*' }]) { + const part = await files.list({}, body); + assert.deepEqual([part.entries.length, part.truncated], [1, true], JSON.stringify(body)); + } + } finally { + tools.setScanLimit(tools.SCAN_LIMIT); + } +}); + // --- HTML to text -------------------------------------------------------------------------------- const PAGE = ` Page Title @@ -616,6 +890,67 @@ test('an address that cannot be read stays as written', () => { assert.deepEqual(links, ['http://[bad', '//[bad/x', 'http://h:port/x', 'https://h/ok']); }); +// The probes of a link. The Python twin's test file carries the same text, line for line. +const LINK_PROBES = String.raw` +# a link as a page at http://h/dir/page?q=1 writes it - \uXXXX for a character that cannot stand in a line - and +# the address it names, a dash for a target that is no link to follow +# a reference is read at the page's address: from its scheme, its host, its folder or itself +/docs/a => http://h/docs/a +b => http://h/dir/b +./b => http://h/dir/b +../b => http://h/b +../../b => http://h/b +b/../c/./d/ => http://h/dir/c/d/ +?x=2 => http://h/dir/page?x=2 +b?x=2#top => http://h/dir/b?x=2#top +//other.example/x => http://other.example/x +//OTHER.example:80/x => http://other.example/x +https://h/x => https://h/x +HTTP://H:80/x/../y#frag => http://h/y#frag +http://h./x => http://h./x +http:x => http://h/dir/x +http:/x => http://h/x +https:x => https:x +# what a browser strips is gone before the scheme is read +\u0020/docs/a\u0020 => http://h/docs/a +\u0009/docs/a\u000a => http://h/docs/a +/do\u0009cs/\u000aa => http://h/docs/a +\u0020javascript:run() => - +\u0009JavaScript:run() => - +java\u000ascript:run() => - +\u0020mailto:x@example.com => - +\u0020Tel:+1 => - +\u0020#top => - +\u0020\u0009 => - +\u00a0/docs/a => http://h/dir/%C2%A0/docs/a +# a backslash is no slash: it is a character a URI does not carry as it is +\\other.example\x => http://h/dir/%5C%5Cother.example%5Cx +/a\b?c\d => http://h/a%5Cb?c%5Cd +# the form of the path and the query +/a b?c d => http://h/a%20b?c%20d +/café => http://h/caf%C3%A9 +/%41%2f => http://h/A%2F +# no web address: the target stays as it is written +ftp://h/x => ftp://h/x +x:y => x:y +data:text/plain,hi => data:text/plain,hi +http://[bad => http://[bad +http://h:port/x => http://h:port/x +http://0177.0.0.1/ => http://0177.0.0.1/ +//h:99999/x => //h:99999/x +`; + +test('a link is read as a browser reads it', () => { + const wrong = []; + for (const [written, expected] of answers(LINK_PROBES)) { + const { text, links } = tools.htmlToText(`

x

`, 'http://h/dir/page?q=1', { markdown: true }); + const got = text === 'x' ? '-' : text.slice(4, -1); + const followed = got === '-' ? [] : [got.split('#', 1)[0]]; + if (got !== expected || JSON.stringify(links) !== JSON.stringify(followed)) wrong.push([written, expected, got, links]); + } + assert.deepEqual(wrong, [], 'a link names one address in both packs, written in one form'); +}); + // --- the web sandbox without a network ----------------------------------------------------------- test('host rules are parsed with scheme and port', () => { @@ -652,6 +987,53 @@ test('an allowlist entry that starts with a class is a pattern', () => { } }); +// The probes of an allowlist entry. The Python twin's test file carries the same text. +const ENTRY_PROBES = String.raw` +# an entry of tools.web.allow - \uXXXX for a character that cannot stand in a line - and the rule it is: its +# pattern, its scheme and its port, a dash for none; or why the boot stops +host:8443 => host https 8443 +host:080 => host https 80 +host:65535 => host https 65535 +http://host:8 => host http 8 +[::1]:8080 => ::1 https 8080 +# an address is written in its one form, as a URL's host is +[0:0:0:0:0:0:0:1]:8080 => ::1 https 8080 +[::FFFF:127.0.0.1] => ::ffff:7f00:1 https - +0:0:0:0:0:0:0:1 => ::1 https - +[127.0.0.1] => 127.0.0.1 https - +# a port is the digits 0 to 9, from 1 to 65535 +host:+8 => tools.web.allow: host:+8 - the port must be a number +host:-8 => tools.web.allow: host:-8 - the port must be a number +host: 8 => tools.web.allow: host: 8 - the port must be a number +host:1_0 => tools.web.allow: host:1_0 - the port must be a number +host:8.0 => tools.web.allow: host:8.0 - the port must be a number +host:0x50 => tools.web.allow: host:0x50 - the port must be a number +host:\u0668\u0660 => tools.web.allow: host:\u0668\u0660 - the port must be a number +host:\uff18\uff10 => tools.web.allow: host:\uff18\uff10 - the port must be a number +host:\u00b2 => tools.web.allow: host:\u00b2 - the port must be a number +host: => tools.web.allow: host: - the port must be a number +[::1]:+8 => tools.web.allow: [::1]:+8 - the port must be a number +host:0 => tools.web.allow: host:0 - the port must be between 1 and 65535 +host:65536 => tools.web.allow: host:65536 - the port must be between 1 and 65535 +host:99999999999999999999999999 => tools.web.allow: host:99999999999999999999999999 - the port must be between 1 and 65535 +`; + +test('an allowlist entry names its port in the digits 0 to 9', () => { + const wrong = []; + for (const [written, expected] of answers(ENTRY_PROBES)) { + let got; + try { + const rule = tools.parseHostRules([decoded(written)])[0]; + got = `${rule.pattern} ${rule.scheme} ${rule.port ?? '-'}`; + } catch (e) { + if (!(e instanceof tools.ToolsError)) throw e; + got = e.message; + } + if (got !== decoded(expected)) wrong.push([written, expected, got]); + } + assert.deepEqual(wrong, [], 'a port is ASCII digits from 1 to 65535, an address is in its one form'); +}); + test('an exclamation mark negates a class only when it is first', () => { const glob = tools.compileGlob('[b-a!x]'); assert.deepEqual(['x', '!', 'y'].map((name) => glob.test(name)), [true, true, false], @@ -1023,6 +1405,134 @@ test('a literal host is classified by the address it names', async () => { assert.deepEqual(wrong, [], 'the spelling of a literal never changes the kind of its address'); }); +// The probes of the tools' own reader of a URL. The Python twin's test file carries the same +// text, line for line. +const URL_READ_PROBES = String.raw` +# a URL - \uXXXX for a character that cannot stand in a line - and the one form the tools read it in, or the +# refusal; every host is listed, over http too +# the scheme and the host in lower case, the scheme's own port left out, an empty path a slash +https://docs.example.com/a/b?x=1#frag => https://docs.example.com/a/b?x=1 +https://DOCS.example.com => https://docs.example.com/ +HtTpS://Docs.Example.Com:443/x => https://docs.example.com/x +http://docs.example.com:80/x => http://docs.example.com/x +https://docs.example.com:80/x => https://docs.example.com:80/x +https://docs.example.com:0443/x => https://docs.example.com/x +https://docs.example.com:/x => https://docs.example.com/x +https://docs.example.com:65535/x => https://docs.example.com:65535/x +https://docs.example.com?x=1 => https://docs.example.com/?x=1 +https://docs.example.com#frag => https://docs.example.com/ +https://docs.example.com/p? => https://docs.example.com/p +https://docs.example.com/p?x=1?y=2 => https://docs.example.com/p?x=1?y=2 +http://a_b.example/ => http://a_b.example/ +http://A.B./x => http://a.b./x +http://xn--bcher-kva.example/ => http://xn--bcher-kva.example/ +# what a browser strips: the controls and the space at the ends, every tab and line break inside; and the white +# space both packs take, around the argument +\u0020https://docs.example.com/x\u0020 => https://docs.example.com/x +\u0009https://docs.example.com/x\u000a => https://docs.example.com/x +\u0000https://docs.example.com/x\u001f => https://docs.example.com/x +ht\u0009tps://docs.exa\u000ample.com/x\u000d => https://docs.example.com/x +\u00a0https://docs.example.com/x\u3000 => https://docs.example.com/x +\ufeffhttps://docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https://docs.example.com/x\u0085 => https://docs.example.com/x%C2%85 +# a backslash is no slash: it is a character a URI does not carry as it is +https:\\docs.example.com\x => 400 url must start with https:// (or http:// for a host listed with it) +https://docs.example.com\x/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +https://docs.example.com/a\b?c\d => https://docs.example.com/a%5Cb?c%5Cd +# no web address: another scheme, or no two slashes after it +ftp://docs.example.com/ => 400 url must start with https:// (or http:// for a host listed with it) +docs.example.com/page => 400 url must start with https:// (or http:// for a host listed with it) +//docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https:/docs.example.com/x => 400 url must start with https:// (or http:// for a host listed with it) +https:docs.example.com => 400 url must start with https:// (or http:// for a host listed with it) +# credentials, a host, a port +https://user@docs.example.com/ => 400 url must not carry credentials +https://user:pw@docs.example.com/ => 400 url must not carry credentials +https://@docs.example.com/ => 400 url must not carry credentials +https://docs.example.com/@x?y=@ => https://docs.example.com/@x?y=@ +https:///path => 400 url has no host +https:// => 400 url has no host +https://:443/ => 400 url has no host +https://./ => 400 url has no host +https://docs.example.com:0/x => 400 url has an invalid port +https://docs.example.com:65536/x => 400 url has an invalid port +https://docs.example.com:x/ => 400 url has an invalid port +https://docs.example.com:+8/ => 400 url has an invalid port +https://docs.example.com:8_0/ => 400 url has an invalid port +https://docs.example.com:\u0668/ => 400 url has an invalid port +https://docs.example.com:8:9/ => 400 url has an invalid port +http://[::1]:x/ => 400 url has an invalid port +# a name is letters, digits, hyphens, dots and underscores +http://b\u00fccher.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://ex%61mple.com/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://exa mple.com/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://a!b.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://\u212a.example/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +http://\uff11\uff12\uff17.\uff10.\uff10.\uff11/ => 400 url has an invalid host (a name is written in letters, digits, hyphens, dots and underscores) +# a host whose last label spells a number is an address, written in dotted decimal and no other way +http://1.2.3.4/ => http://1.2.3.4/ +http://1.2.3.4./ => http://1.2.3.4/ +http://0.0.0.0/ => http://0.0.0.0/ +http://255.255.255.255:8080/ => http://255.255.255.255:8080/ +http://0177.0.0.1/ => 400 0177.0.0.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://2130706433/ => 400 2130706433 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0x7f.1/ => 400 0x7f.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0X7F000001/ => 400 0X7F000001 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://127.1/ => 400 127.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://127.000.000.001/ => 400 127.000.000.001 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1.2.3.256/ => 400 1.2.3.256 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1.2.3.4.5/ => 400 1.2.3.4.5 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://foo.1/ => 400 foo.1 is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://0x/ => 400 0x is not an address in dotted decimal (four numbers from 0 to 255, without leading zeros) +http://1e3/ => http://1e3/ +http://1.2.3.4x/ => http://1.2.3.4x/ +# an IPv6 address stands in brackets, without a zone, and is written in its one short form +http://[::1]:8080/a => http://[::1]:8080/a +http://[0:0:0:0:0:0:0:1]/ => http://[::1]/ +http://[::FFFF:127.0.0.1]/ => http://[::ffff:7f00:1]/ +http://[2001:DB8:0:0:1:0:0:1]/ => http://[2001:db8::1:0:0:1]/ +http://[1:0:0:2:0:0:0:3]:80/ => http://[1:0:0:2::3]/ +http://[fe80::1%25eth0]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[fe80::1%eth0]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[127.0.0.1]/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[::1]x/ => 400 url must start with https:// (or http:// for a host listed with it) +http://[bad/ => 400 url must start with https:// (or http:// for a host listed with it) +# the path and the query: what a URI does not carry as it is becomes its bytes percent-encoded, an escape keeps +# its digits in upper case or becomes the letter, digit, hyphen, dot, underscore or tilde it stands for, and the +# path loses its . and .. segments +https://docs.example.com/a b?c d => https://docs.example.com/a%20b?c%20d +https://docs.example.com/café?é => https://docs.example.com/caf%C3%A9?%C3%A9 +https://docs.example.com/😀 => https://docs.example.com/%F0%9F%98%80 +https://docs.example.com/{y}|z^\u0060" => https://docs.example.com/%3Cx%3E%7By%7D%7Cz%5E%60%22 +https://docs.example.com/a;b=c,d/(x)!$&'*+@:[] => https://docs.example.com/a;b=c,d/(x)!$&'*+@:[] +https://docs.example.com/%41%7e%2f%3a%c3%a9 => https://docs.example.com/A~%2F%3A%C3%A9 +https://docs.example.com/a%zzb%?% => https://docs.example.com/a%25zzb%25?%25 +https://docs.example.com/a/../b => https://docs.example.com/b +https://docs.example.com/a/./b/ => https://docs.example.com/a/b/ +https://docs.example.com/a/%2e%2E/b => https://docs.example.com/b +https://docs.example.com/a/b/.. => https://docs.example.com/a/ +https://docs.example.com/a/b/. => https://docs.example.com/a/b/ +https://docs.example.com/../../x => https://docs.example.com/x +https://docs.example.com/a//b/.../c => https://docs.example.com/a//b/.../c +https://docs.example.com/p?a/../b => https://docs.example.com/p?a/../b +`; + +test('a url is read by one rule in both packs', () => { + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules(['http://*']) }); + const wrong = []; + for (const [written, expected] of answers(URL_READ_PROBES)) { + let got; + try { + got = sandbox.checkUrl(decoded(written)).url; + } catch (e) { + if (!(e instanceof AppException)) throw e; + got = `${e.status} ${e.message}`; + } + if (got !== expected) wrong.push([written, expected, got]); + } + assert.deepEqual(wrong, [], 'a URL has one form, and what is no URL is refused by the same words'); +}); + test('pin refuses private addresses unless allowed', async () => { const lookup = async (host) => (host === 'no-such-host.invalid' ? Promise.reject(new Error('ENOTFOUND')) : [{ address: '127.0.0.1', family: 4 }]); const closed = new tools.WebSandbox({ rules: tools.parseHostRules(['http://127.0.0.1', 'http://169.254.169.254', 'localhost']), lookup }); @@ -1053,6 +1563,205 @@ test('robots.txt rules: the longest match wins, Allow over Disallow on a tie', ( assert.equal(ours.canFetch('/docs'), true, 'our own group wins over *'); }); +// The probes of the robots.txt reader. The Python twin's test file carries the same text. +const ROBOTS_PROBES = String.raw` +# robots.txt files - each line of one after a bar, \r for a carriage return and \t for a tab - and under +# each file the paths a crawl asks about, with the answer +# the longest pattern that matches decides, and an Allow wins a tie +| User-agent: * +| Disallow: /private/ +| Allow: /private/public +| Disallow: /tie +| Allow: /tie +/docs/a allowed +/private/secret refused +/private/public/page allowed +/private allowed +/tie/x allowed +/robots.txt allowed +# the groups that name the tools' token, in any letter case and with a version, are one group, and no other counts +| User-agent: mercurycomposable +| Disallow: /only-us +| +| User-agent: * +| Disallow: / +| +| User-agent: MERCURYCOMPOSABLE/1.0 +| Disallow: /also-us +/only-us/x refused +/also-us refused +/docs allowed +# a group named by a part of the token is another agent's; the groups for * are one group +| User-agent: mercury +| Disallow: / +| User-agent: e +| Disallow: / +| User-agent: * +| Disallow: /a +| User-agent: * +| Disallow: /b +/a refused +/b/x refused +/c allowed +# the tools' own group decides even when it says nothing +| User-agent: MercuryComposable +| Disallow: +| User-agent: * +| Disallow: / +/anything allowed +# a star is any run of characters, a $ at the end of a pattern is the end of the path, and any other $ is itself +| User-agent: * +| Disallow: /*.pdf$ +| Disallow: /a*b +| Disallow: /img/*/raw +| Allow: /img/*/raw/ok$ +| Disallow: /end$ +| Disallow: /dollar$x +/x.pdf refused +/x.pdf?download allowed +/dir/x.pdf refused +/aXXb/more refused +/ab refused +/a allowed +/img/1/raw/x refused +/img/1/2/raw refused +/img/1/raw/ok allowed +/img/1/raw/ok/more refused +/end refused +/end/ allowed +/ended allowed +/dollar$x/y refused +# a pattern is matched against the path and the query, both in the form the tools give an address +| User-agent: * +| Disallow: /p?x=1 +| Disallow: /*?print= +| Disallow: /caf%C3%A9 +| Disallow: /a%2fb +| Disallow: /%7Euser +| Disallow: /sp ace +/p?x=1 refused +/p?x=12 refused +/p?y=1 allowed +/doc?print=1 refused +/doc allowed +/café refused +/caf%c3%a9/x refused +/a%2Fb refused +/a/b allowed +/~user/x refused +/%7euser refused +/sp%20ace refused +# a comment runs from a # to the end of its line; a line ends at a carriage return too; a field is read in any +# letter case, with spaces and tabs around it; a line without a colon, another record and a rule before any +# user-agent line count for nothing +| # a comment +| Disallow: /before-any-agent +| USER-AGENT : * # everyone +| \tdisallow\t:\t/tab # and a comment +| Crawl-delay: 10 +| Sitemap: https://h/sitemap.xml +| Disallow /no-colon +| DISALLOW: /upper\rDisallow: /cr +| Allow: /upper/ok#fragment +/before-any-agent allowed +/tab/x refused +/no-colon allowed +/upper/x refused +/cr refused +/upper/ok allowed +# only an Allow or a Disallow line ends the run of user-agent lines that starts a group +| User-agent: other +| Crawl-delay: 5 +| User-agent: * +| Disallow: /shared +| User-agent: third +| Disallow: /third +/shared refused +/third allowed +# a file without a group allows, and so does an empty one +| Disallow: / +/anything allowed +| +/anything allowed +# a pattern is matched from the start of the path, whatever it starts with +| User-agent: * +| Disallow: *.gif$ +| Disallow: private +/x.gif refused +/private allowed +# a rule of many stars is matched item by item +| User-agent: * +| Disallow: /*a*a*a*a*b +/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa allowed +/aaaab refused +`; + +/** The files of a block of robots probes, each with the paths asked about and the answers. */ +function robotsFiles(block) { + const files = []; + for (const line of block.split('\n')) { + if (!line || line.startsWith('#')) continue; + if (!line.startsWith('|')) { + files.at(-1).asked.push(line.split(' ')); + continue; + } + if (!files.length || files.at(-1).asked.length) files.push({ lines: [], asked: [] }); + files.at(-1).lines.push(line.slice(2).replaceAll(String.raw`\r`, '\r').replaceAll(String.raw`\t`, '\t')); + } + return files.map(({ lines, asked }) => [`${lines.join('\n')}\n`, asked]); +} + +test('robots.txt is read by RFC 9309 in both packs', () => { + const wrong = []; + for (const [text, asked] of robotsFiles(ROBOTS_PROBES)) { + const robots = tools.parseRobots(text); + for (const [path, answer] of asked) { + const got = robots.canFetch(path) ? 'allowed' : 'refused'; + if (got !== answer) wrong.push([text, path, answer, got]); + } + } + assert.deepEqual(wrong, [], "the longest pattern that matches decides, in the tools' group or in *"); +}); + +test('a robots rule of many stars is answered in bounded time', () => { + const began = performance.now(); + for (const stars of [4, 5, 12]) { + const robots = tools.parseRobots(`User-agent: *\nDisallow: /${'*a'.repeat(stars)}*b\n`); + assert.equal(robots.canFetch(`/${'a'.repeat(200)}`), true); + assert.equal(robots.canFetch(`/${'a'.repeat(5000)}`), true); + assert.equal(robots.canFetch(`/${'a'.repeat(5000)}b`), false); + } + const many = tools.parseRobots(`User-agent: *\n${'Disallow: /*a*a*a*a*b\n'.repeat(2000)}`); + assert.equal(many.canFetch(`/${'a'.repeat(200)}`), true); + assert.ok(performance.now() - began < 5000, "the time is bounded by the rule's length times the path's, however many stars"); +}); + +// A rule is matched part by part between its stars, so its time is its length plus the path's. +// Matched item by item, half a megabyte of such rules took seconds a question, on the event loop. +test('a robots txt of long rules is answered in a time bounded by its length', () => { + const rule = `Disallow: /*${'a'.repeat(1000)}b`; + const robots = tools.parseRobots(`User-agent: *\n${Array(490).fill(rule).join('\n')}\n`); + const tiny = tools.parseRobots(`User-agent: *\n${'Disallow: *z\n'.repeat(40000)}`); + const began = performance.now(); + assert.equal(robots.canFetch(`/${'a'.repeat(2000)}`), true); + assert.equal(robots.canFetch(`/${'a'.repeat(2000)}b`), false); + assert.equal(tiny.canFetch(`/${'a'.repeat(8000)}`), true); + assert.ok(performance.now() - began < 2000, "the time is bounded by the file's length and the path's"); +}); + +// An address has a longest length, counted in its one form: a page may write a link of any length, +// and every link is asked of a robots.txt and of a server. +test('an address longer than the bound is refused', () => { + const atTheBound = `https://docs.example.com/${'a'.repeat(tools.MAX_URL_LENGTH - 25)}`; + assert.equal(tools.readUrl(atTheBound).href.length, tools.MAX_URL_LENGTH); + for (const text of [`${atTheBound}a`, `${atTheBound}?q`, `${atTheBound}#f`]) { + assert.deepEqual(refusalSync(() => tools.readUrl(text)), { status: 400, message: 'url is longer than 8192 characters' }); + } + // a link that long names no address the tools take: it stays as it is written + const link = `/${'a'.repeat(tools.MAX_URL_LENGTH)}`; + assert.equal(tools.resolveUrl('https://docs.example.com/', link), link); +}); + // --- the fixture site ---------------------------------------------------------------------------- const SITE_PAGES = { @@ -1066,8 +1775,20 @@ const SITE_PAGES = { '/private/secret': ['Secret', '

Robots keep out.

'], '/detour': ['Detour', '

See the copy and C.

'], '/tangle': ['Tangle', '

one, two, ' - + 'three, C.

'] + + 'three, C.

'], + '/wild': ['Wild', '

one, two, ' + + 'three, four.

'], + '/wild/a.tmp': ['Tmp', '

A file to leave alone.

'], + '/wild/b': ['B', '

A page, printed or viewed.

'], + '/wild/c.tmp': ['C', '

A file with a query.

'] }; +// the fixture site's robots.txt: what a test puts here is served until the test puts it back +const SITE_ROBOTS = { text: 'User-agent: *\nDisallow: /private/\n' }; +// one page under many spellings, as the fixture site links it from /same on its own port +const SAME_PAGE = '

one ' + + 'two three ' + + 'four five six ' + + 'seven

'; const page = (title, body) => `${title}${body}`; let site; @@ -1080,8 +1801,11 @@ before(async () => { response.end(body); }; if (SITE_PAGES[url.pathname]) return send(200, 'text/html; charset=utf-8', page(...SITE_PAGES[url.pathname])); + // the path and the query exactly as the request named them + if (url.pathname.startsWith('/echo/')) return send(200, 'text/plain', request.url); switch (url.pathname) { - case '/robots.txt': return send(200, 'text/plain', 'User-agent: *\nDisallow: /private/\n'); + case '/robots.txt': return send(200, 'text/plain', SITE_ROBOTS.text); + case '/same': return send(200, 'text/html; charset=utf-8', page('Same', SAME_PAGE.replaceAll('PORT', String(server.address().port)))); case '/plain.txt': return send(200, 'text/plain; charset=utf-8', 'plain text body\n'); case '/data.json': return send(200, 'application/json', JSON.stringify({ a: 1 })); case '/image.png': return send(200, 'image/png', Buffer.concat([Buffer.from('\x89PNG\r\n\x1a\n', 'latin1'), Buffer.alloc(64)])); @@ -1295,6 +2019,44 @@ test('an address that cannot be read fails no fetch and no crawl', async () => { assert.equal(reply.visited, 2); }); +test('a crawl asks robots.txt about the path and the query', async () => { + const { web } = webTools(); + const served = SITE_ROBOTS.text; + SITE_ROBOTS.text = 'User-agent: *\nDisallow: /private/\nDisallow: /wild/*.tmp$\nDisallow: /*?print=\n\n' + + 'User-agent: mercury\nDisallow: /wild/\n'; + try { + const reply = await web.webCrawl({}, { url: `${site}/wild` }); + assert.deepEqual(reply.pages.map((p) => p.url), [`${site}/wild`, `${site}/wild/b?view=1`, `${site}/wild/c.tmp?x`], + "a star, a $ and a query are obeyed, and a group for another agent is not the tools'"); + assert.equal(reply.visited, 3); + } finally { + SITE_ROBOTS.text = served; + } +}); + +test('a crawl knows a site and a page by one form', async () => { + const sandbox = new tools.WebSandbox({ rules: tools.parseHostRules(['http://*']), allowPrivate: true, timeoutMs: 500, crawlDelayMs: 0, + lookup: async () => [{ address: '127.0.0.1', family: 4 }] }); + const web = tools.createWebTools(sandbox, { log: ledger() }); + const port = server.address().port; + const reply = await web.webCrawl({}, { url: `HTTP://Fixture.TEST:${port}/same` }); + assert.deepEqual(reply.pages.map((p) => p.url), [`http://fixture.test:${port}/same`, `http://fixture.test:${port}/docs/c`]); + assert.equal(reply.visited, 2, 'a page is fetched once, however its links spell it'); +}); + +test('a request names the path and the query as they were checked', async () => { + const { web } = webTools(); + for (const [written, asked] of [ + ['/echo/a%3Ab%2fc?q=%27x%27&r=%3d', '/echo/a%3Ab%2Fc?q=%27x%27&r=%3D'], + ['/echo/x/../y/%2e%2e/z a?b c#d', '/echo/z%20a?b%20c'], + ["/echo/(a);b=c,d~e!$'*+@:[]", "/echo/(a);b=c,d~e!$'*+@:[]"], + ['/echo/café/%7Euser?é', '/echo/caf%C3%A9/~user?%C3%A9'] + ]) { + const reply = await web.webFetch({}, { url: `${site}${written}` }); + assert.deepEqual([reply.url, reply.text], [`${site}${asked}`, asked], written); + } +}); + // --- the clock ----------------------------------------------------------------------------------- test('time.now in UTC and in a zone', async () => { @@ -1428,6 +2190,19 @@ test('planIngest refuses by rule', () => { } }); +test('a property named __proto__ is kept like any other', () => { + const args = JSON.parse('{"nodes": [{"key": "k", "label": "L", "properties": {"__proto__": 1, "ok": 2}},' + + ' {"key": "m", "label": "L", "properties": {"__proto__": ["a"], "constructor": "c"}}],' + + ' "relationships": [{"from": "k", "to": "m", "type": "T", "properties": {"__proto__": true}}]}'); + const plan = tools.planIngest(args, { maxNodes: 5 }); + assert.deepEqual(plan.nodes.get('L').map((row) => Object.entries(row.properties)), + [[['__proto__', 1], ['ok', 2]], [['__proto__', ['a']], ['constructor', 'c']]]); + assert.deepEqual(Object.entries(plan.relationships.get('T')[0].properties), [['__proto__', true]]); + const nested = JSON.parse('{"nodes": [{"key": "k", "label": "L", "properties": {"__proto__": {"a": 1}}}]}'); + assert.deepEqual(refusalSync(() => tools.planIngest(nested, { maxNodes: 5 })), + { status: 400, message: 'nodes[0].properties.__proto__ must be a scalar or a list of scalars' }); +}); + // --- the knowledge graph: the tools over a fake backend ---------------------------------------- const rows = (columns, values, { truncated = false, counters = undefined } = {}) => ({ columns, values, truncated, counters }); @@ -1765,8 +2540,13 @@ test('pages are numbers in the digits 0 to 9', () => { } assert.deepEqual(tools.pageRange(' 2 ', 12), [2]); assert.deepEqual(tools.pageRange('00002, 1-3', 12), [2, 1, 3]); - assert.deepEqual(tools.pageRange('9'.repeat(5000), 12), [], 'a page beyond the document selects nothing'); - assert.deepEqual(tools.pageRange(`2-${'9'.repeat(5000)}`, 3), [2, 3]); + assert.deepEqual(tools.pageRange('\u00a02\u3000,\u20283', 12), [2, 3], 'white space both packs take'); + assert.deepEqual(tools.pageRange('9007199254740991', 12), [], 'a page beyond the document selects nothing'); + assert.deepEqual(tools.pageRange('2-9007199254740991', 3), [2, 3]); + for (const spec of ['9007199254740992', '9007199254740993-9007199254740992', '2-9007199254740992', '9'.repeat(5000), `2-${'9'.repeat(5000)}`, + '\u00852', '\ufeff2', '2\u001f']) { + assert.deepEqual(refusalSync(() => tools.pageRange(spec, 12)), { status: 400, message: 'pages must be page numbers and ranges such as 1-3,7' }, spec.slice(0, 20)); + } }); // --- the boot: what registers, the health route, describe --------------------------------------- @@ -1814,6 +2594,33 @@ test('a bad sandbox stops the boot by name', async () => { includes(noDriverLog.text(), 'the Bolt driver is not installed - npm install --save-dev neo4j-driver'); }); +test('a setting that is no number and no switch stops the boot by name', async () => { + const root = { [tools.FILE_ROOT]: workspace() }; + const sites = { [tools.WEB_ALLOW]: 'docs.example.com' }; + const graph = { [tools.GRAPH_URI]: 'bolt://graph.example:7687' }; + for (const [settings, message] of [ + [{ [tools.TIME_ENABLED]: 'yes' }, 'tools.time must be true or false'], + [{ ...root, [tools.FILE_HIDDEN]: 1 }, 'tools.file.hidden must be true or false'], + [{ ...root, [tools.FILE_MAX_BYTES]: '1_0' }, 'tools.file.max.bytes must be an integer'], + [{ ...root, 'tools.file.search.timeout.ms': 99 }, 'tools.file.search.timeout.ms must be at least 100'], + [{ ...root, 'tools.file.search.timeout.ms': 2147483648 }, 'tools.file.search.timeout.ms must be at most 2147483647'], + [{ ...sites, [tools.WEB_ALLOW_PRIVATE]: 'on' }, 'tools.web.allow.private must be true or false'], + [{ ...sites, [tools.WEB_TIMEOUT_MS]: 2147483648 }, 'tools.web.timeout.ms must be at most 2147483647'], + [{ ...sites, [tools.WEB_CRAWL_DELAY_MS]: '4294967296' }, 'tools.web.crawl.delay.ms must be at most 2147483647'], + [{ ...graph, [tools.GRAPH_WRITE]: '1' }, 'tools.graph.write must be true or false'], + [{ ...graph, [tools.GRAPH_TIMEOUT_MS]: 2147483648 }, 'tools.graph.timeout.ms must be at most 2147483647'] + ]) { + const { instance, log } = app(settings); + await assert.rejects(instance.boot(), (e) => e instanceof tools.ToolsError && e.message === `Built-in tools cannot start - ${message}`, message); + assert.ok(log.lines.includes(`ERROR Built-in tools cannot start - ${message}`), message); + } + resetConfig(); + configure({ ...root, 'tools.file.search.timeout.ms': ' 250 ' }); + assert.equal((await tools.loadFileSandbox({ log: ledger() })).searchTimeoutMs, 250); + configure({ 'tools.file.search.timeout.ms': undefined }); + assert.equal((await tools.loadFileSandbox({ log: ledger() })).searchTimeoutMs, 10000); +}); + test('a full configuration registers every file, web and clock tool and serves them through the bus', async () => { const root = workspace(); const { instance, registry, log } = app({ ...SITE_SETTINGS, [tools.FILE_ROOT]: root, [tools.WEB_CRAWL_MAX_PAGES]: 80 }); From 0d264b001130b73cdffc32f623e999621219c4ee Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:18 -0800 Subject: [PATCH 3/6] fix(llm-helper): the settings are read when the helper starts, and a switch, a time in milliseconds and a page list by one rule A start-up step reads the settings a request falls back on and builds the transcript store when one is named, so a wrong one stops the application by name. A switch is true or false and any other value stops the start. A time in milliseconds is at most 2147483647, the audit's retention at most 1000000d, a port at most 65535. In a page list white space is ignored around a number and refused inside one. A path is blank by the same 24 characters in both packs. Co-Authored-By: Claude Fable 5.2 --- extensions/llm-helper/README.md | 80 ++- extensions/llm-helper/llm-helper.mjs | 231 +++++--- test/llm-attachments.test.mjs | 2 +- test/llm-helper.test.mjs | 143 ++++- test/vectors/llm-attachments-vectors.json | 81 +++ test/vectors/llm-helper-vectors.json | 658 +++++++++++++++++++++- 6 files changed, 1089 insertions(+), 106 deletions(-) diff --git a/extensions/llm-helper/README.md b/extensions/llm-helper/README.md index c29a0018..b88963c9 100644 --- a/extensions/llm-helper/README.md +++ b/extensions/llm-helper/README.md @@ -102,7 +102,7 @@ token batches as they are produced. | `attachments` | `llm.chat` only, and never a loop turn. Files for the model to look at, named by reference: a non-empty list whose entries are a path inside `llm.attachments.root`, or `{path, pages}` for pages of a PDF, such as `13` or `1-3,7`. See Attachments. | | `params.model` | The model. Default `claude-opus-5-5` (`llm.model`). On Bedrock's default surface a bare id is sent with the `anthropic.` prefix and an id already spelled for Bedrock as written; on the classic runtime surface every id is sent as written, an inference profile id as the account lists it. | | `params.max_tokens` | Output cap. Default 16000 (`llm.max.tokens`). | -| `params.timeout_ms` | `llm.chat`: a deadline for the whole call, SDK retries included. `llm.stream`: the idle allowance between events. Default 60000 (`llm.timeout.ms`). | +| `params.timeout_ms` | `llm.chat`: a deadline for the whole call, SDK retries included. `llm.stream`: the idle allowance between events. Default 60000 (`llm.timeout.ms`), at most 2147483647. | | `params.effort` | `low`, `medium`, `high`, `xhigh` or `max`. Sent only when set; otherwise the model's own default applies. A model that takes no effort parameter answers 400. | | `params.stop_sequences` | A list of strings. | | `params.provider` | Accepted for compatibility: only `anthropic`. | @@ -115,9 +115,19 @@ sampling parameters (`temperature`, `top_p`, `top_k`), so none is forwarded. value (`16000`, or `16000.0`, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9 (`"16000"`), up to 9007199254740991, the largest whole number both runtimes hold exactly; a whole-number key of the configuration is read as such a string. A duration is such a number of -seconds, or ASCII digits and one unit (`30m`, `12h`, `2d`). White space around it is ignored. -Anything else - a fraction, a sign, an underscore, the digits of another script - is a 400 that -names the field or the key. +seconds, or ASCII digits and one unit (`30m`, `12h`, `2d`). White space - the 24 characters both +runtimes' own trim takes: tab to carriage return, the space, the no-break space and the other +space separators, the line and the paragraph separator - is ignored around a number and never +inside one: in `pages` around each page number, so `1 - 3 , 7` is `1-3,7`, and `1 3` is not page +13 but a 400. Anything else - a fraction, a sign, an underscore, the digits of another script - +is refused by the name of the field or the key: a field of a request with a 400, a key of the +configuration when the helper starts (see Configuration). + +**A time in milliseconds has a maximum.** `params.timeout_ms`, `llm.timeout.ms`, +`llm.transcript.audit.sweep.ms` and the two stores' `timeout.ms` take at most 2147483647, about +24.8 days: the longest wait the timers of both runtimes hold (Node.js fires a longer one at +once) and the longest `statement_timeout` PostgreSQL takes. A longer one is refused like a value +that is no number. **`llm.chat` reply** (a map): `text`, or `data` for a `schema` request; `model` (the model that answered); `stop_reason`; `usage {input_tokens, output_tokens}`; `request_id` when the API sent one; @@ -226,7 +236,7 @@ still answers: guard the node with a decision on the reference when the page is | Case | Status | |---|---| | `attachments` on `llm.stream`, or on a loop turn; a last turn that is not the user's | 400 | -| Not a non-empty list; an entry that is neither a path nor `{path, pages}`; `pages` that are malformed, run backward or name a page twice | 400 | +| Not a non-empty list; an entry that is neither a path nor `{path, pages}`; a path that is empty or only white space, by the white space of the number rule; `pages` that are malformed, run backward or name a page twice | 400 | | More files than `llm.attachments.max.count`, or more bytes of files than `llm.attachments.max.bytes` (taken from each file's size before it is read) | 400 | | An absolute path, a path or a link that leads out of the folder, a hidden entry, a missing file, a folder | 400 | | A file that is not PNG, JPEG, GIF, WebP or PDF; `pages` on an image; a page the document does not have; an encrypted or unreadable PDF | 400 | @@ -234,6 +244,7 @@ still answers: guard the node with a decision on the reference when the page is | No `llm.attachments.root` configured | 503 | | `pages` without the `@cantoo/pdf-lib` package | 503, naming the package | | A configured `llm.attachments.root` that is not a folder | the application stops at start (a request that meets it later is a 500) | +| `llm.attachments.max.count` or `llm.attachments.max.bytes` that is not a whole number of 1 or more | the application stops at start (a request that meets it later is a 400) | **Limits that are the provider's.** The helper sends no more than 20 files by default because a request with more than 20 image and document blocks is held to a tighter limit on each image's dimensions. A request takes at most 600 @@ -355,7 +366,9 @@ output_tokens, cache_creation_input_tokens, cache_read_input_tokens}` and `reque ### The transcript store `llm.transcript.store` names it, and a loop turn without one is a `503 transcript store not configured`. A request -without `tools` never touches it, unless single calls are audited (see The audit of a single call). +without `tools` never touches it, unless single calls are audited (see The audit of a single call). A name that is +neither of the two below stops the application at start, by name, and so does `redis` whose client is not installed +or whose connection keys are wrong. | `llm.transcript.store` | For | |---|---| @@ -365,9 +378,9 @@ without `tools` never touches it, unless single calls are audited (see The audit Redis keeps one hash per conversation under `transcript:{conversation}`, holding the turn count and the record. A Lua script makes the compare-and-set atomic on that one key. A deployment may share one Redis with the graph's suspend store (`minigraph-state-redis`, keys `graph:{graph_id}:{cid}`): give this app a Redis ACL user confined to -`~transcript:*`, so the two share a server but neither a namespace nor a credential. The client connects on the -first turn, to a standalone server (a cluster's configuration endpoint needs the cluster client, not built yet); a -store that cannot be reached is a `503 transcript store unreachable - …`. +`~transcript:*`, so the two share a server but neither a namespace nor a credential. The client is built at start +and connects on the first turn, to a standalone server (a cluster's configuration endpoint needs the cluster +client, not built yet); a store that cannot be reached is a `503 transcript store unreachable - …`. Every write sets the record's time to live to `ttl`, so a run that waits for a person keeps its transcript: make `ttl` at least as long as the longest approval wait. When the model ends the run (done, a refusal, the context @@ -436,10 +449,10 @@ for the save; a working store that fails is logged by type, and that call is not prompt and reply, kept for `llm.transcript.audit.retention`. **Retention and purge are the installation's.** `expires_at` is written as the first turn's start plus -`llm.transcript.audit.retention` (default `365d`); the helper runs no purge. `schema/purge.sql` holds the two -statements a purge is, `dev/audit-purge.sh` runs them against the development container by hand (`--dry-run` counts, -`--before ` also removes the conversations started before it), and operations automate the same statements on -the enterprise's own schedule and policy. +`llm.transcript.audit.retention` (default `365d`, at most `1000000d`); the helper runs no purge. `schema/purge.sql` +holds the two statements a purge is, `dev/audit-purge.sh` runs them against the development container by hand +(`--dry-run` counts, `--before ` also removes the conversations started before it), and operations automate +the same statements on the enterprise's own schedule and policy. **Development.** `dev/postgres-up.sh` runs PostgreSQL 17 with the schema applied at first start and pgweb as the SQL browser at `http://127.0.0.1:8081`, on Colima or Docker, `POSTGRES_PASSWORD` from the environment; @@ -462,6 +475,21 @@ of the box). The audit does not redact; a redaction policy is the installation's `resources/application.yml`, or `-Dkey=value` at run time. A call's `params` win over these keys. +**A setting that is wrong stops the application when it starts.** Every key below that can be wrong is read at +start, before a request finds it: a number or a duration that is not one or is out of its range, a name that is not +one of those listed, a switch that is neither `true` nor `false`, a transcript or an audit store whose client is not +installed. One ERROR line says what is wrong - `llm.helper cannot start - llm.max.tokens must be a whole +number >= 1`, or `attachments cannot start - ...` and `transcript audit store cannot start - ...` for those two +features - and the application stops. The keys of a feature that is not configured are not read: the +`llm.transcript.redis.*` keys without `llm.transcript.store: redis`, the `llm.transcript.audit.*` keys without +`llm.transcript.audit`, `llm.aws.api` without `llm.backend: bedrock`. A call's own `params` are not settings and keep +their 400 on the call; a credential, a region and a store that does not answer are found when a call is made. + +**A switch is `true` or `false`.** `llm.log.batches`, `llm.transcript.audit.single`, `llm.transcript.redis.ssl` and +`llm.transcript.audit.postgres.ssl` take the boolean, or the text `true` or `false` in any letter case; a key that +is unset or empty is its default. Any other value the helper is given - `-Dllm.log.batches=1`, a quoted `'maybe'` - +stops the application at start, by name: it is never read as off. + | Key | Default | Meaning | |---|---|---| | `llm.backend` | `anthropic` | The route to the models: `anthropic` (the Claude API) or `bedrock` (AWS Bedrock); see Backends. | @@ -469,25 +497,25 @@ of the box). The audit does not redact; a redaction policy is the installation's | `llm.aws.api` | `mantle` | The Bedrock surface: `mantle`, the Anthropic-shaped endpoint, or `runtime`, the classic one; see Backends. | | `llm.model` | `claude-opus-5-5` | The default model. | | `llm.max.tokens` | `16000` | The default output cap. | -| `llm.timeout.ms` | `60000` | The default deadline (chat) or idle allowance (stream). | +| `llm.timeout.ms` | `60000` | The default deadline (chat) or idle allowance (stream). At most 2147483647. | | `llm.max.retries` | `2` | SDK retries for connection errors, 408, 409, 429 and 5xx. | | `llm.fallbacks` | `default` | `default` or `off`. Server-side refusal fallbacks (`fallbacks: "default"`) on the models that support them (the Opus 5, Fable 5 and Sonnet 5.5 families). The reply's `model` names the model that answered. The Claude API only: Bedrock offers none, so the switch has no effect there. | | `llm.effort` | unset | The default effort. | | `llm.log.batches` | `false` | Log each streamed batch's number, size and arrival time (never its text). | -| `llm.provider` | `anthropic` | Only `anthropic`; any other value is a 400. | +| `llm.provider` | `anthropic` | Only `anthropic`; any other value stops the application at start, and a call's `params.provider` that names another is a 400. | | `llm.attachments.root` | unset | The one folder whose files a request may name in `attachments` (see Attachments). Unset, every attachment is a 503. | -| `llm.attachments.max.count` | `20` | Files per call. | -| `llm.attachments.max.bytes` | `20971520` | Bytes of files per call (20 MB), counted from the files' sizes before they are read. | +| `llm.attachments.max.count` | `20` | Files per call, 1 or more. | +| `llm.attachments.max.bytes` | `20971520` | Bytes of files per call (20 MB), counted from the files' sizes before they are read; 1 or more. | | `llm.transcript.store` | unset | `memory` or `redis`; a loop turn needs one (see The transcript store). | | `llm.transcript.ttl` | `7d` | A loop turn's `ttl` when the request carries none. | | `llm.transcript.retention` | `0` | A loop turn's `retention` when the request carries none. | -| `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). A command waits at most `timeout.ms`, and none is queued while the client is offline. | +| `llm.transcript.redis.host`, `.port`, `.username`, `.password`, `.ssl`, `.database`, `.timeout.ms` | `127.0.0.1`, `6379`, none, none, `false`, `0`, `5000` | The Redis connection: the engines' `redis.*` set under this store's own prefix. The password comes from the environment (`${REDIS_PASSWORD}`). `port` is at most 65535 and `timeout.ms` at most 2147483647. A command waits at most `timeout.ms`, and none is queued while the client is offline. | | `llm.transcript.audit` | unset | `postgres`: record every model turn in the audit store (see The audit store). Unset, no audit. | -| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. A value that is not a duration stops the application at start, by name. | +| `llm.transcript.audit.retention` | `365d` | Written as a conversation's `expires_at`; the purge is the installation's. At most `1000000d`: with it the date keeps a four-digit year, which both packs and the database write the same way. A value that is not a duration, or a longer one, stops the application at start, by name. | | `llm.transcript.audit.grace` | `1d` | How long a closed working record waits for its integrity check before it expires unreleased. A value that is not a duration of a second or more stops the application at start, by name. | -| `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. | +| `llm.transcript.audit.sweep.ms` | `60000` | The sweep that repairs lost events and stopped runs; `0` disables it. At most 2147483647. | | `llm.transcript.audit.single` | `false` | `true`: record a call without `tools` as a conversation of one turn (see The audit of a single call). Needs `llm.transcript.store`. | -| `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` encrypts without verifying the server's certificate (libpq's `sslmode=require`), `false` is `sslmode=disable`. `timeout.ms` bounds a connection attempt, a query on the client and, on the server, a statement (`statement_timeout`). | +| `llm.transcript.audit.postgres.host`, `.port`, `.database`, `.username`, `.password`, `.ssl`, `.timeout.ms` | `127.0.0.1`, `5432`, `mercury`, none, none, `true`, `5000` | The PostgreSQL connection, the engines' convention under this store's prefix. The shipped `application.yml` sets the user and the password from the environment (`${POSTGRES_USER:mercury}`, `${POSTGRES_PASSWORD}`); `ssl` `true` encrypts without verifying the server's certificate (libpq's `sslmode=require`), `false` is `sslmode=disable`. `timeout.ms` bounds a connection attempt, a query on the client and, on the server, a statement (`statement_timeout`). `port` is at most 65535 and `timeout.ms` at most 2147483647. | The credential is never configured here. `ANTHROPIC_API_KEY` (or whatever the SDK resolves: an auth token, or a profile) comes from the environment for the Claude API; the AWS credential chain, @@ -567,9 +595,11 @@ by reference; it still decides nothing about control flow. ## Tests `test/llm-helper.test.mjs` runs the shared `test/vectors/llm-helper-vectors.json` against a fake of -the SDK (68 cases: request validation, the exact SDK call, replies, the error contract, streaming, -the shape of a Bedrock call on either surface; and 98 values under `numbers`, each read as a whole -number, as a duration and as the pages of a PDF, with the one answer both packs give) and the shared +the SDK (70 cases: request validation, the exact SDK call, replies, the error contract, streaming, +the shape of a Bedrock call on either surface; 101 values under `numbers`, each read as a whole +number, as a duration and as the pages of a PDF; 22 values under `switches`, each read as a switch +of the configuration; and 47 cases under `start`, each a configuration that a start-up step +passes or stops by name - all with the one answer both packs give) and the shared `test/vectors/llm-loop-vectors.json` (66 cases of one or more turns: the loop fields, the exact SDK call of each turn with the transcript sent back, the reply, and the stored record after each step), the loop cases once on the memory store and again on a Redis fake that @@ -589,7 +619,7 @@ mailbox; the tests beside it pin that the reply does not wait for the save, that sweep, and that a loop turn is untouched by the switch. `test/llm-attachments.test.mjs` pins the attachments with a third shared file, -`test/vectors/llm-attachments-vectors.json` (48 cases: the shape of the field, where it does not belong, the folder a +`test/vectors/llm-attachments-vectors.json` (52 cases: the shape of the field, where it does not belong, the folder a request stays inside, the files refused before any model call, the blocks the model gets, the reference the audit keeps), over the fixture files of `test/fixtures/attachments`, which both packs hold byte for byte. A cut PDF is checked page by page and never byte for byte, since two PDF libraries do not write the same bytes. The tests beside it diff --git a/extensions/llm-helper/llm-helper.mjs b/extensions/llm-helper/llm-helper.mjs index 2f4a264a..ed38b7b0 100644 --- a/extensions/llm-helper/llm-helper.mjs +++ b/extensions/llm-helper/llm-helper.mjs @@ -87,15 +87,20 @@ const CREDENTIAL_ERROR = 'Could not resolve authentication method'; const AWS_CREDENTIAL_ERROR = 'CredentialsProviderError'; // --- how a number is read: the same in both packs ------------------------------------------- -// the white space ignored around a number, and anywhere in pages: the characters JavaScript's -// trim() and Python's str.strip() both take for white space, so neither pack accepts a character -// the other refuses +// the white space ignored around a number - in pages around each number, never inside one - and +// the white space a path is not made of: the characters JavaScript's trim() and Python's +// str.strip() both take for white space, so neither pack accepts a character the other refuses const SPACE = String.raw`[\t-\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]`; const SPACES = new RegExp(`${SPACE}+`, 'g'); // the digits 0 to 9 and no other: \d here, where the Python twin asks for them by flag. A number is at // most Number.MAX_SAFE_INTEGER (2**53 - 1), the largest whole number both packs hold exactly: above // it this pack's numbers round, and the twins would read two different numbers from one request const WHOLE = new RegExp(String.raw`^${SPACE}*(\d+)${SPACE}*$`); +// the longest wait both packs' timers hold, in milliseconds (2**31 - 1, about 24.8 days): this +// pack's timers keep a delay in 32 bits with a sign and fire at once on a longer one +export const MAX_TIMER_MS = 2147483647; +// the highest port a connection can name +export const MAX_PORT = 65535; // --- the loop contract's defaults and limits (RFC-0011) ----------------------------------- // a request that carries tools is one turn of an agent loop; the other loop fields need tools @@ -133,7 +138,6 @@ export const ATTACHMENTS_MAX_COUNT = 'llm.attachments.max.count'; export const DEFAULT_ATTACHMENTS_MAX_COUNT = 20; export const DEFAULT_ATTACHMENTS_MAX_BYTES = 20 * 1024 * 1024; const ATTACHMENT_KEYS = ['path', 'pages']; -const PAGES = /^\d+(-\d+)?(,\d+(-\d+)?)*$/; // an image's limit as the provider counts it, base64-encoded: by the route to the models export const IMAGE_MAX_ENCODED = 10 * 1024 * 1024; export const BEDROCK_IMAGE_MAX_ENCODED = 5 * 1024 * 1024; @@ -153,6 +157,9 @@ export const AUDIT_ROUTE = 'transcript.audit'; export const AUDIT_POSTGRES = 'postgres'; export const AUDITS = [AUDIT_POSTGRES]; export const DEFAULT_AUDIT_RETENTION = '365d'; +// the longest audit retention, a million days in seconds: with it a conversation's expires_at is a +// date of a four-digit year, which both packs and the database write the same way +export const MAX_AUDIT_RETENTION_S = 1_000_000 * 86400; export const DEFAULT_AUDIT_GRACE = '1d'; export const DEFAULT_AUDIT_SWEEP_MS = 60000; // the sweep's lock on Redis, under the store's prefix so one ACL covers it; never a conversation key @@ -198,16 +205,41 @@ function whole(digits) { return Number.isSafeInteger(number) ? number : undefined; } -/** A whole number from a JSON number or a config string, or a 400 naming the field. */ -function wholeNumber(name, value, minimum) { - const match = WHOLE.exec(numberText(value) ?? ''); - const number = match ? whole(match[1]) : undefined; - if (number === undefined || number < minimum) { +/** The whole number a text spells - ASCII digits, the white space around them ignored and none + * allowed between them - or undefined. */ +function spelled(text) { + const match = WHOLE.exec(text ?? ''); + return match ? whole(match[1]) : undefined; +} + +/** A whole number from a JSON number or a config string, or a 400 naming the field. A number + * that sets a timer or names a port has a maximum of its own, refused the same way. */ +function wholeNumber(name, value, minimum, maximum = Number.MAX_SAFE_INTEGER) { + const number = spelled(numberText(value)); + if (number === undefined || number < minimum || number > maximum) { throw new AppException(400, `${name} must be a whole number >= ${minimum}`); } return number; } +/** A switch of the configuration: true or false, the boolean or the text in any letter case; no + * value and an empty one are the default. Any other value would be read as off without a word - + * TLS written "yes" would be no TLS - so it is refused by name. */ +function switchOf(prop, key, fallback) { + const value = prop(key); + if (value === undefined || value === null || value === '') { + return fallback; + } + if (typeof value === 'boolean') { + return value; + } + const lowered = typeof value === 'string' ? value.toLowerCase() : ''; + if (lowered !== 'true' && lowered !== 'false') { + throw new AppException(500, `${key} must be true or false`); + } + return lowered === 'true'; +} + // --- provider failures as the portable error contract ---------------------------------- /** status, error type, message and request id - the same text on every runtime. */ @@ -357,17 +389,23 @@ async function bedrockClient(prop, api) { } } +/** The route to the models the configuration names, or a 501 that names the ones served. */ +function backendName(prop) { + const name = String(prop('llm.backend', DEFAULT_BACKEND) || DEFAULT_BACKEND).toLowerCase(); + if (!BACKENDS.includes(name)) { + throw new AppException(501, + `unknown LLM backend '${name}' - this helper serves: ${BACKENDS.join(', ')}`); + } + return name; +} + /** The backend, built on first use. Credentials resolve per call, so the app starts (and * reports its health) without one. */ export function defaultBackend(prop) { let built; return async () => { if (built === undefined) { - const name = String(prop('llm.backend', DEFAULT_BACKEND) || DEFAULT_BACKEND).toLowerCase(); - if (!BACKENDS.includes(name)) { - throw new AppException(501, - `unknown LLM backend '${name}' - this helper serves: ${BACKENDS.join(', ')}`); - } + const name = backendName(prop); const api = name === BEDROCK_BACKEND ? awsApi(prop) : AWS_API_MANTLE; const client = name === BEDROCK_BACKEND ? await bedrockClient(prop, api) : new Anthropic(); built = backendFor(name, client, api); @@ -649,12 +687,12 @@ export async function redisStore(prop, { importer = (name) => import(name), log throw error; } const timeoutMs = wholeNumber('llm.transcript.redis.timeout.ms', - prop('llm.transcript.redis.timeout.ms', '5000'), 1); + prop('llm.transcript.redis.timeout.ms', '5000'), 1, MAX_TIMER_MS); const client = redis.createClient({ socket: { host: String(prop('llm.transcript.redis.host', '127.0.0.1')), - port: wholeNumber('llm.transcript.redis.port', prop('llm.transcript.redis.port', '6379'), 1), - tls: String(prop('llm.transcript.redis.ssl', 'false')).toLowerCase() === 'true', + port: wholeNumber('llm.transcript.redis.port', prop('llm.transcript.redis.port', '6379'), 1, MAX_PORT), + tls: switchOf(prop, 'llm.transcript.redis.ssl', false), connectTimeout: timeoutMs, // a dropped connection is retried three times; then the next turn connects afresh reconnectStrategy: (retries, cause) => (retries >= 3 ? cause : 100 * (retries + 1)) @@ -864,11 +902,11 @@ export async function postgresAuditStore(prop, { importer = (name) => import(nam } const Pool = pg.Pool ?? pg.default?.Pool; const prefix = 'llm.transcript.audit.postgres.'; - const timeoutMs = wholeNumber(`${prefix}timeout.ms`, prop(`${prefix}timeout.ms`, '5000'), 1); - const ssl = String(prop(`${prefix}ssl`, 'true')).toLowerCase() === 'true'; + const timeoutMs = wholeNumber(`${prefix}timeout.ms`, prop(`${prefix}timeout.ms`, '5000'), 1, MAX_TIMER_MS); + const ssl = switchOf(prop, `${prefix}ssl`, true); const pool = new Pool({ host: String(prop(`${prefix}host`, '127.0.0.1')), - port: wholeNumber(`${prefix}port`, prop(`${prefix}port`, '5432'), 1), + port: wholeNumber(`${prefix}port`, prop(`${prefix}port`, '5432'), 1, MAX_PORT), database: String(prop(`${prefix}database`, 'mercury')), user: prop(`${prefix}username`) || undefined, password: prop(`${prefix}password`) || undefined, @@ -1036,6 +1074,18 @@ function systemOf(body) { return body.system || undefined; } +/** An effort the models take, in lower case, or a 400 naming the field or the setting. */ +function effortLevel(name, effort) { + if (effort === undefined || effort === null) { + return undefined; + } + const level = String(effort).toLowerCase(); + if (!EFFORTS.includes(level)) { + throw new AppException(400, `${name} must be one of: ${EFFORTS.join(', ')}`); + } + return level; +} + function stopSequencesOf(params) { const stops = params.stop_sequences; if (stops === undefined || stops === null) { @@ -1062,20 +1112,21 @@ function schemaOf(body, streaming) { } /** The pages of a PDF to send, as ranges in the order named, with the text as written. A - * mapping may carry a page number as a number. Whether a page exists is the document's to say, - * when it is read. */ + * mapping may carry a page number as a number. White space is ignored around a number - so around + * a comma and a hyphen - and never inside one: "1 3" names no page. Whether a page exists is the + * document's to say, when it is read. */ function pagesOf(index, raw) { - const text = numberText(raw)?.replace(SPACES, ''); + const text = numberText(raw); const malformed = () => new AppException(400, `attachments[${index}].pages must name pages from 1, such as 13 or 1-3,7`); - if (text === undefined || !PAGES.test(text)) { + if (text === undefined) { throw malformed(); } const ranges = []; for (const part of text.split(',')) { - const [first, last] = part.split('-'); - const low = whole(first); - const high = whole(last ?? first); + const hyphen = part.indexOf('-'); + const low = spelled(hyphen < 0 ? part : part.slice(0, hyphen)); + const high = hyphen < 0 ? low : spelled(part.slice(hyphen + 1)); if (low === undefined || high === undefined || low < 1 || high < low) { throw malformed(); } @@ -1084,7 +1135,7 @@ function pagesOf(index, raw) { } ranges.push([low, high]); } - return { pages: ranges, pagesText: text }; + return { pages: ranges, pagesText: text.replace(SPACES, '') }; } /** One attachment: a path, or a map with a path and the pages of a PDF. */ @@ -1102,7 +1153,8 @@ function attachmentOf(index, entry) { } else if (typeof entry !== 'string') { throw new AppException(400, `attachments[${index}] must be a path or {path, pages}`); } - if (typeof named !== 'string' || !named.trim()) { + // blank by the white space of the number rule, so both packs call the same paths blank + if (typeof named !== 'string' || !named.replace(SPACES, '')) { throw new AppException(400, `attachments[${index}].path must be a path inside ${ATTACHMENTS_ROOT}`); } return pages === undefined || pages === null ? { path: named } : { path: named, ...pagesOf(index, pages) }; @@ -1145,12 +1197,13 @@ function resultsOf(raw) { return raw; } -/** Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it. */ -function durationOf(name, value, minimum) { +/** Seconds from a whole number or a duration such as 30m, 12h or 2d, or a 400 naming it. A + * duration that becomes a date has a maximum of its own, refused the same way. */ +function durationOf(name, value, minimum, maximum = Number.MAX_SAFE_INTEGER) { const match = DURATION.exec(numberText(value) ?? ''); const count = match ? whole(match[1]) : undefined; const seconds = count === undefined ? -1 : count * DURATION_SECONDS[match[2]]; - if (!Number.isSafeInteger(seconds) || seconds < minimum) { + if (!Number.isSafeInteger(seconds) || seconds < minimum || seconds > maximum) { throw new AppException(400, `${name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) ` + `>= ${minimum}`); } @@ -1446,17 +1499,12 @@ export function createLlmHelper({ } } - function effortOf(params) { - const effort = params.effort || prop('llm.effort'); - if (effort === undefined || effort === null) { - return undefined; - } - const level = String(effort).toLowerCase(); - if (!EFFORTS.includes(level)) { - throw new AppException(400, `params.effort must be one of: ${EFFORTS.join(', ')}`); - } - return level; - } + const effortOf = (params) => effortLevel('params.effort', params.effort || prop('llm.effort')); + + const attachmentsMaxCount = () => wholeNumber(ATTACHMENTS_MAX_COUNT, + prop(ATTACHMENTS_MAX_COUNT, String(DEFAULT_ATTACHMENTS_MAX_COUNT)), 1); + const attachmentsMaxBytes = () => wholeNumber(ATTACHMENTS_MAX_BYTES, + prop(ATTACHMENTS_MAX_BYTES, String(DEFAULT_ATTACHMENTS_MAX_BYTES)), 1); /** The files a single call names (RFC-0016): the shape only. The files themselves are read by * attach(), after every other check of the request has passed. */ @@ -1468,8 +1516,7 @@ export function createLlmHelper({ if (!Array.isArray(raw) || !raw.length) { throw new AppException(400, ATTACHMENTS_SHAPE); } - const limit = wholeNumber(ATTACHMENTS_MAX_COUNT, - prop(ATTACHMENTS_MAX_COUNT, String(DEFAULT_ATTACHMENTS_MAX_COUNT)), 1); + const limit = attachmentsMaxCount(); if (raw.length > limit) { throw new AppException(400, `attachments: ${raw.length} files exceed ${ATTACHMENTS_MAX_COUNT} (${limit})`); } @@ -1503,7 +1550,7 @@ export function createLlmHelper({ const maxTokens = wholeNumber('params.max_tokens', setting(params, 'max_tokens', 'llm.max.tokens', String(DEFAULT_MAX_TOKENS)), 1); const timeoutMs = wholeNumber('params.timeout_ms', - setting(params, 'timeout_ms', 'llm.timeout.ms', String(DEFAULT_TIMEOUT_MS)), 1); + setting(params, 'timeout_ms', 'llm.timeout.ms', String(DEFAULT_TIMEOUT_MS)), 1, MAX_TIMER_MS); const maxRetries = wholeNumber('llm.max.retries', prop('llm.max.retries', String(DEFAULT_MAX_RETRIES)), 0); return { @@ -1662,9 +1709,9 @@ export function createLlmHelper({ const auditGraceS = () => durationOf('llm.transcript.audit.grace', prop('llm.transcript.audit.grace', DEFAULT_AUDIT_GRACE), 1); const auditRetentionS = () => durationOf('llm.transcript.audit.retention', - prop('llm.transcript.audit.retention', DEFAULT_AUDIT_RETENTION), 0); + prop('llm.transcript.audit.retention', DEFAULT_AUDIT_RETENTION), 0, MAX_AUDIT_RETENTION_S); const auditSweepMs = () => wholeNumber('llm.transcript.audit.sweep.ms', - prop('llm.transcript.audit.sweep.ms', String(DEFAULT_AUDIT_SWEEP_MS)), 0); + prop('llm.transcript.audit.sweep.ms', String(DEFAULT_AUDIT_SWEEP_MS)), 0, MAX_TIMER_MS); /** How long the saved record lives. A run the model ended takes the retention; a run the loop * stops (a cut-off turn, or the loop's own limits) keeps its time to live and expires with it. @@ -1713,8 +1760,7 @@ export function createLlmHelper({ // check writes the two rows from the record and releases it, and the sweep re-sends a check that // failed. No content crosses the bus, and the reply never waits for the save. - const auditSingleConfigured = () => auditConfigured() - && String(prop(AUDIT_SINGLE, 'false')).toLowerCase() === 'true'; + const auditSingleConfigured = () => auditConfigured() && switchOf(prop, AUDIT_SINGLE, false); // the saves in flight, so the shutdown can wait for them const singleSaves = new Set(); @@ -1886,8 +1932,7 @@ export function createLlmHelper({ let loaded; try { const root = await rootOf(); - const maxBytes = wholeNumber(ATTACHMENTS_MAX_BYTES, - prop(ATTACHMENTS_MAX_BYTES, String(DEFAULT_ATTACHMENTS_MAX_BYTES)), 1); + const maxBytes = attachmentsMaxBytes(); loaded = await loadAttachments({ specs: request.attachments, root, maxBytes, imageMaxEncoded: provider.imageMaxEncoded, library: pdfLibrary }); @@ -1904,19 +1949,23 @@ export function createLlmHelper({ }; } - /** A root that is configured and is not a folder is a deployment error: stop by name at start, - * before a request finds it. */ + /** A limit that is not a whole number, and a root that is configured and is not a folder, is a + * deployment error: stop by name at start, before a request finds it. */ async function attachmentsBoot() { - if (!prop(ATTACHMENTS_ROOT)) { - return; - } + const configured = Boolean(prop(ATTACHMENTS_ROOT)); try { - await rootOf(); + attachmentsMaxCount(); + attachmentsMaxBytes(); + if (configured) { + await rootOf(); + } } catch (error) { log.error(`attachments cannot start - ${error.message}`); throw refusal(error); } - log.info(`attachments ready - ${ATTACHMENTS_ROOT} is set`); + if (configured) { + log.info(`attachments ready - ${ATTACHMENTS_ROOT} is set`); + } } /** @@ -1997,6 +2046,8 @@ export function createLlmHelper({ return loopTurn(headers, body); } const request = prepare(body, { streaming: false }); + // the switch, read before the model is called: a wrong one costs no token + const single = auditSingleConfigured(); const started = performance.now(); const startedAt = isoUtc(); let done; @@ -2019,7 +2070,7 @@ export function createLlmHelper({ log.warn(`llm.chat failed - status=${mapped.status}`); throw mapped; } - if (auditSingleConfigured()) { + if (single) { // before the reply is judged: a refusal, a cut-off reply and a reply that is a 422 below // were answered by the model and cost tokens, so they are recorded too. With attachments // the record keeps a reference to each file, never its bytes @@ -2068,9 +2119,14 @@ export function createLlmHelper({ const started = performance.now(); let request; let provider; + let single; + let batchLog; try { request = prepare(event.body, { streaming: true }); provider = await backend(); + // the switches, read before the model is called: a wrong one costs no token + single = auditSingleConfigured(); + batchLog = switchOf(prop, 'llm.log.batches', false); } catch (error) { if (error instanceof AppException) { out.fail(error); @@ -2084,7 +2140,6 @@ export function createLlmHelper({ my_correlation_id: headers.my_correlation_id ?? null }; let frames = 0; - const batchLog = String(prop('llm.log.batches', 'false')).toLowerCase() === 'true'; const forward = (text) => { if (frames === 0) { // the head rides the first token; a stream that never gets one fails cleanly @@ -2101,7 +2156,7 @@ export function createLlmHelper({ const startedAt = isoUtc(); try { done = await complete(request, provider, forward); - if (auditSingleConfigured()) { + if (single) { // a stream the model completed is a single call like any other (RFC-0015) auditSingle(headers, request, done, [startedAt, isoUtc()]); } @@ -2257,24 +2312,29 @@ export function createLlmHelper({ let auditStoreOpened; // the store the boot built, closed at shutdown /** Start the audit when llm.transcript.audit is configured: register transcript.audit with one - * instance, open the store and start the sweep. A driver that is not installed, and a grace or a - * retention that is not a duration, stops the application by name (a deployment error); a - * database that does not answer is logged, and the sweep repairs what the outage defers. */ + * instance, open the store and start the sweep. A driver that is not installed, and a setting of + * the audit that is wrong - its grace, its retention, its sweep, a switch, a connection key - + * stops the application by name (a deployment error); a database that does not answer is logged, + * and the sweep repairs what the outage defers. */ async function auditBoot() { if (!auditConfigured()) { return; } + let sweepMs; + let single; try { // read here, not first on a turn's save or in the audit function, where a malformed one // would surface after the model was called auditGraceS(); auditRetentionS(); + sweepMs = auditSweepMs(); + single = auditSingleConfigured(); auditStoreOpened = await audit(); } catch (error) { log.error(`transcript audit store cannot start - ${error.message}`); throw error; } - if (auditSingleConfigured() && !prop('llm.transcript.store')) { + if (single && !prop('llm.transcript.store')) { // a single call's record waits in the working store for its check: a deployment error log.error(`transcript audit store cannot start - ${MISSING_SINGLE_STORE}`); throw new AppException(503, MISSING_SINGLE_STORE); @@ -2290,7 +2350,6 @@ export function createLlmHelper({ log.warn(`transcript audit store ${auditStoreOpened.name} not answering at start - ${auditFailure(error)}; ` + 'the sweep repairs what the outage defers'); } - const sweepMs = auditSweepMs(); if (sweepMs > 0 && sweepTimer === undefined) { sweepTimer = setInterval(() => { auditSweep().catch((error) => log.warn(`${AUDIT_ROUTE} sweep failed - ${auditFailure(error)}`)); @@ -2312,9 +2371,43 @@ export function createLlmHelper({ } } + // -- the start: a setting that is wrong stops the application before a request finds it ------ + + /** The settings a request falls back on, each read once under its own name, or an AppException + * that names it. A request's own params are checked on the request, as before. */ + function checkSettings() { + checkProvider({}); + if (backendName(prop) === BEDROCK_BACKEND) { + awsApi(prop); + } + wholeNumber('llm.max.tokens', prop('llm.max.tokens', String(DEFAULT_MAX_TOKENS)), 1); + wholeNumber('llm.timeout.ms', prop('llm.timeout.ms', String(DEFAULT_TIMEOUT_MS)), 1, MAX_TIMER_MS); + wholeNumber('llm.max.retries', prop('llm.max.retries', String(DEFAULT_MAX_RETRIES)), 0); + effortLevel('llm.effort', prop('llm.effort')); + fallbacksEnabled(); + switchOf(prop, 'llm.log.batches', false); + durationOf('llm.transcript.ttl', prop('llm.transcript.ttl', DEFAULT_TRANSCRIPT_TTL), 1); + durationOf('llm.transcript.retention', prop('llm.transcript.retention', DEFAULT_TRANSCRIPT_RETENTION), 0); + } + + /** The helper's settings are read when it starts - the ones a request falls back on, and the + * transcript store with its connection keys when one is named: a wrong one is a deployment error + * and stops the application by name, before a request finds it. */ + async function settingsBoot() { + try { + checkSettings(); + if (prop('llm.transcript.store')) { + await store(); + } + } catch (error) { + log.error(`llm.helper cannot start - ${error.message}`); + throw error; + } + } + return { prepare, plan, chat, stream, health, upload, transcriptAudit, auditSweep, auditBoot, auditShutdown, - auditSingleIdle, singleSaves: () => singleSaves.size, attachmentsBoot, + auditSingleIdle, singleSaves: () => singleSaves.size, attachmentsBoot, settingsBoot, sweeping: () => sweepTimer !== undefined }; } @@ -2324,6 +2417,8 @@ preload('llm.chat', { instances: 50 }, helper.chat); preload('llm.stream', { instances: 50, interceptor: true }, helper.stream); preload('llm.health', { instances: 5, isPrivate: true }, helper.health); preload('llm.upload', { instances: 10 }, helper.upload); +// the settings first: a wrong one stops the start before the audit opens its store +platform.onStartup(helper.settingsBoot); // the audit starts inside the serving loop, before the host listens, when it is configured platform.onStartup(helper.auditBoot); platform.onStartup(helper.attachmentsBoot); // a configured root that is not a folder stops the start diff --git a/test/llm-attachments.test.mjs b/test/llm-attachments.test.mjs index b42b31fa..36a9459a 100644 --- a/test/llm-attachments.test.mjs +++ b/test/llm-attachments.test.mjs @@ -30,7 +30,7 @@ import { fakeBackend, FakeWriter, settings, silent } from './fixtures/llm-helper const FIXTURES = fileURLToPath(new URL('./fixtures/attachments/', import.meta.url)); const VECTORS_FILE = new URL('./vectors/llm-attachments-vectors.json', import.meta.url); // the Python twin pins the same digests: change a file in both packs or in neither -const VECTORS_SHA256 = '06b0e85f7fa67c51eb9e63e0833d25a5e96f660c91210e460d3a346f2c574153'; +const VECTORS_SHA256 = '3d76157645db836ad64388d969dfefb644e732e5233fe623a3f0c756e17c2c7e'; const FIXTURES_SHA256 = { 'damaged.pdf': '36a27d716a382936c825c5c3cb7bd7a2d38c0af35242d89b186b31faf2eb4ee1', 'encrypted.pdf': '9f9e621bbe4dad963b3f5846b449dcc7424344335722c670e5d425efc7580dc7', diff --git a/test/llm-helper.test.mjs b/test/llm-helper.test.mjs index e48a7932..af691fb3 100644 --- a/test/llm-helper.test.mjs +++ b/test/llm-helper.test.mjs @@ -16,16 +16,16 @@ import { readFileSync } from 'node:fs'; import { test } from 'node:test'; import { AnthropicBedrock, AnthropicBedrockMantle } from '@anthropic-ai/bedrock-sdk'; import Anthropic from '@anthropic-ai/sdk'; -import { AppException } from 'mercury-composable'; +import { AppException, FunctionRegistry } from 'mercury-composable'; import { - anthropicBackend, blockOf, createLlmHelper, defaultBackend, defaultStore, failure, - MemoryStore, recordFrom, REDIS_SAVE, RedisStore, redisStore, TRANSCRIPT_PREFIX, transcript + anthropicBackend, blockOf, createLlmHelper, defaultAudit, defaultBackend, defaultStore, failure, + MemoryStore, postgresAuditStore, recordFrom, REDIS_SAVE, RedisStore, redisStore, TRANSCRIPT_PREFIX, transcript } from '../extensions/llm-helper/llm-helper.mjs'; import { delta, fakeBackend, FakeStream, FakeWriter, settings, silent, statusError } from './fixtures/llm-helper-fakes.mjs'; const VECTORS_FILE = new URL('./vectors/llm-helper-vectors.json', import.meta.url); // the Python twin pins the same digest: change the file in both packs or in neither -const VECTORS_SHA256 = 'eff1bfef426d6ac815f9a14ffc8de962eeac1894cbef0015b517b61c42b20b78'; +const VECTORS_SHA256 = 'cda5392eb56599b3ad8f5a5942af3e12a87c5c29972ab4d963050ddc0fe330ca'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const CHAT_CASES = VECTORS.cases.filter((c) => c.route === 'llm.chat'); const STREAM_CASES = VECTORS.cases.filter((c) => c.route === 'llm.stream'); @@ -413,6 +413,123 @@ for (const probe of NUMBERS.probes) { }); } +// --- the shared contract: how a switch of the configuration is read -------------------------- +// +// "switches" in llm-helper-vectors.json is one list of values and what each reads as: true, false, +// the switch's default, or nothing - a value that is refused by name instead of being read as off. + +const SWITCHES = VECTORS.switches; +const BOTH_STORES = { 'llm.transcript.store': 'redis', 'llm.transcript.audit': 'postgres' }; + +/** A PostgreSQL driver and a Redis driver that reach no server: the pool and the client as the + * helper builds them from the connection keys, and the options they were built with. */ +function noServers() { + const built = {}; + class Pool { + constructor(options) { built.pool = options; } + + async connect() { return { release() {} }; } + + async end() { return undefined; } + + on() {} + } + const redis = { createClient: (options) => { built.redis = options; return { on() {} }; } }; + return { + built, + pg: { importer: async () => ({ Pool }), log: silent }, + redis: { importer: async () => redis, log: silent } + }; +} + +/** Whether the audit store's pool is built to connect with TLS. */ +async function postgresTls(config) { + const drivers = noServers(); + await postgresAuditStore(settings(config), drivers.pg); + return drivers.built.pool.ssl !== false; +} + +/** Whether the transcript store's client is built to connect with TLS. */ +async function redisTls(config) { + const drivers = noServers(); + await redisStore(settings(config), drivers.redis); + return drivers.built.redis.socket.tls; +} + +for (const [key, fallback, tls] of [ + ['llm.transcript.audit.postgres.ssl', true, postgresTls], + ['llm.transcript.redis.ssl', false, redisTls] +]) { + for (const probe of SWITCHES.probes) { + // the TLS switch of each store, as the store it builds: TLS, none, or the refusal by name + test(`a switch is read as the python twin reads it: ${key} ${probe.name}`, async () => { + const config = probe.value === null ? BOTH_STORES : { ...BOTH_STORES, [key]: probe.value }; + let answer; + try { + answer = await tls(config); + } catch (error) { + answer = refusalFrom(error); + } + const wanted = probe.on === 'default' ? fallback : probe.on; + assert.deepEqual(answer, wanted ?? [500, SWITCHES.refusal.replace('{name}', key)]); + }); + } +} + +test('a switch that is wrong is refused before the model is called', async () => { + // the start refuses a switch that is wrong. A call that still meets one - a setting changed at + // run time - is a 500 by name on both routes, before any token is spent + const audited = { 'llm.transcript.store': 'memory', 'llm.transcript.audit': 'postgres' }; + const single = helperFor({ provider: REPLY, config: { ...audited, 'llm.transcript.audit.single': 'yes' } }); + await assert.rejects(single.helper.chat({}, { prompt: 'x' }), (error) => { + assert.deepEqual(refusalFrom(error), [500, 'llm.transcript.audit.single must be true or false']); + return true; + }); + await single.helper.stream({}, { body: { prompt: 'x' } }); + assert.deepEqual(refusalFrom(single.out.error), [500, 'llm.transcript.audit.single must be true or false']); + const batches = helperFor({ provider: REPLY, config: { 'llm.log.batches': 'on' } }); + await batches.helper.stream({}, { body: { prompt: 'x' } }); + assert.deepEqual(refusalFrom(batches.out.error), [500, 'llm.log.batches must be true or false']); + assert.equal(single.ledger.calls.length + batches.ledger.calls.length, 0, 'a wrong switch costs no model call'); +}); + +// --- the shared contract: what stops the application when it starts --------------------------- +// +// "start" in llm-helper-vectors.json names, for each of the three start-up steps, settings that are +// wrong and settings that are not: a wrong one stops the application by name, in the step's own +// voice, where it used to be refused on the first request that needed it. + +const START = VECTORS.start; + +for (const c of START.cases) { + // a start-up step with the case's settings: it passes without a word, or it logs the refusal in + // its own voice and stops the application + test(`a setting that is wrong stops the start by name: ${c.name}`, async () => { + const errors = []; + const drivers = noServers(); + const prop = settings(c.config); + const helper = createLlmHelper({ + prop, backend: () => fakeBackend(undefined).backend, store: defaultStore(prop, drivers.redis), + audit: defaultAudit(prop, drivers.pg), registry: new FunctionRegistry(), + log: { info() {}, warn() {}, error: (line) => errors.push(line) }, trace: () => {} + }); + const boot = { settings: helper.settingsBoot, attachments: helper.attachmentsBoot, audit: helper.auditBoot }[c.boot]; + try { + if (c.refused === null) { + await boot(); + } else { + await assert.rejects(boot(), (error) => { + assert.equal(error.message, c.refused); + return true; + }); + } + } finally { + await helper.auditShutdown(); + } + assert.deepEqual(errors, c.refused === null ? [] : [START.voices[c.boot].replace('{message}', c.refused)]); + }); +} + // --- the loop turn: what a vector cannot pin ----------------------------------------------- test('a stored block is the JSON the SDK would send back', () => { @@ -617,6 +734,24 @@ test('the redis store without the redis package is a 503 that names it', async ( }); }); +test('the redis store without the redis package stops the start by name', async () => { + // the store is built when the helper starts, so a client that is not installed is found then, + // as the audit store's driver is, and not on the first loop turn + const missing = Object.assign(new Error("Cannot find package 'redis'"), { code: 'ERR_MODULE_NOT_FOUND' }); + const errors = []; + const prop = settings({ 'llm.transcript.store': 'redis' }); + const helper = createLlmHelper({ + prop, backend: () => fakeBackend(undefined).backend, + store: defaultStore(prop, { importer: async () => { throw missing; } }), + log: { info() {}, warn() {}, error: (line) => errors.push(line) }, trace: () => {} + }); + await assert.rejects(helper.settingsBoot(), (error) => { + assert.equal(error.status, 503); + return true; + }); + assert.deepEqual(errors, ['llm.helper cannot start - The redis transcript store needs redis - npm install redis']); +}); + test('the redis store connects on the first command, within its timeout', async () => { let connects = 0; const waiting = { isOpen: false, connect: () => { connects += 1; return new Promise(() => {}); } }; diff --git a/test/vectors/llm-attachments-vectors.json b/test/vectors/llm-attachments-vectors.json index b3d9e14a..ee6c7db7 100644 --- a/test/vectors/llm-attachments-vectors.json +++ b/test/vectors/llm-attachments-vectors.json @@ -184,6 +184,24 @@ } } }, + { + "name": "shape/a-path-of-no-break-and-ideographic-spaces", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u00a0\u3000" + ] + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0].path must be a path inside llm.attachments.root" + ] + } + } + }, { "name": "shape/pages-that-are-not-pages", "route": "llm.chat", @@ -590,6 +608,69 @@ } } }, + { + "name": "root/a-path-of-a-byte-order-mark-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\ufeff" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, + { + "name": "root/a-path-of-a-separator-character-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u001c" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, + { + "name": "root/a-path-of-a-next-line-character-is-a-name", + "route": "llm.chat", + "body": { + "prompt": "Read the page.", + "attachments": [ + "\u0085" + ] + }, + "files": { + "page.png": "pixel.png" + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "attachments[0]: not found" + ] + } + } + }, { "name": "root/a-folder", "route": "llm.chat", diff --git a/test/vectors/llm-helper-vectors.json b/test/vectors/llm-helper-vectors.json index a29f1e91..2197d940 100644 --- a/test/vectors/llm-helper-vectors.json +++ b/test/vectors/llm-helper-vectors.json @@ -1,7 +1,7 @@ { "contract": "llm-helper", "version": 1, - "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream. numbers states how a number is read, the same in both packs: its own description gives the rule and what the harness checks.", + "description": "One contract, two function hosts. mercury-python and mercury-nodejs ship this file byte-identical and run every case against their own fake of the Anthropic SDK, so the two helpers cannot drift apart. A case's config may name llm.backend, and the harness then installs its fake under that backend's shape (bedrock: no server-side fallbacks, the messages namespace, and the model id by surface - llm.aws.api mantle, the default, prefixes a bare id with anthropic.; runtime sends every id as written). A case names the route, the config keys in force, the request body and what the fake provider does; the expectation is the exact SDK call (namespace, parameters, options), then either the reply map or the error (status and message fragments) for llm.chat, or the head, the segments in order, the terminal metadata (a subset) or the in-band error for llm.stream. numbers states how a number is read, switches how a switch of the configuration is read and start which settings stop the application when it starts, each the same in both packs: a section's own description gives the rule and what the harness checks.", "provider_kinds": { "message": "succeeds: deltas are the token batches; text is the final message text (default: the deltas joined); usage, model, stop_reason, request_id (the request-id response header), stop_details", "status": "an HTTP error from the API: status, type, message, request_id; after = the number of deltas delivered before it is raised (0: at open), deltas = those batches", @@ -11,7 +11,7 @@ "hang": "never answers - the helper's own deadline must fire" }, "numbers": { - "description": "How a number is read, the same in both packs: one list of values, each read as a whole number, as a duration and as the pages of a PDF. whole is the whole number the value spells, duration the seconds it spells, pages the ranges [first, last] it names, in the order named; null where it spells none, and \"absent\" for a null, which is a field left out. The rule: a whole number is a JSON number with a whole value (16000, or 16000.0, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9, up to 9007199254740991, the largest whole number both runtimes hold exactly; a duration is such a number of seconds, or ASCII digits and one of s, m, h, d, up to that many seconds; pages are numbers from 1 and ranges of them, joined by commas. The white space both runtimes' own trim takes (tab to carriage return, space, no-break space and the other space separators, the line and paragraph separators) is ignored around a whole number and a duration and anywhere in pages; any other character spells nothing - a sign, an underscore, a point, a digit of another script, a byte order mark. The harness reads each value as params.max_tokens (minimum 1) of llm.chat and, when it is a string, as the setting llm.max.retries (minimum 0): the SDK call carries the number, or the request is refused before any provider call. It reads it as the ttl (minimum 1) and as the retention (minimum 0) of a first loop turn on the memory store: the stored record lives that many seconds, or carries that retention, or the turn is refused before any provider call and no record is stored. It reads it as attachments[0].pages through the request check, which decides the shape before any file is read. A field refuses a number below its minimum as it refuses a value that spells none: status 400 and the text of refusals for its kind, {name} being the field and {minimum} its minimum.", + "description": "How a number is read, the same in both packs: one list of values, each read as a whole number, as a duration and as the pages of a PDF. whole is the whole number the value spells, duration the seconds it spells, pages the ranges [first, last] it names, in the order named; null where it spells none, and \"absent\" for a null, which is a field left out. The rule: a whole number is a JSON number with a whole value (16000, or 16000.0, which one runtime cannot tell from it) or a string of the ASCII digits 0 to 9, up to 9007199254740991, the largest whole number both runtimes hold exactly; a duration is such a number of seconds, or ASCII digits and one of s, m, h, d, up to that many seconds; pages are numbers from 1 and ranges of them, joined by commas. The white space both runtimes' own trim takes (tab to carriage return, space, no-break space and the other space separators, the line and paragraph separators) is ignored around a number - around a whole number and a duration, and in pages around each page number, so around a comma and a hyphen - and never inside one; any other character spells nothing - a sign, an underscore, a point, a digit of another script, a byte order mark. The harness reads each value as params.max_tokens (minimum 1) of llm.chat and, when it is a string, as the setting llm.max.retries (minimum 0): the SDK call carries the number, or the request is refused before any provider call. It reads it as the ttl (minimum 1) and as the retention (minimum 0) of a first loop turn on the memory store: the stored record lives that many seconds, or carries that retention, or the turn is refused before any provider call and no record is stored. It reads it as attachments[0].pages through the request check, which decides the shape before any file is read. A field refuses a number below its minimum as it refuses a value that spells none: status 400 and the text of refusals for its kind, {name} being the field and {minimum} its minimum.", "refusals": { "whole": "{name} must be a whole number >= {minimum}", "duration": "{name} must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= {minimum}", @@ -138,12 +138,7 @@ "value": "5 12", "whole": null, "duration": null, - "pages": [ - [ - 512, - 512 - ] - ] + "pages": null }, { "name": "a-byte-order-mark-before", @@ -757,6 +752,32 @@ ] ] }, + { + "name": "two-pages-without-a-comma", + "value": "1 3", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "a-space-inside-a-page-of-a-range", + "value": "1 0-12", + "whole": null, + "duration": null, + "pages": null + }, + { + "name": "line-breaks-around-a-hyphen", + "value": "1\n-\n3", + "whole": null, + "duration": null, + "pages": [ + [ + 1, + 3 + ] + ] + }, { "name": "pages-with-a-byte-order-mark", "value": "1\ufeff-3", @@ -827,6 +848,553 @@ } ] }, + "switches": { + "description": "How a switch of the configuration is read, the same in both packs: true or false, the boolean or the text in any letter case; no value and an empty one are the switch's default; any other value - yes, on, 1, a number, text with a space around it - is refused by name, where it used to be read as off without a word. on is what the value reads as: true, false, \"default\", or null for a value that is refused. The harness gives each value to llm.transcript.audit.postgres.ssl (default true) and to llm.transcript.redis.ssl (default false) and builds the store from the connection keys: the connection is made with TLS or without it, or the build is refused with status 500 and the text of refusal, {name} being the key. A value reaches the reader as a boolean or as text, whichever the configuration gave; the two read the same.", + "refusal": "{name} must be true or false", + "probes": [ + { + "name": "the-boolean-true", + "value": true, + "on": true + }, + { + "name": "the-boolean-false", + "value": false, + "on": false + }, + { + "name": "true", + "value": "true", + "on": true + }, + { + "name": "false", + "value": "false", + "on": false + }, + { + "name": "upper-case-true", + "value": "TRUE", + "on": true + }, + { + "name": "capitalized-true", + "value": "True", + "on": true + }, + { + "name": "upper-case-false", + "value": "FALSE", + "on": false + }, + { + "name": "mixed-case-false", + "value": "fAlSe", + "on": false + }, + { + "name": "empty-text", + "value": "", + "on": "default" + }, + { + "name": "no-value", + "value": null, + "on": "default" + }, + { + "name": "yes", + "value": "yes", + "on": null + }, + { + "name": "no", + "value": "no", + "on": null + }, + { + "name": "on", + "value": "on", + "on": null + }, + { + "name": "off", + "value": "off", + "on": null + }, + { + "name": "one-as-text", + "value": "1", + "on": null + }, + { + "name": "zero-as-text", + "value": "0", + "on": null + }, + { + "name": "a-word", + "value": "maybe", + "on": null + }, + { + "name": "a-letter", + "value": "t", + "on": null + }, + { + "name": "spaces-around-true", + "value": " true ", + "on": null + }, + { + "name": "the-number-one", + "value": 1, + "on": null + }, + { + "name": "the-number-zero", + "value": 0, + "on": null + }, + { + "name": "a-list", + "value": [ + true + ], + "on": null + } + ] + }, + "start": { + "description": "What stops the application when it starts, the same in both packs: a setting that is wrong is a deployment error, refused by name before a request finds it, where it used to be refused on the first request that needed it - some after the model was called - or read as off. A case names the start-up step (settings: the settings a request falls back on and the transcript store with its connection keys; attachments: the limits and the root; audit: the audit store), the configuration keys in force and refused: null when the step passes, else the refusal. A step that refuses logs one line at ERROR, the text of voices for the step with {message} the refusal, and stops the start; a step that passes logs none. The harness builds the stores from the connection keys with clients that reach no server, so a step that passes opens nothing. A request's own params are not settings: they keep their 400 on the request. A timer takes at most 2147483647 ms (about 24.8 days, the longest wait both runtimes' timers hold), a port is at most 65535, and the audit retention at most 1000000d, with which a conversation's expires_at is a date of a four-digit year.", + "voices": { + "settings": "llm.helper cannot start - {message}", + "attachments": "attachments cannot start - {message}", + "audit": "transcript audit store cannot start - {message}" + }, + "cases": [ + { + "name": "settings/the-defaults-start", + "boot": "settings", + "config": {}, + "refused": null + }, + { + "name": "settings/an-unknown-provider", + "boot": "settings", + "config": { + "llm.provider": "gemini" + }, + "refused": "unknown LLM provider 'gemini' - this helper serves: anthropic" + }, + { + "name": "settings/an-unknown-backend", + "boot": "settings", + "config": { + "llm.backend": "vertex" + }, + "refused": "unknown LLM backend 'vertex' - this helper serves: anthropic, bedrock" + }, + { + "name": "settings/an-unknown-bedrock-surface", + "boot": "settings", + "config": { + "llm.backend": "bedrock", + "llm.aws.api": "console" + }, + "refused": "llm.aws.api must be one of: mantle, runtime" + }, + { + "name": "settings/the-bedrock-surface-is-read-for-bedrock-only", + "boot": "settings", + "config": { + "llm.aws.api": "console" + }, + "refused": null + }, + { + "name": "settings/max-tokens-not-a-number", + "boot": "settings", + "config": { + "llm.max.tokens": "lots" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/max-tokens-zero", + "boot": "settings", + "config": { + "llm.max.tokens": "0" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/max-tokens-in-the-digits-of-another-script", + "boot": "settings", + "config": { + "llm.max.tokens": "\u0663" + }, + "refused": "llm.max.tokens must be a whole number >= 1" + }, + { + "name": "settings/timeout-not-a-number", + "boot": "settings", + "config": { + "llm.timeout.ms": "soon" + }, + "refused": "llm.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/timeout-above-the-longest-timer", + "boot": "settings", + "config": { + "llm.timeout.ms": "2147483648" + }, + "refused": "llm.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/the-longest-timer-starts", + "boot": "settings", + "config": { + "llm.timeout.ms": "2147483647" + }, + "refused": null + }, + { + "name": "settings/retries-not-a-number", + "boot": "settings", + "config": { + "llm.max.retries": "two" + }, + "refused": "llm.max.retries must be a whole number >= 0" + }, + { + "name": "settings/an-unknown-effort", + "boot": "settings", + "config": { + "llm.effort": "extreme" + }, + "refused": "llm.effort must be one of: low, medium, high, xhigh, max" + }, + { + "name": "settings/fallbacks-neither-default-nor-off", + "boot": "settings", + "config": { + "llm.fallbacks": "maybe" + }, + "refused": "llm.fallbacks must be 'default' or 'off'" + }, + { + "name": "settings/batch-logging-not-a-switch", + "boot": "settings", + "config": { + "llm.log.batches": "yes" + }, + "refused": "llm.log.batches must be true or false" + }, + { + "name": "settings/ttl-not-a-duration", + "boot": "settings", + "config": { + "llm.transcript.ttl": "week" + }, + "refused": "llm.transcript.ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "settings/ttl-zero", + "boot": "settings", + "config": { + "llm.transcript.ttl": "0" + }, + "refused": "llm.transcript.ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "settings/retention-not-a-duration", + "boot": "settings", + "config": { + "llm.transcript.retention": "forever" + }, + "refused": "llm.transcript.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "settings/an-unknown-transcript-store", + "boot": "settings", + "config": { + "llm.transcript.store": "rediss" + }, + "refused": "llm.transcript.store must be one of: memory, redis" + }, + { + "name": "settings/redis-port-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "sixty" + }, + "refused": "llm.transcript.redis.port must be a whole number >= 1" + }, + { + "name": "settings/redis-port-above-the-highest", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "65536" + }, + "refused": "llm.transcript.redis.port must be a whole number >= 1" + }, + { + "name": "settings/redis-database-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.database": "x" + }, + "refused": "llm.transcript.redis.database must be a whole number >= 0" + }, + { + "name": "settings/redis-timeout-not-a-number", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.timeout.ms": "x" + }, + "refused": "llm.transcript.redis.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/redis-timeout-above-the-longest-timer", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.timeout.ms": "2147483648" + }, + "refused": "llm.transcript.redis.timeout.ms must be a whole number >= 1" + }, + { + "name": "settings/redis-tls-not-a-switch", + "boot": "settings", + "config": { + "llm.transcript.store": "redis", + "llm.transcript.redis.ssl": "yes" + }, + "refused": "llm.transcript.redis.ssl must be true or false" + }, + { + "name": "settings/the-redis-keys-are-read-for-redis-only", + "boot": "settings", + "config": { + "llm.transcript.store": "memory", + "llm.transcript.redis.port": "sixty" + }, + "refused": null + }, + { + "name": "settings/every-setting-well-formed-starts", + "boot": "settings", + "config": { + "llm.provider": "anthropic", + "llm.backend": "bedrock", + "llm.aws.api": "runtime", + "llm.max.tokens": "2048", + "llm.timeout.ms": "9000", + "llm.max.retries": "0", + "llm.effort": "LOW", + "llm.fallbacks": "OFF", + "llm.log.batches": "TRUE", + "llm.transcript.ttl": "12h", + "llm.transcript.retention": "0", + "llm.transcript.store": "redis", + "llm.transcript.redis.port": "65535", + "llm.transcript.redis.database": "2", + "llm.transcript.redis.timeout.ms": "2147483647", + "llm.transcript.redis.ssl": "true" + }, + "refused": null + }, + { + "name": "attachments/the-defaults-start", + "boot": "attachments", + "config": {}, + "refused": null + }, + { + "name": "attachments/max-count-not-a-number", + "boot": "attachments", + "config": { + "llm.attachments.max.count": "many" + }, + "refused": "llm.attachments.max.count must be a whole number >= 1" + }, + { + "name": "attachments/max-bytes-not-a-number", + "boot": "attachments", + "config": { + "llm.attachments.max.bytes": "big" + }, + "refused": "llm.attachments.max.bytes must be a whole number >= 1" + }, + { + "name": "attachments/max-bytes-zero", + "boot": "attachments", + "config": { + "llm.attachments.max.bytes": "0" + }, + "refused": "llm.attachments.max.bytes must be a whole number >= 1" + }, + { + "name": "attachments/limits-well-formed-start", + "boot": "attachments", + "config": { + "llm.attachments.max.count": "5", + "llm.attachments.max.bytes": "1000" + }, + "refused": null + }, + { + "name": "audit/grace-not-a-duration", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.grace": "x" + }, + "refused": "llm.transcript.audit.grace must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 1" + }, + { + "name": "audit/retention-not-a-duration", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "forever" + }, + "refused": "llm.transcript.audit.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "audit/retention-above-the-longest", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "1000001d" + }, + "refused": "llm.transcript.audit.retention must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) >= 0" + }, + { + "name": "audit/the-longest-retention-starts", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.retention": "1000000d", + "llm.transcript.audit.sweep.ms": "0" + }, + "refused": null + }, + { + "name": "audit/sweep-not-a-number", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.sweep.ms": "soon" + }, + "refused": "llm.transcript.audit.sweep.ms must be a whole number >= 0" + }, + { + "name": "audit/sweep-above-the-longest-timer", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.sweep.ms": "2147483648" + }, + "refused": "llm.transcript.audit.sweep.ms must be a whole number >= 0" + }, + { + "name": "audit/single-calls-not-a-switch", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.store": "memory", + "llm.transcript.audit.single": "yes" + }, + "refused": "llm.transcript.audit.single must be true or false" + }, + { + "name": "audit/single-calls-without-the-working-store", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.single": "true" + }, + "refused": "llm.transcript.audit.single needs the working store - set llm.transcript.store (redis, or memory for a single process)" + }, + { + "name": "audit/postgres-tls-not-a-switch", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.ssl": "yes" + }, + "refused": "llm.transcript.audit.postgres.ssl must be true or false" + }, + { + "name": "audit/postgres-port-not-a-number", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.port": "x" + }, + "refused": "llm.transcript.audit.postgres.port must be a whole number >= 1" + }, + { + "name": "audit/postgres-port-above-the-highest", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.port": "65536" + }, + "refused": "llm.transcript.audit.postgres.port must be a whole number >= 1" + }, + { + "name": "audit/postgres-timeout-above-the-longest-timer", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.audit.postgres.timeout.ms": "2147483648" + }, + "refused": "llm.transcript.audit.postgres.timeout.ms must be a whole number >= 1" + }, + { + "name": "audit/an-unknown-audit-store", + "boot": "audit", + "config": { + "llm.transcript.audit": "mongo" + }, + "refused": "llm.transcript.audit must be one of: postgres" + }, + { + "name": "audit/every-setting-well-formed-starts", + "boot": "audit", + "config": { + "llm.transcript.audit": "postgres", + "llm.transcript.store": "memory", + "llm.transcript.audit.grace": "2h", + "llm.transcript.audit.retention": "30d", + "llm.transcript.audit.sweep.ms": "0", + "llm.transcript.audit.single": "TRUE", + "llm.transcript.audit.postgres.ssl": "False", + "llm.transcript.audit.postgres.port": "5433", + "llm.transcript.audit.postgres.timeout.ms": "2500" + }, + "refused": null + }, + { + "name": "audit/the-audit-keys-are-read-with-an-audit-store-only", + "boot": "audit", + "config": { + "llm.transcript.audit.grace": "x", + "llm.transcript.audit.sweep.ms": "soon" + }, + "refused": null + } + ] + }, "cases": [ { "name": "prep/missing-prompt-and-messages", @@ -1047,6 +1615,24 @@ } } }, + { + "name": "prep/timeout-above-the-longest-timer", + "route": "llm.chat", + "body": { + "prompt": "x", + "params": { + "timeout_ms": 2147483648 + } + }, + "expect": { + "error": { + "status": 400, + "message_contains": [ + "params.timeout_ms must be a whole number >= 1" + ] + } + } + }, { "name": "prep/bad-effort", "route": "llm.chat", @@ -1737,6 +2323,62 @@ } } }, + { + "name": "chat/the-longest-timeout-is-accepted", + "route": "llm.chat", + "body": { + "prompt": "x", + "params": { + "timeout_ms": 2147483647 + } + }, + "provider": { + "kind": "message", + "model": "claude-opus-5-5", + "stop_reason": "end_turn", + "deltas": [ + "ok" + ], + "usage": { + "input_tokens": 5, + "output_tokens": 1 + }, + "request_id": "req_ok_001" + }, + "expect": { + "sdk": { + "namespace": "beta.messages", + "params": { + "model": "claude-opus-5-5", + "max_tokens": 16000, + "messages": [ + { + "role": "user", + "content": "x" + } + ], + "betas": [ + "server-side-fallback-2026-07-01" + ], + "fallbacks": "default" + }, + "options": { + "timeout_ms": 2147483647, + "max_retries": 2 + } + }, + "result": { + "text": "ok", + "model": "claude-opus-5-5", + "stop_reason": "end_turn", + "usage": { + "input_tokens": 5, + "output_tokens": 1 + }, + "request_id": "req_ok_001" + } + } + }, { "name": "chat/other-model-gets-no-fallbacks", "route": "llm.chat", From 02c289334170cd8545c144262f830ea2fc27af00 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:20 -0800 Subject: [PATCH 4/6] fix(ask-person, agent-question): one reader of a time, a number, a duration and a switch; a signed payload has one spelling A time is a date, T, a time to the minute or the second, and Z or an offset, read to the millisecond by one rule in both packs. A wait whose expiry is past the year 9999 is a 400. turn, ttl, the list's since, before and limit and every setting follow the number and duration rule; a switch that is neither true nor false stops the boot. The bytes under a ticket's signature are the canonical JSON of its five fields. A setting that sets a timer is at most 2147483647 ms, a port at most 65535, a turn at most 2147483647. A required text is blank by the same 24 characters in both packs. A graph is looked up among the configured ones only, and a row id or a whole number above 2^53-1 is held and written with every digit. Co-Authored-By: Claude Fable 5.2 --- extensions/agent-question/README.md | 40 +- extensions/agent-question/agent-question.mjs | 333 +- extensions/ask-person/README.md | 65 +- extensions/ask-person/ask-person.mjs | 328 +- test/agent-question.test.mjs | 422 +- test/ask-person.test.mjs | 476 +- test/vectors/agent-question-vectors.json | 6227 +++++++- test/vectors/ask-person-vectors.json | 12978 ++++++++++++++--- 8 files changed, 17956 insertions(+), 2913 deletions(-) diff --git a/extensions/agent-question/README.md b/extensions/agent-question/README.md index b8653c2d..9e5beaf4 100644 --- a/extensions/agent-question/README.md +++ b/extensions/agent-question/README.md @@ -10,7 +10,12 @@ application is one of those routes. It is a standalone application on the packag - **Intake.** `agent.question.inbox` is a composable function reached over Event-over-HTTP like any peer function. It writes nothing - the record is the recorder's (`question.audit` in the ask-person process) - it checks the event and - wakes the feed, so a connected device sees the row the moment it is recorded. + wakes the feed, so a connected device sees the row the moment it is recorded. The event's `turn` is read as the main + flow reads it - a whole number: a JSON number with a whole value or ASCII digits, at most 2147483647, the largest the + record's `turn` column holds - and the answer carries the number. Its `requested_at` and a wait's `expires_at` are + times by the main flow's one reader - a date, an upper-case `T`, a time, then `Z` or an offset `+HH:MM` - and a text + the event must carry is blank by the main flow's rule, the white space of a number and no other character; anything + else is a 400. - **The person's side**, REST automation entries of `resources/rest.yaml` (RFC-0018, `rest.automation: true`), each a private function of this process (`question.config`, `question.list`, `question.events`, `question.decide`, `transcript.list`, `transcript.show`); who is at the UI is resolved once by the entries' authentication function, @@ -29,10 +34,19 @@ application is one of those routes. It is a standalone application on the packag the feed carries the change to every device. A row id and a stream's cursor - `Last-Event-ID`, else `since`, else the beginning - are one to nineteen ASCII digits from start to end, no larger than the record's `BIGINT` columns hold (9223372036854775807); anything else is a 400. + `GET /questions` reads its `since` and its `before` the same way (an empty `before` is the newest page), and a + `limit` - there and in `GET /transcripts` - is a whole number: ASCII digits, at most 9007199254740991, with white + space ignored around it, held between 1 and the most a page takes (1000 rows, 200 conversations); anything else is a + 400. A row is told by the numbers it has: a page, a stream's event and a refusal carry `id` and `seq` with every + digit, past 9007199254740991 too, and so is a whole number that large in a row's calls or in a decision the click + forwards. The `before` of `GET /transcripts` is a time by the main flow's one reader - `2026-11-19T11:00:00Z`, or + the same instant at an offset, whose plus sign is `%2B` in a URL - and the store is asked by that instant in UTC, to + the millisecond; anything else is a 400. - **The feed** reads the record's change sequence: a poll every `question.poll` (1 s) and a wake-up from the intake or a click, whichever comes first. A wait is `open` until the engine accepts the decision (`answered`) or finds nothing waiting (`expired`); an advice has no state - whether a person has read it is the device's, kept by the UI. The - record is never written here; the recorder's sweeper expires waits and the installation's purge retires rows. + record is never written here; the recorder's sweeper expires waits and the installation's purge retires rows. The + health reply tells the feed's cursor: a number up to 9007199254740991 and its digits, as text, beyond. This app is the backend in both packs. Its front-end - the React UI with the question-and-answer panel, the history with infinite scroll and the transcript browser - is built and maintained here, in @@ -112,11 +126,25 @@ flow as `decided_by` under its own bearer (`question.reply.token`, the reply end | `question.reply.timeout` | `10s` | how long the reply endpoint may take | | `question.page.title` | `Agent questions` | the UI's title, told through `GET /questions/config` | +A setting is read by the main flow's rule, whether a YAML file holds the value or a `${NAME:default}` reference or a +`-D` override gives it as text: `.port` and `.timeout.ms` are whole numbers - ASCII digits, a port 1 to 65535; +`question.poll` and `question.reply.timeout` are durations - seconds, or `ms`, `s`, `m`, `h`, `d` right after the +number - more than zero. A setting that sets a timer - the two durations and `.timeout.ms` - takes at most 2147483647 +ms (about 24.8 days), the longest delay both runtimes' timers hold; the host's `event.stream.keep.alive` is also how +often a quiet stream looks for its device, so one longer than that stops the boot too, by the host's own message. +`question.store.postgres.ssl` is a switch: `true` or `false`, the boolean or the text in any letter case; no value and +an empty one are the default; any other value stops the boot by the key's name instead of being read as on. So does a +number or a duration that is not one. A setting's text loses the white space of the number rule around it and no other +character. + ## Tests `test/agent-question.test.mjs` runs the shared vectors (`test/vectors/agent-question-vectors.json`: the event the intake accepts or refuses, the request the click sends, the pages the replay and the history read, the row id and the cursor a -request names) and drives the app in-process as the reader of the record: the intake waking the feed, the replay and the -history pages and the stream, the transcripts browsed, a decision forwarded to a fake reply endpoint and the row re-read -as the recorder left it, the two auth modes with the UI's configuration, the PostgreSQL reader's statements on a -recording fake of the pool, and - gated on `AGENT_QUESTION_TEST_URL` - the schemas and the rows on a live PostgreSQL. +request names, what `GET /questions` asks for, a page size, rows past the whole numbers a double holds, a number, a +duration and a switch as the one rule reads them, a time as the one reader reads it and the white space around a +text) and drives the app in-process as the reader of the record: the intake +waking the feed, the replay and the history pages and the stream, the transcripts browsed, a decision forwarded to a +fake reply endpoint and the row re-read as the recorder left it, the two auth modes with the UI's configuration, the +PostgreSQL reader's statements on a recording fake of the pool, and - gated on `AGENT_QUESTION_TEST_URL` - the schemas +and the rows on a live PostgreSQL. diff --git a/extensions/agent-question/agent-question.mjs b/extensions/agent-question/agent-question.mjs index e5cb8e4c..5787e065 100644 --- a/extensions/agent-question/agent-question.mjs +++ b/extensions/agent-question/agent-question.mjs @@ -100,8 +100,38 @@ export const REPLY_TIMEOUT = 'question.reply.timeout'; export const PAGE_TITLE = 'question.page.title'; export const MISSING_POSTGRES = 'question.store is postgres but the pg driver is not installed - npm install pg'; -const DURATION = /^(\d+)\s*(ms|s|m|h|d)?$/; +// how a number is read, the same in both packs and in every extension. The white space ignored around a number and a +// duration: the characters JavaScript's trim() and Python's str.strip() both take for white space, so neither pack +// accepts a character the other refuses +const SPACE = String.raw`[\t-\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]`; +// the same 24 characters where they stand around a text, to take off: a required text is blank and a setting's text is +// trimmed by these and no other. Each runtime's own trim takes a few more - this one's U+FEFF, the Python twin's +// U+001C to U+001F and U+0085 - which here are characters of a name. The lookbehind starts a match only at a run's +// first character, so the scan stays linear +const AROUND = new RegExp(`^${SPACE}+|(? typeof value === 'object' && value !== null && !Array.isArray(value); const isText = (value) => typeof value === 'string'; -const isWhole = (value) => typeof value === 'number' && Number.isInteger(value); +/** + * What a number is read from: a string as written, or the digits of a JSON number with a whole value - an integer, + * which is all this pack sees of a float such as 16000.0. Null for anything else: a boolean, a fraction, a number + * beyond Number.MAX_SAFE_INTEGER. + */ +function numberText(value) { + if (isText(value)) return value; + return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : null; +} + +/** The whole number a run of ASCII digits spells, or null above Number.MAX_SAFE_INTEGER. */ +function digits(run) { + const number = Number(run); + return Number.isSafeInteger(number) ? number : null; +} + +/** + * The whole number a value spells - a JSON number with a whole value, or ASCII digits with white space around them at + * most - up to Number.MAX_SAFE_INTEGER; null when it spells none: a sign, an underscore, a point or an exponent in + * text, a digit of another script. + */ +export function wholeNumber(value) { + const match = WHOLE.exec(numberText(value) ?? ''); + return match ? digits(match[1]) : null; +} + +/** + * Milliseconds from a whole number of seconds or a duration such as 500ms, 30m, 12h or 2d - such a number and, right + * after it, one of ms, s, m, h, d - up to Number.MAX_SAFE_INTEGER milliseconds; null when the value is neither. + */ export function durationMs(value) { - if (typeof value === 'boolean') return null; - if (typeof value === 'number') return Number.isInteger(value) && value >= 0 ? value * 1000 : null; - if (!isText(value)) return null; - const match = DURATION.exec(value.trim()); - if (!match) return null; - return Number.parseInt(match[1], 10) * UNIT_MS[match[2] ?? 's']; + const match = DURATION.exec(numberText(value) ?? ''); + const count = match ? digits(match[1]) : null; + if (count === null) return null; + const ms = count * UNIT_MS[match[2] ?? 's']; + return Number.isSafeInteger(ms) ? ms : null; } +/** + * What a switch is set to: the boolean, or the text true or false in any letter case; no value and an empty one are + * the default. Null for any other value - it is never read as off. + */ +export function switchValue(value, defaultValue) { + if (value === undefined || value === null || value === '') return defaultValue; + if (typeof value === 'boolean') return value; + const lowered = isText(value) ? value.toLowerCase() : ''; + if (lowered !== 'true' && lowered !== 'false') return null; + return lowered === 'true'; +} + +/** + * A text without the white space around it - the 24 characters of the number rule, the same in both packs, where + * trim() alone takes a few more. A blank text leaves nothing. + */ +const trimmed = (value) => value.replace(AROUND, ''); + +/** + * An ISO-8601 time with an offset or Z, as a Date; null when it is not one. One reader in both packs and in the main + * flow: a date YYYY-MM-DD, an upper-case T, a time HH:MM or HH:MM:SS - the second with a fraction of one to nine + * digits at most - then Z or +HH:MM / -HH:MM, and nothing before or after it; a date the calendar has, in the years + * 0001 to 9999 as written and in UTC. The instant is read to the millisecond: a longer fraction is cut, never rounded. + */ export function parseIso(text) { - const candidate = String(text).trim(); - if (!/^\d{4}-\d{2}-\d{2}/.test(candidate)) return null; - const ms = Date.parse(candidate); - return Number.isNaN(ms) ? null : new Date(ms); + const match = ISO_TIME.exec(text); + if (match === null) return null; + const [year, month, day, hour, minute, second, offsetHours, offsetMinutes] = [1, 2, 3, 4, 5, 6, 9, 10].map((at) => Number(match[at] ?? 0)); + if (year < 1 || hour > 23 || minute > 59 || second > 59 || offsetHours > 23 || offsetMinutes > 59) return null; + // the date as written, at midnight UTC: setUTCFullYear takes a year before 100 as it is, and a date the calendar + // does not have comes back as another + const written = new Date(0); + written.setUTCFullYear(year, month - 1, day); + if (written.getUTCFullYear() !== year || written.getUTCMonth() !== month - 1 || written.getUTCDate() !== day) return null; + const millisecond = Number((match[7] ?? '').padEnd(3, '0').slice(0, 3)); + const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes); + const ms = written.getTime() + ((hour * 60 + minute - offset) * 60 + second) * 1000 + millisecond; + return ms < MIN_TIME_MS || ms > MAX_TIME_MS ? null : new Date(ms); } // --- configuration ---------------------------------------------------------------------------- function text(config, key, defaultValue = '') { const value = config.get(key); - return value === undefined || value === null ? defaultValue : String(value).trim(); + return value === undefined || value === null ? defaultValue : trimmed(String(value)); } +/** A setting that sets a timer: a duration of more than nothing and of no more than a timer holds. */ function timeout(config, key, defaultValue) { const value = config.get(key); const ms = durationMs(value === undefined || value === null ? defaultValue : value); - if (ms === null || ms <= 0) throw new QuestionError(`${key} must be a duration such as 10s or 2m (seconds, s, m, h, d) > 0`); + if (ms === null || ms <= 0 || ms > MAX_TIMER_MS) { + throw new QuestionError(`${key} must be a duration such as 10s or 2m (seconds, s, m, h, d) > 0`); + } return ms; } -/** A key named in milliseconds (timeout.ms): a whole number > 0. */ +/** A key named in milliseconds (timeout.ms): a whole number > 0, and no more than a timer holds. */ function wholeMs(config, key, defaultValue) { const value = config.get(key); - const candidate = String(value === undefined || value === null ? defaultValue : value).trim(); - if (!/^\d+$/.test(candidate) || Number.parseInt(candidate, 10) <= 0) { + const number = wholeNumber(value === undefined || value === null ? defaultValue : value); + if (number === null || number <= 0 || number > MAX_TIMER_MS) { throw new QuestionError(`${key} must be a whole number of milliseconds > 0`); } - return Number.parseInt(candidate, 10); + return number; +} + +/** + * The host's keep-alive interval sets a timer of this app too - a quiet stream looks for its device that often: one + * longer than a timer holds stops the boot by the key's own message. A value that is no duration is the host's to + * refuse. + */ +function checkKeepAlive(config) { + const ms = durationMs(config.get(KEEP_ALIVE) ?? '30s'); + if (ms !== null && ms > MAX_TIMER_MS) throw new QuestionError(KEEP_ALIVE_RULE); +} + +/** + * A switch of the configuration, or a QuestionError naming the key: a value that is neither true nor false stops the + * boot instead of leaving the switch off. + */ +function switchOf(config, key, defaultValue) { + const value = switchValue(config.get(key), defaultValue); + if (value === null) throw new QuestionError(`${key} must be true or false`); + return value; } export function loadSettings(config) { @@ -175,14 +289,15 @@ export function loadSettings(config) { } } const timeoutMs = wholeMs(config, `${POSTGRES_PREFIX}timeout.ms`, 5000); - const portText = text(config, `${POSTGRES_PREFIX}port`, '5432'); - if (!/^\d+$/.test(portText) || Number.parseInt(portText, 10) <= 0) throw new QuestionError(`${POSTGRES_PREFIX}port must be a port number`); - const ssl = text(config, `${POSTGRES_PREFIX}ssl`, 'true').toLowerCase() !== 'false'; + const port = wholeNumber(config.get(`${POSTGRES_PREFIX}port`) ?? 5432); + if (port === null || port < 1 || port > MAX_PORT) throw new QuestionError(`${POSTGRES_PREFIX}port must be a port number`); + const ssl = switchOf(config, `${POSTGRES_PREFIX}ssl`, true); + checkKeepAlive(config); return { store, postgres: { host: text(config, `${POSTGRES_PREFIX}host`, '127.0.0.1'), - port: Number.parseInt(portText, 10), + port, database: text(config, `${POSTGRES_PREFIX}database`, 'mercury'), user: text(config, `${POSTGRES_PREFIX}username`) || undefined, password: text(config, `${POSTGRES_PREFIX}password`) || undefined, @@ -231,7 +346,10 @@ export function publicRow(row) { }; } -/** What a wait carries beyond an advice - its turn, its ticket, link and expiry, its calls - or an AppException(400). */ +/** + * What a wait carries beyond an advice - its turn, its ticket, link and expiry (a time by the one reader of both + * packs), its calls - or an AppException(400). + */ function validateWait(event, turn) { if (turn === undefined || turn === null) throw new AppException(400, 'turn is required for an approval or a question'); for (const name of ['ticket', 'link', 'expires_at']) { @@ -240,6 +358,32 @@ function validateWait(event, turn) { if (!Array.isArray(event.calls) || event.calls.length === 0) { throw new AppException(400, 'calls must be a non-empty list for an approval or a question'); } + if (parseIso(event.expires_at) === null) throw new AppException(400, 'expires_at must be an ISO-8601 time'); +} + +/** + * An event's turn as the whole number it is - up to the largest the record's column holds - and null when the event + * carries none; or an AppException(400). + */ +function turnOf(event) { + const given = event.turn; + if (given === undefined || given === null) return null; + const turn = wholeNumber(given); + if (turn === null || turn > MAX_TURN) throw new AppException(400, 'turn must be a whole number >= 0'); + return turn; +} + +/** + * What an event may carry beyond what it must: details and requested_at as text, and requested_at a time by the one + * reader of both packs - or an AppException(400). + */ +function validateOptional(event) { + for (const name of ['details', 'requested_at']) { + if (event[name] !== undefined && event[name] !== null && !isText(event[name])) throw new AppException(400, `${name} must be text`); + } + if (event.requested_at !== undefined && event.requested_at !== null && parseIso(event.requested_at) === null) { + throw new AppException(400, 'requested_at must be an ISO-8601 time'); + } } /** The message event the main flow sends, checked for what a channel needs - or an AppException(400). */ @@ -249,15 +393,14 @@ export function validateEvent(event) { if (!KINDS.includes(kind)) throw new AppException(400, 'kind must be one of approval, question, advice'); for (const name of ['graph_id', 'description', 'correlation_id', 'summary']) { const value = event[name]; - if (!isText(value) || !value.trim()) throw new AppException(400, `${name} is required`); + // blank - nothing but the white space of the number rule - is as good as missing, in both packs + if (!isText(value) || !trimmed(value)) throw new AppException(400, `${name} is required`); } - const turn = event.turn; - if (turn !== undefined && turn !== null && (!isWhole(turn) || turn < 0)) throw new AppException(400, 'turn must be a whole number >= 0'); + const turn = turnOf(event); if (WAIT_KINDS.includes(kind)) validateWait(event, turn); - for (const name of ['details', 'requested_at']) { - if (event[name] !== undefined && event[name] !== null && !isText(event[name])) throw new AppException(400, `${name} must be text`); - } - return { ...event }; + validateOptional(event); + // the turn as the whole number it is, however it was written - "2" is turn 2 in both packs + return turn === null ? { ...event } : { ...event, turn }; } /** The click, automated: the reply endpoint is the link's own base, the body what a person's browser would post. */ @@ -267,6 +410,37 @@ export function replyRequest(link, ticket, decisions, who) { return [`${link.slice(0, at)}/ask/reply`, { ticket, decisions: decisions.map((d) => ({ ...d })), decided_by: who }]; } +/** + * A number of the record held exactly, from the digits a request or the database gives (a BIGINT column arrives as + * text): a number, or a BigInt past the whole numbers a number holds exactly - so a row is found, ordered and shown by + * the number it has, never by the nearest one a number can hold. + */ +function exact(value) { + const big = BigInt(value); + return big > Number.MAX_SAFE_INTEGER || big < Number.MIN_SAFE_INTEGER ? big : Number(big); +} + +/** Rows by their sequence, oldest change first - compared, never subtracted: a sequence may be a BigInt. */ +function bySeq(a, b) { + if (a.seq < b.seq) return -1; + return a.seq > b.seq ? 1 : 0; +} + +/** The newest sequence among rows, or the one given when none is newer - compared, as a sequence may be a BigInt. */ +function newestSeq(rows, start) { + let newest = start; + for (const row of rows) { + if (row.seq > newest) newest = row.seq; + } + return newest; +} + +/** + * JSON as a client reads it, with a BigInt written as the number it is - every digit, where JSON.stringify alone + * refuses one. + */ +const toJson = (value) => JSON.stringify(value, (_key, item) => (typeof item === 'bigint' ? JSON.rawJSON(String(item)) : item)); + /** * A row id or a cursor as a request names it: one to nineteen ASCII digits from start to end, and no more than the * record's BIGINT columns hold - or null when the text is anything else. A number, or a BigInt past the whole numbers @@ -275,8 +449,7 @@ export function replyRequest(link, ticket, decisions, who) { function recordNumber(text) { if (!isText(text) || !RECORD_NUMBER.test(text)) return null; const value = BigInt(text); - if (value > RECORD_MAX) return null; - return value > Number.MAX_SAFE_INTEGER ? value : Number(value); + return value > RECORD_MAX ? null : exact(value); } /** The row a decision names in /questions/{id}/decide - or an AppException(400). */ @@ -296,10 +469,34 @@ export function streamCursor(lastEventId, since) { return value; } +/** + * The size of a page as a query names it: the default when it names none, else a whole number held between 1 and the + * most a page takes - or null when the text spells no whole number. + */ +export function pageSize(text, defaultValue, most) { + if (text === undefined || text === null || text === '') return defaultValue; + const number = wholeNumber(text); + return number === null ? null : Math.min(most, Math.max(1, number)); +} + +/** + * What GET /questions asks for - whether it pages back through the history, its cursor and its page size - or an + * AppException(400). before (empty: the newest page) and since (none or empty: the beginning) are numbers of the + * record, read as a row id and a stream's cursor are; limit is a whole number. + */ +export function listQuery(query) { + const paging = Object.hasOwn(query, 'before'); + const text = paging ? query.before : query.since; + const cursor = text ? recordNumber(text) : null; + const limit = pageSize(query.limit, LIST_LIMIT, LIST_LIMIT_MAX); + if (limit === null || (text && cursor === null)) throw new AppException(400, 'since, before and limit must be whole numbers'); + return [paging, paging ? cursor : (cursor ?? 0), limit]; +} + /** The replay's page: the rows whose sequence passed the cursor, oldest change first, and the cursor to continue from. */ export function pageSince(rows, since, limit) { - const changed = rows.filter((row) => row.seq > since).sort((a, b) => a.seq - b.seq).slice(0, limit); - return { rows: changed.map(publicRow), next: Math.max(since, ...changed.map((row) => row.seq)), more: changed.length >= limit }; + const changed = rows.filter((row) => row.seq > since).sort(bySeq).slice(0, limit); + return { rows: changed.map(publicRow), next: newestSeq(changed, since), more: changed.length >= limit }; } /** @@ -307,8 +504,9 @@ export function pageSince(rows, since, limit) { * first, and the cursor of the older page (the smallest sequence shown; null when nothing was). */ export function pageBefore(rows, before, limit) { - const older = rows.filter((row) => before === null || before === undefined || row.seq < before).sort((a, b) => b.seq - a.seq).slice(0, limit); - return { rows: older.map(publicRow), next: older.length > 0 ? Math.min(...older.map((row) => row.seq)) : null, more: older.length >= limit }; + const older = rows.filter((row) => before === null || before === undefined || row.seq < before).sort((a, b) => bySeq(b, a)).slice(0, limit); + // newest first, so the last row shown is the oldest: the cursor of the page before it + return { rows: older.map(publicRow), next: older.length > 0 ? older.at(-1).seq : null, more: older.length >= limit }; } // --- the readers ------------------------------------------------------------------------------ @@ -350,15 +548,15 @@ export class MemoryReader { } async since(seq, limit) { - return [...this.rows.values()].filter((r) => r.seq > seq).sort((a, b) => a.seq - b.seq).slice(0, limit); + return [...this.rows.values()].filter((r) => r.seq > seq).sort(bySeq).slice(0, limit); } async before(seq, limit) { - return [...this.rows.values()].filter((r) => seq === null || seq === undefined || r.seq < seq).sort((a, b) => b.seq - a.seq).slice(0, limit); + return [...this.rows.values()].filter((r) => seq === null || seq === undefined || r.seq < seq).sort((a, b) => bySeq(b, a)).slice(0, limit); } async latest() { - return Math.max(0, ...[...this.rows.values()].map((r) => r.seq)); + return newestSeq([...this.rows.values()], 0); } async counts() { @@ -419,7 +617,7 @@ const json = (value) => (typeof value === 'string' ? JSON.parse(value) : (value /** A row from a record as pg returns it (jsonb parsed, timestamptz as Dates, int8 as text). */ export function rowFromRecord(record) { return { - id: Number(record.id), seq: Number(record.seq), kind: String(record.kind), graph_id: String(record.graph_id), + id: exact(record.id), seq: exact(record.seq), kind: String(record.kind), graph_id: String(record.graph_id), correlation_id: String(record.correlation_id), turn: record.turn === null || record.turn === undefined ? null : Number(record.turn), ticket: record.ticket ?? null, link: record.link ?? null, description: String(record.description), summary: String(record.summary), details: record.details ?? null, message: json(record.message) ?? {}, @@ -495,7 +693,7 @@ export class PostgresReader { async latest() { const rows = await this.records(SQL_LATEST, []); - return rows.length > 0 && rows[0].latest !== null && rows[0].latest !== undefined ? Number(rows[0].latest) : 0; + return rows.length > 0 && rows[0].latest !== null && rows[0].latest !== undefined ? exact(rows[0].latest) : 0; } async counts() { @@ -631,7 +829,7 @@ export class Feed { return []; } if (rows.length > 0) { - this.cursor = Math.max(this.cursor, ...rows.map((row) => row.seq)); + this.cursor = newestSeq(rows, this.cursor); wakeups.publish(rows); } return rows; @@ -712,7 +910,9 @@ export async function questionHealth(headers) { counts = { error: failure(error) }; } return { - service: INTAKE_ROUTE, href: 'http://127.0.0.1', store: reader().name, rows: counts, feed: feed.cursor, + // the host renders this map and renders no BigInt: a cursor past the numbers a number holds is told in its digits + service: INTAKE_ROUTE, href: 'http://127.0.0.1', store: reader().name, rows: counts, + feed: typeof feed.cursor === 'bigint' ? String(feed.cursor) : feed.cursor, connected: wakeups.connected, auth: config.auth }; } @@ -730,7 +930,7 @@ function bearerOf(request) { const value = request.header('authorization') ?? ''; const at = value.indexOf(' '); if (at < 0) return null; - const token = value.slice(at + 1).trim(); + const token = trimmed(value.slice(at + 1)); return value.slice(0, at).toLowerCase() === 'bearer' && token ? token : null; } @@ -833,7 +1033,7 @@ const identityOf = (request) => ({ * A JSON reply as the UI reads it: serialized here, so a null stays a null (an advice's `state`, a silent engine's * `status` - the engines' renderer would omit them), under its content type. */ -const jsonReply = (status, body) => new EventEnvelope().setStatus(status).setHeader('content-type', 'application/json').setBody(JSON.stringify(body)); +const jsonReply = (status, body) => new EventEnvelope().setStatus(status).setHeader('content-type', 'application/json').setBody(toJson(body)); /** What the UI needs before it signs in: the auth mode, the title and, under oauth2, the issuer, the public client id, the scopes and the audience. */ export function uiConfig(config) { @@ -849,12 +1049,6 @@ export async function questionConfig() { return jsonReply(200, uiConfig(currentSettings())); } -/** A whole number from a query value, the default when absent; null when not a number. */ -function whole(value, defaultValue) { - if (value === null || value === undefined || value === '') return defaultValue; - return /^\d+$/.test(value) ? Number.parseInt(value, 10) : null; -} - /** * GET /questions?since=&limit=: every row that changed since the cursor, oldest change first, and the cursor to * continue from - the replay. GET /questions?before=&limit=: the history's older page, newest change first, and @@ -862,20 +1056,14 @@ function whole(value, defaultValue) { */ export async function questionList(_headers, body) { const request = new AsyncHttpRequest(body); - const paging = 'before' in request.queryParametersMap; - const limitRaw = whole(request.queryParameter('limit'), LIST_LIMIT); - const before = paging ? whole(request.queryParameter('before'), null) : null; - const since = paging ? 0 : whole(request.queryParameter('since'), 0); - if (limitRaw === null || since === null || (paging && request.queryParameter('before') && before === null)) { - throw new AppException(400, 'since, before and limit must be whole numbers'); - } - const limit = Math.min(LIST_LIMIT_MAX, Math.max(1, limitRaw)); + const asked = Object.fromEntries(Object.keys(request.queryParametersMap).map((name) => [name, request.queryParameter(name)])); + const [paging, cursor, limit] = listQuery(asked); let page; try { if (paging) { - page = { ...pageBefore(await reader().before(before, limit), null, limit), before }; + page = { ...pageBefore(await reader().before(cursor, limit), null, limit), before: cursor }; } else { - page = { ...pageSince(await reader().since(since, limit), since, limit), since }; + page = { ...pageSince(await reader().since(cursor, limit), cursor, limit), since: cursor }; } } catch (error) { log.warn(`The record could not be read - ${failure(error)}`); @@ -885,17 +1073,19 @@ export async function questionList(_headers, body) { } -/** The host's SSE keep-alive interval (event.stream.keep.alive, the engines' key; default 30s, 0 disables). */ +/** + * The host's SSE keep-alive interval (event.stream.keep.alive, the engines' key; default 30s, 0 disables), read as + * the host reads it - a duration, by the rule above. The setting is the host's, which refuses a value that is no + * duration when it starts, by the key's name, and this app's boot refuses one longer than a timer holds; a stream that + * meets either all the same looks for its device at the default. + */ export function keepAliveMs() { - const raw = String(appConfig().getProperty('event.stream.keep.alive', '30s') ?? '30s').trim().toLowerCase(); - if (['0', '0s', '0ms', '0m'].includes(raw)) return 0; - const match = /^(\d+)(ms|s|m)?$/.exec(raw); - if (!match) return 30_000; - return Number.parseInt(match[1], 10) * UNIT_MS[match[2] ?? 's']; + const ms = durationMs(appConfig().get(KEEP_ALIVE) ?? '30s'); + return ms === null || ms > MAX_TIMER_MS ? 30_000 : ms; } /** A changed row as the `question` event's data: serialized here, so a null stays a null. */ -const frame = (row) => JSON.stringify(publicRow(row)); +const frame = (row) => toJson(publicRow(row)); /** * One device's stream: the rows since its cursor first, then every change the feed finds, until the device leaves @@ -954,9 +1144,8 @@ export async function transcriptList(_headers, body) { if (parsed === null) throw new AppException(400, 'before must be an ISO-8601 time'); before = isoUtc(parsed); } - const limitRaw = whole(request.queryParameter('limit'), TRANSCRIPTS_LIMIT); - if (limitRaw === null) throw new AppException(400, 'limit must be a whole number'); - const limit = Math.min(TRANSCRIPTS_LIMIT_MAX, Math.max(1, limitRaw)); + const limit = pageSize(request.queryParameter('limit'), TRANSCRIPTS_LIMIT, TRANSCRIPTS_LIMIT_MAX); + if (limit === null) throw new AppException(400, 'limit must be a whole number'); let rows; try { rows = await reader().conversations(before, limit, request.queryParameter('correlation_id') || null, request.queryParameter('graph_id') || null); @@ -987,7 +1176,7 @@ async function forward(url, body, config) { const headers = { 'content-type': 'application/json', accept: 'application/json' }; if (config.replyToken) headers.authorization = `Bearer ${config.replyToken}`; try { - const response = await fetch(url, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(config.replyTimeoutMs) }); + const response = await fetch(url, { method: 'POST', headers, body: toJson(body), signal: AbortSignal.timeout(config.replyTimeoutMs) }); const textBody = await response.text(); let parsed; try { diff --git a/extensions/ask-person/README.md b/extensions/ask-person/README.md index c18486ec..23197f53 100644 --- a/extensions/ask-person/README.md +++ b/extensions/ask-person/README.md @@ -86,11 +86,34 @@ is in memory, and when the record's database does not answer at start (the write | `kind` | `approval` (a call needs `approved`) or `question` (an ask row) | `advice` | | `graph_id`, `description`, `correlation_id`, `summary` | required text | required text | | `node` | optional: the loop node that waits | optional | -| `turn` | required, a whole number: the turn that waits | optional: the turn it follows | +| `turn` | required, a whole number from 0 to 2147483647 (below): the turn that waits | optional: the turn it follows | | `calls` | required: the approval block as the loop returned it | refused | -| `ttl` | required: the suspend node's time to live (`30m`, `12h`, `2d`, or whole seconds) | refused | +| `ttl` | required: the suspend node's time to live, a duration (`30m`, `12h`, `2d`, or whole seconds; below) | refused | | `details` | - | optional text, the body | -| `requested_at` | optional ISO-8601; the default is now | optional | +| `requested_at` | optional: an ISO-8601 time with `Z` or an offset (below); the default is now | optional | + +A number is read by one rule, the same in both packs and in the LLM helper: a **whole number** is a JSON number with a +whole value (`2`, or `2.0`, which one runtime cannot tell from it) or text of the ASCII digits 0 to 9, at most +9007199254740991 - the largest whole number both runtimes hold exactly - with the white space both runtimes' own trim +takes ignored around it and none inside; a sign, an underscore, a point or an exponent in text and the digits of +another script spell none. `turn` is a whole number of at most 2147483647 - the largest the record's `turn` column, a +32-bit `INTEGER`, holds - and the event carries it as the number, however the message wrote it. `ttl` is a +**duration**, more than zero: a whole number of seconds, or a whole number and, right after it, one of `ms`, `s`, `m`, +`h`, `d`; a duration is held in milliseconds, at most 9007199254740991 of them, and a wait ends before the year 10000 - +an expiry that neither pack can write is refused (`ttl must end before the year 10000`). `graph_id` and +`correlation_id` name the wait in its ticket, whose payload keeps Unicode as it is, in UTF-8: text with a lone +surrogate - half of a character, which no ticket can carry - is refused, for an advice too (`graph_id must be text +without a lone surrogate`). + +A **time** is read by one reader, the same in both packs: a date `YYYY-MM-DD`, an upper-case `T`, a time `HH:MM` or +`HH:MM:SS` with a fraction of one to nine digits at most, then `Z` or an offset `+HH:MM` / `-HH:MM`, and nothing +before or after it - no white space, no time without an offset, no other spelling of ISO 8601. The date is one the +calendar has, the hour 0 to 23, the minute and the second 0 to 59, the offset at most 23:59, and the year 0001 to +9999, as written and in UTC; the instant is read to the millisecond, a longer fraction cut. The event keeps +`requested_at` as the message wrote it, and a time the extension writes - `expires_at`, a row's stamps - is UTC to the +millisecond (`2026-11-21T09:12:04.118Z`). A required text is missing when it is **blank**: nothing but the white space +of the number rule, the same 24 characters in both packs. U+FEFF, U+0085 and U+001C to U+001F are not among them - +one runtime's own trim takes them and the other's does not - so here they are characters of a name. The function cross-checks `graph_id` against the engine's `x-graph-id` header when one is present. It answers `{ticket, link, expires_at, delivered, recorded}` for a wait and `{delivered, recorded}` for an advice, where @@ -103,7 +126,8 @@ its id as `graph_id` and the stage as `turn`; the record has one shape for an AI `v1..`: the payload `{"g": graph_id, "c": correlation_id, "t": turn, "k": kind, "e": expiry}` as canonical JSON (keys sorted, no spaces, Unicode kept) and its HMAC-SHA256 under `ask.ticket.key`, both base64url without -padding. Opaque and clean - no question text, no business data, no person - and stateless: the reply endpoint verifies +padding; the expiry is `expires_at` in whole seconds from 1970-01-01T00:00:00Z, rounded down - before 1970 too. +Opaque and clean - no question text, no business data, no person - and stateless: the reply endpoint verifies it with the key alone, so every channel works without a store. `ask.ticket.previous-key` verifies the tickets issued before a rotation. A ticket is accepted as many times as it is presented: single use is the engine's at-most-once resume, and the second presentation gets `nothing waiting`. An expired ticket (410) is refused without a call to the @@ -111,7 +135,11 @@ engine; a malformed one or another version is a 400, one no key signs a 403. A t well-formed only with its three parts, the payload and the signature each canonical base64url without padding - the alphabet from start to end, no newline, no stray character, no bits left over in the last one - and the signature as long as the MAC, so any other spelling is malformed whatever it resembles and a 403 is a well-formed ticket that no -key signs. +key signs. The payload has one spelling too: under a valid signature the signed bytes are the canonical JSON of the +five fields and nothing else - a graph id and a correlation id that are not empty and hold no lone surrogate, a turn +from 0, a wait's kind, an expiry, the two numbers whole and no larger in size than 9007199254740991 - so a float for a +whole number, an escape the canonical form does not write, a key twice, a space, another order of the keys or bytes +that are not UTF-8 are malformed whoever signed them. ## The reply page and endpoint @@ -171,8 +199,14 @@ The writes are order-independent, so `question.audit` may run several instances upserted unless the row holds a newer `requested_at` (an older message landing late never overwrites a newer one), an advice is appended, and an answer applies while the row is open or when the engine accepted the decision - the first accepted decision stands, a late `nothing waiting` never overwrites it. The sweeper (`ask.audit.sweep`) marks open -waits past their expiry `expired`. A question joins its transcript (the LLM helper's `transcript` table) by -`correlation_id` and `graph_id`. Rows are never deleted here; `schema/purge.sql` is the installation's retention. +waits past their expiry `expired`. Two times are compared as the instants they name, in the memory store as in +PostgreSQL: a `requested_at` written at an offset or to the minute is in its place, whatever its text sorts as. A +question joins its transcript (the LLM helper's `transcript` table) by `correlation_id` and `graph_id`. Rows are never +deleted here; `schema/purge.sql` is the installation's retention. +`id` and `seq` are `BIGINT`: a row is told by the numbers it has - in the recorder's answer and in its log line - past +9007199254740991 too. `turn` is a 32-bit `INTEGER`, the reason a message's turn is at most 2147483647. `message`, +`decisions` and `outcome` are given to the store as compact JSON with every digit of a whole number past +9007199254740991 - one in a waiting call's input, for instance - in both packs. **The contract** (`QuestionStore` in `ask-person.mjs`) is published so a field keeps the record on another database: `record(event, now)` (a wait upserted or an advice appended, the row as it stands), `answer(key, decisions, who, state, @@ -204,11 +238,24 @@ record under the store's read role; it is the backend of the React UI maintained | `ask.audit.instances` | `1` | the recorder's workers; more is safe | | `ask.audit.timeout` | `5s` | how long a write may take before the hold or the reply goes on without it | +A setting is read by the rule of the message's numbers, whether a YAML file holds the value or a `${NAME:default}` +reference or a `-D` override gives it as text: `ask.audit.instances`, `.port` and `.timeout.ms` are whole numbers; the +timeouts and `ask.audit.sweep` are durations - seconds, or `ms`, `s`, `m`, `h`, `d` right after the number - more than +zero. A setting that sets a timer - a timeout, `ask.audit.sweep`, `.timeout.ms` - takes at most 2147483647 ms (about +24.8 days), the longest delay both runtimes' timers hold, and `.port` is 1 to 65535. A switch (`ask.enabled`, +`ask.audit.postgres.ssl`) is `true` or `false`, the boolean or the text in any letter case; no value and an empty one +are the default; any other value - `yes`, `on`, `1` - stops the boot by the key's name instead of being read as off. So +does a number or a duration that is not one. A setting's text - a key, a name, a URL, a mode - loses the white space of +the number rule around it and no other character. + ## Tests `test/ask-person.test.mjs` runs the shared vectors (`test/vectors/ask-person-vectors.json`: the ticket issued, verified, -tampered, expired and rotated; the message validated and the event built; the re-advice and the resume requests; the -outcomes; the row a message becomes, the state an answer leaves and the record's transitions) and drives the function +tampered, expired and rotated, and the payloads a key holder signed in another spelling; the message validated and the +event built; the re-advice and the resume requests; the outcomes; the row a message becomes, the state an answer leaves +and the record's transitions; a number, a duration and a switch as the one rule reads them; a time as the one reader +reads it, the white space around a text, and whole numbers past 9007199254740991 as the record is given them) and +drives the function and the page in-process: channels that take, refuse and miss the event, the record written before they are told; the reply endpoint against a fake engine, the answer recorded with who decided; the two auth modes with a signed token and the page's configuration; the PostgreSQL store's statements on a recording fake of the pool, and - gated on diff --git a/extensions/ask-person/ask-person.mjs b/extensions/ask-person/ask-person.mjs index eaa486b6..9aaaff60 100644 --- a/extensions/ask-person/ask-person.mjs +++ b/extensions/ask-person/ask-person.mjs @@ -97,8 +97,34 @@ export const AUDIT_INSTANCES = 'ask.audit.instances'; export const AUDIT_TIMEOUT = 'ask.audit.timeout'; export const MISSING_POSTGRES = 'ask.audit is postgres but the pg driver is not installed - npm install pg'; -const DURATION = /^(\d+)\s*(ms|s|m|h|d)?$/; +// how a number is read, the same in both packs and in every extension. The white space ignored around a number and a +// duration: the characters JavaScript's trim() and Python's str.strip() both take for white space, so neither pack +// accepts a character the other refuses +const SPACE = String.raw`[\t-\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]`; +// the same 24 characters where they stand around a text, to take off: a required text is blank and a setting's text is +// trimmed by these and no other. Each runtime's own trim takes a few more - this one's U+FEFF, the Python twin's +// U+001C to U+001F and U+0085 - which here are characters of a name. The lookbehind starts a match only at a run's +// first character, so the scan stays linear +const AROUND = new RegExp(`^${SPACE}+|(? typeof value === 'object' && value !== null && !Array.isArray(value); const isText = (value) => typeof value === 'string'; -const isWhole = (value) => typeof value === 'number' && Number.isInteger(value); +/** The entry of a name in a table - its own keys only, never a member every object inherits (constructor, toString). */ +const own = (table, name) => (Object.hasOwn(table, name) ? table[name] : undefined); /** The order sort() takes by default, written out: by UTF-16 code unit, never by locale - a ticket's payload is signed in it. */ function byCodeUnit(a, b) { @@ -134,45 +161,139 @@ function byCodeUnit(a, b) { return a > b ? 1 : 0; } +/** + * JSON as the record, the engine and a client read it, with a BigInt written as the number it is - every digit, where + * JSON.stringify alone refuses one. A whole number past Number.MAX_SAFE_INTEGER reaches this pack as a BigInt - in a + * waiting call's input, from an engine - and the Python twin writes such a number with every digit too. + */ +const toJson = (value) => JSON.stringify(value, (_key, item) => (typeof item === 'bigint' ? JSON.rawJSON(String(item)) : item)); + // --- durations and times ---------------------------------------------------------------------- -/** Milliseconds from a whole number of seconds or a duration such as 500ms, 30m, 12h or 2d; null otherwise. */ +/** + * What a number is read from: a string as written, or the digits of a JSON number with a whole value - an integer, + * which is all this pack sees of a float such as 16000.0. Null for anything else: a boolean, a fraction, a number + * beyond Number.MAX_SAFE_INTEGER. + */ +function numberText(value) { + if (isText(value)) return value; + return typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : null; +} + +/** The whole number a run of ASCII digits spells, or null above Number.MAX_SAFE_INTEGER. */ +function digits(run) { + const number = Number(run); + return Number.isSafeInteger(number) ? number : null; +} + +/** + * The whole number a value spells - a JSON number with a whole value, or ASCII digits with white space around them at + * most - up to Number.MAX_SAFE_INTEGER; null when it spells none: a sign, an underscore, a point or an exponent in + * text, a digit of another script. + */ +export function wholeNumber(value) { + const match = WHOLE.exec(numberText(value) ?? ''); + return match ? digits(match[1]) : null; +} + +/** + * Milliseconds from a whole number of seconds or a duration such as 500ms, 30m, 12h or 2d - such a number and, right + * after it, one of ms, s, m, h, d - up to Number.MAX_SAFE_INTEGER milliseconds; null when the value is neither. + */ export function durationMs(value) { - if (typeof value === 'boolean') return null; - if (typeof value === 'number') return Number.isInteger(value) && value >= 0 ? value * 1000 : null; - if (!isText(value)) return null; - const match = DURATION.exec(value.trim()); - if (!match) return null; - return Number.parseInt(match[1], 10) * UNIT_MS[match[2] ?? 's']; + const match = DURATION.exec(numberText(value) ?? ''); + const count = match ? digits(match[1]) : null; + if (count === null) return null; + const ms = count * UNIT_MS[match[2] ?? 's']; + return Number.isSafeInteger(ms) ? ms : null; } -/** An ISO-8601 time with an offset or Z, as a Date; null when it is not one. */ +/** + * What a switch is set to: the boolean, or the text true or false in any letter case; no value and an empty one are + * the default. Null for any other value - it is never read as off. + */ +export function switchValue(value, defaultValue) { + if (value === undefined || value === null || value === '') return defaultValue; + if (typeof value === 'boolean') return value; + const lowered = isText(value) ? value.toLowerCase() : ''; + if (lowered !== 'true' && lowered !== 'false') return null; + return lowered === 'true'; +} + +/** + * A text without the white space around it - the 24 characters of the number rule, the same in both packs, where + * trim() alone takes a few more. A blank text leaves nothing. + */ +const trimmed = (value) => value.replace(AROUND, ''); + +/** + * An ISO-8601 time with an offset or Z, as a Date; null when it is not one. One reader in both packs: a date + * YYYY-MM-DD, an upper-case T, a time HH:MM or HH:MM:SS - the second with a fraction of one to nine digits at most - + * then Z or +HH:MM / -HH:MM, and nothing before or after it; a date the calendar has, in the years 0001 to 9999 as + * written and in UTC. The instant is read to the millisecond: a longer fraction is cut, never rounded. + */ export function parseIso(text) { - const candidate = text.trim(); - if (!/^\d{4}-\d{2}-\d{2}/.test(candidate)) return null; - const ms = Date.parse(candidate); - return Number.isNaN(ms) ? null : new Date(ms); + const match = ISO_TIME.exec(text); + if (match === null) return null; + const [year, month, day, hour, minute, second, offsetHours, offsetMinutes] = [1, 2, 3, 4, 5, 6, 9, 10].map((at) => Number(match[at] ?? 0)); + if (year < 1 || hour > 23 || minute > 59 || second > 59 || offsetHours > 23 || offsetMinutes > 59) return null; + // the date as written, at midnight UTC: setUTCFullYear takes a year before 100 as it is, and a date the calendar + // does not have comes back as another + const written = new Date(0); + written.setUTCFullYear(year, month - 1, day); + if (written.getUTCFullYear() !== year || written.getUTCMonth() !== month - 1 || written.getUTCDate() !== day) return null; + const millisecond = Number((match[7] ?? '').padEnd(3, '0').slice(0, 3)); + const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes); + const ms = written.getTime() + ((hour * 60 + minute - offset) * 60 + second) * 1000 + millisecond; + return ms < MIN_TIME_MS || ms > MAX_TIME_MS ? null : new Date(ms); +} + +/** + * True when a time is before another: by their instants, as the reference store compares two stamps - so a time + * written at an offset or to the minute is in its place - and by their texts when one of them is no time. + */ +function earlier(left, right) { + const first = parseIso(left); + const second = parseIso(right); + return first === null || second === null ? left < right : first.getTime() < second.getTime(); +} + +/** + * When a wait expires - requested_at plus its ttl - or null when that is not before the year 10000: a time neither + * pack can write. + */ +function expiryOf(requestedAt, ttlMs) { + const ms = (parseIso(requestedAt) ?? new Date()).getTime() + ttlMs; + return ms > MAX_TIME_MS ? null : new Date(ms); } // --- configuration ---------------------------------------------------------------------------- function text(config, key, defaultValue = '') { const value = config.get(key); - return value === undefined || value === null ? defaultValue : String(value).trim(); + return value === undefined || value === null ? defaultValue : trimmed(String(value)); } +/** + * A switch of the configuration, or an AskError naming the key: a value that is neither true nor false stops the boot + * instead of leaving the switch off. + */ function flag(config, key, defaultValue) { - const value = config.get(key); - if (value === undefined || value === null) return defaultValue; - if (typeof value === 'boolean') return value; - return ['true', 'yes', 'on', '1'].includes(String(value).trim().toLowerCase()); + const value = switchValue(config.get(key), defaultValue); + if (value === null) throw new AskError(`${key} must be true or false`); + return value; } /** A list of names from a YAML list or a comma-separated text (a -D override). */ function names(value) { if (value === undefined || value === null) return []; const items = Array.isArray(value) ? value : String(value).split(','); - return items.map((item) => String(item).trim()).filter(Boolean); + return items.map((item) => trimmed(String(item))).filter(Boolean); +} + +/** Set a name of the configuration as a table's own key - __proto__ included, which a plain assignment would lose. */ +function setOwn(table, name, value) { + Object.defineProperty(table, name, { value, enumerable: true, writable: true, configurable: true }); } /** The mapping a YAML list of {keyName, valueName} maps gives. */ @@ -182,7 +303,7 @@ function pairsOfList(items, keyName, valueName, setting) { if (!isMap(item) || !item[keyName] || !item[valueName]) { throw new AskError(`${setting} entries need ${keyName} and ${valueName}`); } - result[String(item[keyName]).trim()] = String(item[valueName]).trim(); + setOwn(result, trimmed(String(item[keyName])), trimmed(String(item[valueName]))); } return result; } @@ -191,12 +312,12 @@ function pairsOfList(items, keyName, valueName, setting) { function pairsOfText(given, keyName, valueName, setting) { const result = {}; for (const part of given.split(',')) { - if (!part.trim()) continue; + if (!trimmed(part)) continue; const at = part.indexOf('='); - const key = at < 0 ? '' : part.slice(0, at).trim(); - const target = at < 0 ? '' : part.slice(at + 1).trim(); + const key = at < 0 ? '' : trimmed(part.slice(0, at)); + const target = at < 0 ? '' : trimmed(part.slice(at + 1)); if (!key || !target) throw new AskError(`${setting} takes ${keyName}=${valueName} pairs`); - result[key] = target; + setOwn(result, key, target); } return result; } @@ -208,19 +329,23 @@ function pairs(value, keyName, valueName, setting) { return pairsOfText(String(value), keyName, valueName, setting); } +/** A setting that sets a timer: a duration of more than nothing and of no more than a timer holds. */ function timeout(config, key, defaultValue) { const value = config.get(key); const ms = durationMs(value === undefined || value === null ? defaultValue : value); - if (ms === null || ms <= 0) throw new AskError(`${key} must be ${DURATION_RULE} > 0`); + if (ms === null || ms <= 0 || ms > MAX_TIMER_MS) throw new AskError(`${key} must be ${DURATION_RULE} > 0`); return ms; } -/** A whole number >= minimum (a count of instances, a number of milliseconds). */ -function whole(config, key, defaultValue, minimum) { +/** + * A whole number >= minimum (a count of instances, a number of milliseconds) and, for a key that sets a timer, of no + * more than a timer holds. + */ +function whole(config, key, defaultValue, minimum, maximum = Number.MAX_SAFE_INTEGER) { const value = config.get(key); - const given = String(value === undefined || value === null ? defaultValue : value).trim(); - if (!/^\d+$/.test(given) || Number.parseInt(given, 10) < minimum) throw new AskError(`${key} must be a whole number >= ${minimum}`); - return Number.parseInt(given, 10); + const number = wholeNumber(value === undefined || value === null ? defaultValue : value); + if (number === null || number < minimum || number > maximum) throw new AskError(`${key} must be a whole number >= ${minimum}`); + return number; } /** @@ -228,12 +353,12 @@ function whole(config, key, defaultValue, minimum) { * ask.audit.postgres. prefix; the password a reference, never logged. */ function auditPostgres(config, timeoutMs) { - const portText = text(config, `${AUDIT_POSTGRES_PREFIX}port`, '5432'); - if (!/^\d+$/.test(portText) || Number.parseInt(portText, 10) <= 0) throw new AskError(`${AUDIT_POSTGRES_PREFIX}port must be a port number`); - const ssl = text(config, `${AUDIT_POSTGRES_PREFIX}ssl`, 'true').toLowerCase() !== 'false'; + const port = wholeNumber(config.get(`${AUDIT_POSTGRES_PREFIX}port`) ?? 5432); + if (port === null || port < 1 || port > MAX_PORT) throw new AskError(`${AUDIT_POSTGRES_PREFIX}port must be a port number`); + const ssl = flag(config, `${AUDIT_POSTGRES_PREFIX}ssl`, true); return { host: text(config, `${AUDIT_POSTGRES_PREFIX}host`, '127.0.0.1'), - port: Number.parseInt(portText, 10), + port, database: text(config, `${AUDIT_POSTGRES_PREFIX}database`, 'mercury'), user: text(config, `${AUDIT_POSTGRES_PREFIX}username`) || undefined, password: text(config, `${AUDIT_POSTGRES_PREFIX}password`) || undefined, @@ -256,7 +381,7 @@ export function loadSettings(config) { const replyUrl = text(config, REPLY_URL).replace(TRAILING_SLASHES, ''); const auth = text(config, REPLY_AUTH, 'none').toLowerCase(); const audit = text(config, AUDIT, 'memory').toLowerCase(); - const postgresTimeoutMs = whole(config, `${AUDIT_POSTGRES_PREFIX}timeout.ms`, 5000, 1); + const postgresTimeoutMs = whole(config, `${AUDIT_POSTGRES_PREFIX}timeout.ms`, 5000, 1, MAX_TIMER_MS); const settings = { enabled, channels: names(config.get(CHANNELS)), @@ -349,19 +474,47 @@ export function issueTicket(payload, key) { return `${TICKET_VERSION}.${b64u(encoded)}.${b64u(mac(encoded, key))}`; } +/** + * True for text a ticket's payload can carry: not empty, and every character one UTF-8 can write - a lone surrogate is + * half of a character, and the canonical form keeps Unicode as it is. + */ +const carried = (text) => isText(text) && text.length > 0 && text.isWellFormed(); + +/** + * A wait's payload: the five fields and no other - a graph id and a correlation id a ticket can carry, a turn from 0, a + * wait's kind and an expiry, the numbers integers both packs hold. + */ function payloadIsValid(payload) { if (!isMap(payload)) return false; const keys = Object.keys(payload).sort(byCodeUnit).join(','); if (keys !== 'c,e,g,k,t') return false; - return isText(payload.g) && payload.g.length > 0 && isText(payload.c) && payload.c.length > 0 - && isWhole(payload.t) && payload.t >= 0 && WAIT_KINDS.includes(payload.k) && isWhole(payload.e); + return carried(payload.g) && carried(payload.c) && Number.isSafeInteger(payload.t) && payload.t >= 0 + && WAIT_KINDS.includes(payload.k) && Number.isSafeInteger(payload.e); +} + +/** + * The payload a signed part spells, or null when it spells none: the bytes are the canonical JSON of a wait's payload + * and nothing else - a payload has one spelling, as the ticket's parts have, so a float for a whole number, a key + * twice, a space, an escape the canonical form does not write or bytes that are not UTF-8 are refused whoever signed + * them. + */ +function payloadOf(payloadBytes) { + let payload; + try { + payload = JSON.parse(payloadBytes.toString('utf8')); + } catch { + return null; + } + if (!payloadIsValid(payload)) return null; + return Buffer.from(canonicalJson(payload), 'utf8').equals(payloadBytes) ? payload : null; } /** * The payload of a ticket this process issued, or a TicketError: 400 when the ticket is malformed or of another * version, 403 when no key signs it, 410 when it has expired. A ticket is well-formed when it has the three parts, its * payload and its signature are canonical base64url without padding and the signature is as long as the MAC; one that - * is not is malformed whatever it resembles, so a 403 is a well-formed ticket that no key signs. + * is not is malformed whatever it resembles, so a 403 is a well-formed ticket that no key signs. The payload under a + * valid signature is the canonical JSON of a wait's five fields or it is malformed too. */ export function verifyTicket(ticket, keys, nowSeconds) { const parts = String(ticket).split('.'); @@ -376,24 +529,23 @@ export function verifyTicket(ticket, keys, nowSeconds) { return expected.length === given.length && timingSafeEqual(expected, given); }); if (!signed) throw new TicketError(403, 'Ticket signature is invalid'); - let payload; - try { - payload = JSON.parse(payloadBytes.toString('utf8')); - } catch { - throw new TicketError(400, 'Ticket is malformed'); - } - if (!payloadIsValid(payload)) throw new TicketError(400, 'Ticket is malformed'); + const payload = payloadOf(payloadBytes); + if (payload === null) throw new TicketError(400, 'Ticket is malformed'); if (payload.e < nowSeconds) throw new TicketError(410, 'Ticket expired'); return payload; } // --- the message and the event ---------------------------------------------------------------- +/** + * A text the message must carry: blank - nothing but the white space of the number rule - is as good as missing, by + * the same characters in both packs. + */ function requiredText(body, name) { const value = body[name]; if (value === undefined || value === null) throw new AppException(400, `${name} is required`); if (!isText(value)) throw new AppException(400, `${name} must be text`); - if (!value.trim()) throw new AppException(400, `${name} is required`); + if (!trimmed(value)) throw new AppException(400, `${name} is required`); return value; } @@ -404,13 +556,40 @@ function optionalText(body, name) { return value; } +/** + * A required text that names the wait in its ticket - the graph id, the correlation id - or an AppException(400): a + * lone surrogate is half of a character, which no ticket can carry. + */ +function ticketText(body, name) { + const value = requiredText(body, name); + if (!carried(value)) throw new AppException(400, `${name} must be text without a lone surrogate`); + return value; +} + function turnOf(value, required) { if (value === undefined || value === null) { if (required) throw new AppException(400, 'turn is required for an approval or a question'); return null; } - if (!isWhole(value) || value < 0) throw new AppException(400, 'turn must be a whole number >= 0'); - return value; + const turn = wholeNumber(value); + // a turn the record's column cannot hold is no turn + if (turn === null || turn > MAX_TURN) throw new AppException(400, 'turn must be a whole number >= 0'); + return turn; +} + +// a wait whose expiry - requested_at plus ttl - is a time neither pack can write +const TTL_ENDS_TOO_LATE = 'ttl must end before the year 10000'; + +/** + * A wait's ttl in milliseconds - a duration of more than nothing, which ends before the year 10000 - or an + * AppException(400) naming the rule. + */ +function ttlMsOf(body, requestedAt) { + if (!('ttl' in body)) throw new AppException(400, 'ttl is required for an approval or a question'); + const ttlMs = durationMs(body.ttl); + if (ttlMs === null || ttlMs <= 0) throw new AppException(400, `ttl must be ${DURATION_RULE} > 0`); + if (expiryOf(requestedAt, ttlMs) === null) throw new AppException(400, TTL_ENDS_TOO_LATE); + return ttlMs; } /** The message a hold node sends, checked in a fixed order - the same in the Python twin - or an AppException(400). */ @@ -418,9 +597,9 @@ export function validateMessage(body) { if (!isMap(body)) throw new AppException(400, 'person.ask takes a map'); const kind = body.kind; if (!KINDS.includes(kind)) throw new AppException(400, 'kind must be one of approval, question, advice'); - const graphId = requiredText(body, 'graph_id'); + const graphId = ticketText(body, 'graph_id'); const description = requiredText(body, 'description'); - const correlationId = requiredText(body, 'correlation_id'); + const correlationId = ticketText(body, 'correlation_id'); const summary = requiredText(body, 'summary'); const node = optionalText(body, 'node'); const requestedAtText = optionalText(body, 'requested_at'); @@ -441,9 +620,7 @@ export function validateMessage(body) { || !calls.every((call) => isMap(call) && isText(call.id) && call.id.length > 0)) { throw new AppException(400, 'calls must be a non-empty list of the waiting calls, each with an id'); } - if (!('ttl' in body)) throw new AppException(400, 'ttl is required for an approval or a question'); - const ttlMs = durationMs(body.ttl); - if (ttlMs === null || ttlMs <= 0) throw new AppException(400, `ttl must be ${DURATION_RULE} > 0`); + const ttlMs = ttlMsOf(body, requestedAt); return { kind, graph_id: graphId, description, correlation_id: correlationId, summary, requested_at: requestedAt, node, turn, calls: calls.map((call) => ({ ...call })), ttl: body.ttl, ttl_ms: ttlMs, details: null @@ -451,6 +628,7 @@ export function validateMessage(body) { } export function ticketPayload(message, expiresAt) { + // the expiry in whole seconds, the floor - before 1970 too return { g: message.graph_id, c: message.correlation_id, t: message.turn, k: message.kind, e: Math.floor(expiresAt.getTime() / 1000) }; } @@ -465,8 +643,8 @@ export function buildEvent(message, key, replyUrl) { if (message.ttl !== null) event.ttl = message.ttl; event.requested_at = message.requested_at; if (WAIT_KINDS.includes(message.kind) && message.ttl_ms !== null) { - const requested = parseIso(message.requested_at) ?? new Date(); - const expiresAt = new Date(requested.getTime() + message.ttl_ms); + const expiresAt = expiryOf(message.requested_at, message.ttl_ms); + if (expiresAt === null) throw new AppException(400, TTL_ENDS_TOO_LATE); // a message validateMessage did not see const ticket = issueTicket(ticketPayload(message, expiresAt), key); event.expires_at = isoUtc(expiresAt); event.ticket = ticket; @@ -478,7 +656,7 @@ export function buildEvent(message, key, replyUrl) { // --- the resume and the outcome --------------------------------------------------------------- function entryOf(payload, graphs) { - const entry = graphs[String(payload.g)]; + const entry = own(graphs, String(payload.g)); if (!entry) throw new ReplyError(404, `graph ${payload.g} is not configured for replies`); return entry; } @@ -629,7 +807,7 @@ export class MemoryQuestionStore { const existing = existingId === undefined ? undefined : this.rows.get(existingId); let row; if (existing) { - if (fields.requested_at < existing.requested_at) return existing; // an older message landing late never overwrites a newer row + if (earlier(fields.requested_at, existing.requested_at)) return existing; // an older message landing late never overwrites a newer row row = { ...existing, ...fields, seq: this.bump() }; } else { this.nextId += 1; @@ -653,7 +831,7 @@ export class MemoryQuestionStore { async expire(now) { const changed = []; for (const row of this.rows.values()) { - if (row.state === 'open' && WAIT_KINDS.includes(row.kind) && row.expires_at && row.expires_at < now) { + if (row.state === 'open' && WAIT_KINDS.includes(row.kind) && row.expires_at && earlier(row.expires_at, now)) { const updated = { ...row, seq: this.bump(), state: 'expired', updated_at: now }; this.rows.set(updated.id, updated); changed.push(updated); @@ -701,8 +879,6 @@ export const SQL_EXPIRE = "UPDATE question SET seq = nextval('question_seq'), st export const SQL_SINCE = `SELECT ${COLUMNS} FROM question WHERE seq > $1 ORDER BY seq LIMIT $2`; export const SQL_COUNTS = 'SELECT COALESCE(state, kind) AS label, count(*) FROM question GROUP BY COALESCE(state, kind)'; -const compact = (value) => JSON.stringify(value); - function stamp(value) { if (value === null || value === undefined) return null; if (value instanceof Date) return isoUtc(value); @@ -712,10 +888,19 @@ function stamp(value) { const json = (value) => (typeof value === 'string' ? JSON.parse(value) : (value ?? null)); +/** + * A number of the record as the database gives it - a BIGINT column arrives as text - held exactly: a number, or a + * BigInt past the whole numbers a number holds exactly, so the row told of is the row stored. + */ +function exact(value) { + const big = BigInt(value); + return big > Number.MAX_SAFE_INTEGER || big < Number.MIN_SAFE_INTEGER ? big : Number(big); +} + /** A row from a record as pg returns it (jsonb parsed, timestamptz as Dates, int8 as text). */ export function rowFromRecord(record) { return { - id: Number(record.id), seq: Number(record.seq), kind: String(record.kind), graph_id: String(record.graph_id), + id: exact(record.id), seq: exact(record.seq), kind: String(record.kind), graph_id: String(record.graph_id), correlation_id: String(record.correlation_id), turn: record.turn === null || record.turn === undefined ? null : Number(record.turn), ticket: record.ticket ?? null, link: record.link ?? null, description: String(record.description), summary: String(record.summary), details: record.details ?? null, message: json(record.message) ?? {}, @@ -760,18 +945,18 @@ export class PostgresQuestionStore { let row; if (key !== null) { row = await this.one(SQL_RECORD_WAIT, [f.ticket, f.graph_id, f.correlation_id, f.turn, f.kind, f.description, f.summary, - compact(f.message), f.link, f.requested_at, f.expires_at, now]); + toJson(f.message), f.link, f.requested_at, f.expires_at, now]); if (!row) row = await this.one(SQL_WAIT, key); // the guard kept a newer row: answer with it as it stands } else { row = await this.one(SQL_RECORD_ADVICE, [f.graph_id, f.correlation_id, f.turn, f.description, f.summary, f.details, - compact(f.message), f.requested_at, now]); + toJson(f.message), f.requested_at, now]); } if (!row) throw new AppException(500, 'the question record returned no row'); return row; } async answer(key, decisions, who, state, outcome, now) { - const row = await this.one(SQL_ANSWER, [state, compact(decisions), compact(outcome), who, now, now, key[0], key[1], key[2], state]); + const row = await this.one(SQL_ANSWER, [state, toJson(decisions), toJson(outcome), who, now, now, key[0], key[1], key[2], state]); // no row: the guard kept a row another device decided first (or no wait was recorded) - as stored return row ?? await this.one(SQL_WAIT, key); } @@ -898,7 +1083,7 @@ export async function record(event, config) { /** Send the event to every channel route, in parallel and best effort; a failure is logged by type, never by content. */ export async function deliver(event, config) { const one = async (route) => { - const endpoint = config.channelEndpoints[route]; + const endpoint = own(config.channelEndpoints, route); try { const reply = await po().request(route, { ...event }, { timeoutMs: config.channelTimeoutMs, endpoint }); const ok = reply.getStatus() < 400; @@ -970,7 +1155,7 @@ function bearerOf(request) { const at = value.indexOf(' '); if (at < 0) return null; const scheme = value.slice(0, at).toLowerCase(); - const token = value.slice(at + 1).trim(); + const token = trimmed(value.slice(at + 1)); return scheme === 'bearer' && token ? token : null; } @@ -1241,7 +1426,7 @@ function page(title, body, script = '') { */ const textReply = (status, contentType, text) => new EventEnvelope().setStatus(status).setHeader('content-type', contentType).setBody(text); const htmlReply = (status, html) => textReply(status, 'text/html', html); -const jsonReply = (status, body) => textReply(status, 'application/json', JSON.stringify(body)); +const jsonReply = (status, body) => textReply(status, 'application/json', toJson(body)); /** A ticket that cannot be used, as the page's script reads it: `expired` for 410, else `error`. */ const ticketRefusal = (error) => jsonReply(error.status, { type: error.status === 410 ? 'expired' : 'error', message: error.message }); @@ -1284,8 +1469,9 @@ async function engine(request, timeoutMs) { const response = await fetch(request.url, { method: 'POST', headers: { ...request.headers, 'content-type': 'application/json', accept: 'application/json' }, - body: JSON.stringify(request.body), - signal: AbortSignal.timeout(timeoutMs + 1000) + body: toJson(request.body), + // a second more than the engine's own allowance, and never more than a timer holds + signal: AbortSignal.timeout(Math.min(timeoutMs + 1000, MAX_TIMER_MS)) }); return mapOutcome(response.status, await response.text(), null); } catch (error) { @@ -1313,7 +1499,7 @@ export async function askPage(_headers, body) { if (!(error instanceof TicketError)) throw error; return notice(error.status, error.status === 410 ? 'This wait has expired' : 'This link cannot be used', error.message); } - if (!config.graphs[String(payload.g)]) { + if (!own(config.graphs, String(payload.g))) { return notice(404, 'This graph is not configured', `graph ${payload.g} is not configured for replies`); } return htmlReply(200, shellPage(ticket, payload)); diff --git a/test/agent-question.test.mjs b/test/agent-question.test.mjs index 3fc76432..bdeec67e 100644 --- a/test/agent-question.test.mjs +++ b/test/agent-question.test.mjs @@ -3,7 +3,10 @@ * * The shared contract file test/vectors/agent-question-vectors.json (byte-identical in mercury-python) pins the pure * half: the event the intake accepts or refuses, the request the automated click sends, the pages the replay and the - * history read, and the row id and the cursor a request names - digits the record holds, or the 400. The tests after + * history read, the row id and the cursor a request names - digits the record holds, or the 400 - what GET /questions + * asks for, a page size, rows past the whole numbers a double holds told by the numbers they have, a number, a + * duration and a switch read by the one rule of both packs, a time read by their one reader and the white space + * around a text. The tests after * the vector runs drive the app in-process as the reader of the question record the main * flow keeps: the intake waking the feed, the replay and the history pages and the stream over the host, the * transcripts browsed, a decision forwarded to a fake reply endpoint under the app's bearer and the row re-read as the @@ -17,12 +20,14 @@ import { readFileSync } from 'node:fs'; import http from 'node:http'; import { fileURLToPath } from 'node:url'; import { after, before, test } from 'node:test'; -import { AppException, appConfig, defaultRegistry, EventApiServer, FunctionRegistry, isoUtc, Platform, PostOffice } from 'mercury-composable'; +import { + AppException, appConfig, AsyncHttpRequest, defaultRegistry, EventApiServer, FunctionRegistry, isoUtc, Platform, PostOffice +} from 'mercury-composable'; import * as aq from '../extensions/agent-question/agent-question.mjs'; const VECTORS_FILE = new URL('./vectors/agent-question-vectors.json', import.meta.url); // the Python twin runs the same file: change it in both packs or in neither -const VECTORS_SHA256 = 'ad693f2b6924735e0590a67e0799caf739a51e233cd9c3dd261d100a4147c030'; +const VECTORS_SHA256 = '75b8b12bbb1c454fff4e4bdffad7df20563a6223062a1c0e995250033535b3e8'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const RECORD_SCHEMA = new URL('../extensions/ask-person/schema/postgres.sql', import.meta.url); const PUBLIC = fileURLToPath(new URL('../extensions/agent-question/resources/public', import.meta.url)); @@ -100,8 +105,9 @@ const getJson = async (url, headers = {}) => { const response = await fetch(url, test('the vector file is the one the Python twin runs', () => { assert.equal(createHash('sha256').update(readFileSync(VECTORS_FILE)).digest('hex'), VECTORS_SHA256); assert.equal(VECTORS.contract, 'agent-question'); - assert.equal(VECTORS.version, 4); - for (const section of ['intake_cases', 'click_cases', 'feed_cases', 'row_id_cases', 'cursor_cases']) { + assert.equal(VECTORS.version, 6); + for (const section of ['intake_cases', 'click_cases', 'feed_cases', 'row_id_cases', 'cursor_cases', 'number_cases', 'switch_cases', + 'list_cases', 'page_size_cases', 'exact_cases', 'time_cases', 'text_cases']) { assert.ok(VECTORS[section].length > 0, section); } }); @@ -170,17 +176,195 @@ for (const c of VECTORS.cursor_cases) { }); } +// a value read as a whole number and as a duration: the one rule of both packs and of every extension +for (const c of VECTORS.number_cases) { + test(`number: ${c.name}`, () => { + assert.equal(aq.wholeNumber(c.value), c.whole); + assert.equal(aq.durationMs(c.value), c.duration_ms); + }); +} + +// a switch: true or false, the default for no value and an empty one, and null - refused - for any other +for (const c of VECTORS.switch_cases) { + test(`switch: ${c.name}`, () => { + const [on, off] = c.switch === 'default' ? [true, false] : [c.switch, c.switch]; + assert.equal(aq.switchValue(c.value, true), on); + assert.equal(aq.switchValue(c.value, false), off); + if (c.value === null) assert.equal(aq.switchValue(undefined, true), true, 'a key that is not set is no value'); + }); +} + +// what GET /questions asks for, from its parameters as the request wrote them +for (const c of VECTORS.list_cases) { + test(`list: ${c.name}`, () => { + if ('paging' in c) { + const [paging, cursor, limit] = aq.listQuery(c.query); + assert.deepEqual({ paging, cursor: cursor === null ? null : String(cursor), limit }, { paging: c.paging, cursor: c.cursor, limit: c.limit }); + } else { + assert.throws(() => aq.listQuery(c.query), (e) => e instanceof AppException && e.status === c.status && e.message === c.error); + } + }); +} + +for (const c of VECTORS.page_size_cases) { + test(`page size: ${c.name}`, () => assert.equal(aq.pageSize(c.limit, c.default, c.most), c.size)); +} + +/** A reader that keeps the instant the transcripts were asked for, and holds no conversation. */ +class RecordingReader extends aq.MemoryReader { + asked = []; + + async conversations(before) { + this.asked.push(before); + return []; + } +} + +// a time a caller supplies, by the one reader of both packs: the instant to the millisecond and the text written back +// for it - which is what the transcripts' before hands the store - or no time at all, the 400 +for (const c of VECTORS.time_cases) { + test(`time: ${c.name}`, async () => { + const moment = aq.parseIso(c.text); + const stamped = aq.rowFromRecord(record({ requested_at: c.text })).requested_at; + const reader = new RecordingReader(); + aq.reset(reader); + const request = new AsyncHttpRequest().setQueryParameter('before', c.text).toMap(); + try { + if (c.ms === null) { + assert.equal(moment, null); + assert.equal(stamped, c.text, 'a stamp the store gave as text is kept as it came'); + } else { + assert.equal(moment.getTime(), c.ms); + assert.equal(isoUtc(moment), c.stamp); + assert.equal(stamped, c.stamp); + } + if (c.ms === null && c.text) { + await assert.rejects(aq.transcriptList({}, request), (e) => e instanceof AppException && e.status === 400 && e.message === 'before must be an ISO-8601 time'); + assert.deepEqual(reader.asked, []); + } else { + // the store is asked by the text written for the instant; an empty before is no cursor + const reply = await aq.transcriptList({}, request); + assert.equal(reply.getStatus(), 200); + assert.deepEqual(reader.asked, [c.stamp]); + } + } finally { + aq.reset(); + } + }); +} + +// the white space around a text - the 24 characters of the number rule and no other - and what it decides: a setting's +// text loses it, and a required text of nothing else is missing, in both packs alike +for (const c of VECTORS.text_cases) { + test(`text: ${c.name}`, () => { + const clear = configure({ ...BASE, [aq.PAGE_TITLE]: c.text }); + try { + assert.equal(clear.settings.pageTitle, c.trimmed); + } finally { + clear(); + } + const event = waitEvent({ summary: c.text }); + if (c.blank) { + assert.throws(() => aq.validateEvent(event), (e) => e instanceof AppException && e.status === 400 && e.message === 'summary is required'); + } else { + assert.equal(aq.validateEvent(event).summary, c.text); + } + }); +} + +test('the white space of a number and of a text is the same 24 characters', () => { + // the white space around a number and the white space a blank text is made of are one set: no character of the basic + // plane is the one and a character of a name, or the reverse + const event = waitEvent(); + const blank = (text) => { + try { + aq.validateEvent({ ...event, summary: text }); + return false; + } catch (error) { + if (!(error instanceof AppException)) throw error; + return true; + } + }; + const units = Array.from({ length: 0x10000 }, (_unused, code) => String.fromCharCode(code)); + const aroundANumber = units.filter((ch) => aq.wholeNumber(`${ch}5${ch}`) === 5); + assert.deepEqual(units.filter(blank), aroundANumber); + assert.equal(aroundANumber.length, 24); +}); + +/** The rows of an exact case as the database gives them - pg reads a BIGINT column as text. */ +const exactRows = (c) => c.rows.map((s) => aq.rowFromRecord({ + id: s.id, seq: s.seq, ticket: s.kind === 'advice' ? null : `t-${s.id}`, graph_id: 'order-assistant', correlation_id: `case-${s.id}`, + turn: 2, kind: s.kind, description: 'Customer-support assistant', summary: 'A refund waits', details: null, message: { kind: s.kind, calls: CALLS }, + link: null, state: s.state, requested_at: new Date('2026-11-19T09:12:05.123Z'), expires_at: null, updated_at: new Date('2026-11-19T09:12:05.123Z'), + answered_at: null, answered_by: null, decisions: null, outcome: null +})); + +/** A page as a query of an exact case names it: every number as text. */ +const shownAs = (page) => ({ ids: page.rows.map((r) => String(r.id)), seqs: page.rows.map((r) => String(r.seq)), + next: page.next === null ? null : String(page.next), more: page.more }); +const asked = (query) => ({ ids: query.ids, seqs: query.seqs, next: query.next, more: query.more }); + +for (const c of VECTORS.exact_cases) { + test(`exact: ${c.name}`, async () => { + const rows = exactRows(c); + const reader = new aq.MemoryReader(); + for (const row of rows) reader.put(row); + for (const query of c.queries) { + // a cursor as a request names it: the digits read exactly, as a stream's are + const paging = 'before' in query; + const text = paging ? query.before : query.since; + const cursor = text === null ? null : aq.streamCursor(null, text); + const page = paging ? aq.pageBefore(rows, cursor, query.limit) : aq.pageSince(rows, cursor, query.limit); + const read = paging ? await reader.before(cursor, query.limit) : await reader.since(cursor, query.limit); + assert.deepEqual(shownAs(page), asked(query), JSON.stringify(query)); + assert.deepEqual(read.map((r) => String(r.id)), query.ids, JSON.stringify(query)); + } + assert.equal(String(await reader.latest()), c.latest); + }); +} + // --- configuration ------------------------------------------------------------------------------ -for (const [values, names] of [ +for (const [values, names, given] of [ [{ [aq.STORE]: 'redis' }, 'question.store must be memory or postgres'], [{ [aq.AUTH]: 'basic' }, 'question.auth must be one of none, oauth2'], [{ [aq.AUTH]: 'proxy' }, 'question.auth must be one of none, oauth2'], [{ [aq.AUTH]: 'oauth2' }, 'set question.auth.oauth2.issuer or question.auth.oauth2.jwks-url'], [{ [`${aq.POSTGRES_PREFIX}port`]: 'db' }, 'question.store.postgres.port must be a port number'], - [{ [aq.POLL]: '0' }, 'question.poll must be a duration'] + [{ [aq.POLL]: '0' }, 'question.poll must be a duration'], + // a switch is true or false: any other value stops the boot instead of being read as on + [{ [`${aq.POSTGRES_PREFIX}ssl`]: 'off' }, 'question.store.postgres.ssl must be true or false', 'off'], + [{ [`${aq.POSTGRES_PREFIX}ssl`]: 'no' }, 'question.store.postgres.ssl must be true or false', 'no'], + [{ [`${aq.POSTGRES_PREFIX}ssl`]: 0 }, 'question.store.postgres.ssl must be true or false', 'the number 0'], + // a number is ASCII digits: the digits of another script, a sign and a number past 2**53 - 1 are refused + [{ [`${aq.POSTGRES_PREFIX}port`]: '\u0665\u0664\u0663\u0662' }, 'question.store.postgres.port must be a port number', 'Arabic-Indic digits'], + [{ [`${aq.POSTGRES_PREFIX}port`]: '+5432' }, 'question.store.postgres.port must be a port number', 'a plus sign'], + [{ [`${aq.POSTGRES_PREFIX}timeout.ms`]: '\uff15\uff10\uff10' }, 'question.store.postgres.timeout.ms must be a whole number of milliseconds > 0', 'fullwidth digits'], + [{ [`${aq.POSTGRES_PREFIX}timeout.ms`]: 9007199254740992 }, 'question.store.postgres.timeout.ms must be a whole number of milliseconds > 0', 'one past the largest whole number'], + // a duration is such a number and, right after it, a unit + [{ [aq.POLL]: '\u0663s' }, 'question.poll must be a duration', 'an Arabic-Indic digit'], + [{ [aq.POLL]: '1 s' }, 'question.poll must be a duration', 'a space before the unit'], + [{ [aq.REPLY_TIMEOUT]: '1.5m' }, 'question.reply.timeout must be a duration', 'a fraction'], + [{ [aq.REPLY_TIMEOUT]: '9007199254741s' }, 'question.reply.timeout must be a duration', 'a second past the most milliseconds'], + [{ [aq.POLL]: '9'.repeat(5000) }, 'question.poll must be a duration', 'five thousand digits'], + // a setting that sets a timer takes no more than a timer holds in both packs: 2147483647 ms + [{ [aq.POLL]: '2147483648ms' }, 'question.poll must be a duration', 'a millisecond past what a timer holds'], + [{ [aq.POLL]: '25d' }, 'question.poll must be a duration', '25 days'], + [{ [aq.REPLY_TIMEOUT]: 2147484 }, 'question.reply.timeout must be a duration', 'a second past what a timer holds'], + [{ [`${aq.POSTGRES_PREFIX}timeout.ms`]: 2147483648 }, 'question.store.postgres.timeout.ms must be a whole number of milliseconds > 0', 'a millisecond past what a timer holds'], + // the host's keep-alive interval is how often a quiet stream looks for its device: the key's own message + [{ 'event.stream.keep.alive': '30d' }, 'event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none', '30 days'], + [{ 'event.stream.keep.alive': '2147483648ms' }, 'event.stream.keep.alive must be a duration such as 30s, 2m or 500ms (seconds, ms, s, m, h, d), or 0 for none', 'a millisecond past what a timer holds'], + // a port is 1 to 65535 + [{ [`${aq.POSTGRES_PREFIX}port`]: 65536 }, 'question.store.postgres.port must be a port number', 'one past the highest port'], + [{ [`${aq.POSTGRES_PREFIX}port`]: '70000' }, 'question.store.postgres.port must be a port number', '70000'], + [{ [`${aq.POSTGRES_PREFIX}port`]: 0 }, 'question.store.postgres.port must be a port number', 'port 0'], + // a setting's text is trimmed by the white space of the number rule: any other character is part of it + [{ [aq.STORE]: '\u0085memory' }, 'question.store must be memory or postgres', 'a next-line character before'], + [{ [aq.STORE]: 'memory\ufeff' }, 'question.store must be memory or postgres', 'a byte order mark after'], + [{ [aq.AUTH]: '\u001fnone' }, 'question.auth must be one of none, oauth2', 'a unit separator before'] ]) { - test(`the boot fails by name: ${names}`, () => { + test(`the boot fails by name: ${names}${given ? ` - ${given}` : ''}`, () => { for (const [key, value] of Object.entries({ ...BASE, ...values })) appConfig().set(key, value); try { assert.throws(() => aq.configure(), (e) => e instanceof aq.QuestionError && e.message.includes(names)); @@ -205,6 +389,97 @@ test("the postgres settings follow the audit store's", () => { } }); +test('the settings read a number, a duration and a switch by the one rule', () => { + // the text a ${NAME:default} reference resolves to and the value a YAML file holds are read alike: a switch in any + // letter case, a whole number or a duration with white space around it + const clear = configure({ ...BASE, [`${aq.POSTGRES_PREFIX}ssl`]: 'FALSE', [`${aq.POSTGRES_PREFIX}port`]: ' 6543\n', + [`${aq.POSTGRES_PREFIX}timeout.ms`]: 2500.0, [aq.POLL]: ' 007s ', [aq.REPLY_TIMEOUT]: 3.0 }); + try { + const s = clear.settings; + assert.equal(s.postgres.ssl, false); + assert.equal(s.postgres.port, 6543); + assert.equal(s.postgres.statement_timeout, 2500); + assert.equal(s.pollMs, 7000); + assert.equal(s.replyTimeoutMs, 3000); + appConfig().set(`${aq.POSTGRES_PREFIX}ssl`, 'True'); + assert.deepEqual(aq.configure().postgres.ssl, { rejectUnauthorized: false }); + appConfig().set(`${aq.POSTGRES_PREFIX}ssl`, ''); + assert.deepEqual(aq.configure().postgres.ssl, { rejectUnauthorized: false }, 'an empty value is the default'); + } finally { + clear(); + } +}); + +test('a setting that sets a timer takes the longest wait a timer holds', () => { + // 2147483647 ms is the longest delay a timer holds, so it is the most such a setting takes in both packs - in any + // unit - the host's keep-alive among them; and a port is at most 65535 + const clear = configure({ ...BASE, [aq.POLL]: '2147483647ms', [aq.REPLY_TIMEOUT]: '24d', [`${aq.POSTGRES_PREFIX}timeout.ms`]: '2147483647', + [`${aq.POSTGRES_PREFIX}port`]: 65535, 'event.stream.keep.alive': '2147483s' }); + try { + const s = clear.settings; + assert.equal(s.pollMs, 2_147_483_647); + assert.equal(s.replyTimeoutMs, 2_073_600_000); + assert.equal(s.postgres.statement_timeout, 2147483647); + assert.equal(s.postgres.port, 65535); + appConfig().set(`${aq.POSTGRES_PREFIX}port`, '1'); + assert.equal(aq.configure().postgres.port, 1); + // a keep-alive that is no duration is the host's to refuse, by the same message, when it starts + appConfig().set('event.stream.keep.alive', 'soon'); + assert.equal(aq.configure().pollMs, 2_147_483_647); + } finally { + clear(); + } +}); + +test('a quiet stream looks for its device at the keep-alive a timer holds', () => { + // at the host's keep-alive interval; every 30 seconds when the host sends none, and when the interval is longer + // than a timer holds - where the timer would fire at once, over and over + const read = (value) => { + appConfig().set('event.stream.keep.alive', value); + return aq.keepAliveMs(); + }; + try { + assert.deepEqual(['1s', '500ms', '2147483647ms'].map(read), [1000, 500, 2_147_483_647]); + assert.deepEqual(['2147483648ms', '25d', '30d', '9007199254740s'].map(read), Array(4).fill(30_000)); + } finally { + appConfig().set('event.stream.keep.alive', undefined); + } +}); + +test("a setting's text is trimmed by the white space of the number rule", () => { + // a setting's text loses the 24 characters around it and no other, so both packs read the same value from one file: + // a byte order mark, a next-line character or a separator - white space to one runtime's own trim only - is part of it + const clear = configure({ ...BASE, [aq.STORE]: '\u00a0memory\u3000', [aq.AUTH]: '\u2028none\t', [aq.PAGE_TITLE]: '\u2003Questions\u205f', + [aq.REPLY_TOKEN]: '\ufefftoken\u0085', [aq.OAUTH2_AUDIENCE]: '\u001caudience\u001f' }); + try { + const s = clear.settings; + assert.equal(s.store, 'memory'); + assert.equal(s.auth, 'none'); + assert.equal(s.pageTitle, 'Questions'); + assert.equal(s.replyToken, '\ufefftoken\u0085'); + assert.equal(s.oauth2Audience, '\u001caudience\u001f'); + } finally { + clear(); + } +}); + +test("a stream reads the host's keep-alive by the duration rule", () => { + // the keep-alive is the host's setting, and the host reads it by the rule: a stream looks for its device at the + // same interval, whatever unit the setting names, and at the default when the value is one the host refuses + const read = (value) => { + appConfig().set('event.stream.keep.alive', value); + return aq.keepAliveMs(); + }; + try { + assert.deepEqual(['1s', '500ms', ' 2m ', '1h', '1d', 45, '007', '0', 0, '0d'].map(read), + [1000, 500, 120_000, 3_600_000, 86_400_000, 45_000, 7000, 0, 0, 0]); + assert.equal(read(undefined), 30_000, 'no value is the default'); + assert.deepEqual(['soon', '\u0663s', '2 m', '30S', '1.5m', '9007199254741s', true].map(read), Array(7).fill(30_000)); + } finally { + appConfig().set('event.stream.keep.alive', undefined); + } +}); + // --- the intake and the feed ---------------------------------------------------------------------- test('the intake accepts the event and wakes the feed', async () => { @@ -247,6 +522,7 @@ test('the intake accepts the event and wakes the feed', async () => { class FakeReply { constructor() { this.posts = []; + this.texts = []; // each click as it arrived: a number past a double shows every digit only here this.onPost = null; this.jwks = { keys: [] }; this.server = http.createServer((req, res) => { @@ -255,8 +531,10 @@ class FakeReply { const chunks = []; req.on('data', (c) => chunks.push(c)); req.on('end', async () => { - const body = JSON.parse(Buffer.concat(chunks).toString() || '{}'); + const text = Buffer.concat(chunks).toString(); + const body = JSON.parse(text || '{}'); this.posts.push({ body, authorization: req.headers.authorization ?? null }); + this.texts.push(text); if (this.onPost) await this.onPost(body); if (body.ticket === 't-expired') return send(410, { type: 'nothing-waiting', run: 'fresh' }); if (body.ticket === 't-refused') return send(200, { type: 'approval', turn: 2, error: 'not a call waiting for approval', calls: CALLS }); @@ -334,6 +612,99 @@ test('the replay and the history page the record', async () => { } }); +test('the list reads its numbers by the rule', async () => { + // since and before are numbers of the record, limit is a whole number: ASCII digits, or the 400 - the same request + // gets the same answer from both packs + const clear = configure(BASE); + try { + sevenRows(); + const refusal = 'since, before and limit must be whole numbers'; + // another script's three, a sign, a fraction, a space, one past the largest number the record holds + for (const query of ['since=%D9%A3', 'before=%D9%A3', 'since=%2B3', 'since=3.0', 'since=%203', 'before=3%20', `since=${2n ** 63n}`, + `before=${2n ** 63n}`, 'limit=%D9%A3', 'limit=%2B3', 'limit=3.0', 'limit=1%200', `limit=${2n ** 53n}`, 'before=&limit=x']) { + const [status, body] = await getJson(`${host}/questions?${query}`); + assert.equal(status, 400, query); + assert.equal(body.message, refusal, query); + } + let [status, page] = await getJson(`${host}/questions?since=003&limit=%202%20`); + assert.equal(status, 200); + assert.deepEqual(page.rows.map((r) => r.id), [4, 3], 'leading zeros are digits; white space around a limit is ignored'); + assert.equal(page.since, 3); + [status, page] = await getJson(`${host}/questions?before=${2n ** 63n - 1n}&limit=${2n ** 53n - 1n}`); + assert.equal(status, 200); + assert.equal(page.rows.length, 7, 'the largest cursor and the largest limit: every row, a page of the most it takes'); + const reader = aq.reader(); + reader.putConversation(conversation(CONVERSATION_A, '2026-11-19T09:00:00.000Z'), [turn(1)]); + reader.putConversation(conversation(CONVERSATION_B, '2026-11-19T10:00:00.000Z'), [turn(1)]); + for (const query of ['limit=%D9%A1', 'limit=%2B1', 'limit=1.0', `limit=${2n ** 53n}`]) { + const [refused, body] = await getJson(`${host}/transcripts?${query}`); + assert.equal(refused, 400, query); + assert.equal(body.message, 'limit must be a whole number', query); + } + const [listed, transcripts] = await getJson(`${host}/transcripts?limit=%2001%20`); + assert.equal(listed, 200); + assert.deepEqual(transcripts.conversations.map((c) => c.conversation), [CONVERSATION_B]); + } finally { + clear(); + } +}); + +/** JSON as a client that keeps every digit reads it: a whole number a double does not hold exactly is a BigInt. */ +const exactJson = (text) => JSON.parse(text, (_key, value, context) => ( + typeof value === 'number' && !Number.isSafeInteger(value) && /^-?\d+$/.test(context.source) ? BigInt(context.source) : value)); + +test('a row past the whole numbers a double holds is sent with every digit', async () => { + // the record's id and seq are BIGINT columns: a page, a stream's event and a refusal tell a row by the numbers it + // has - a double would round them, lose a row whose id rounds to another's and put the page in another order + const clear = configure(BASE); + const controller = new AbortController(); + try { + const c = VECTORS.exact_cases[0]; + for (const row of exactRows(c)) aq.reader().put(row); + for (const query of c.queries) { + const named = 'before' in query ? `before=${query.before ?? ''}` : `since=${query.since}`; + const response = await fetch(`${host}/questions?${named}&limit=${query.limit}`); + assert.equal(response.status, 200, named); + assert.deepEqual(shownAs(exactJson(await response.text())), asked(query), named); + } + const stream = await fetch(`${host}/questions/events`, { headers: { 'last-event-id': '9223372036854775806' }, signal: controller.signal }); + const first = await frames(stream)(); + assert.equal(first[0], 'event: question'); + const sent = exactJson(first[1].slice('data: '.length)); + assert.deepEqual([String(sent.id), String(sent.seq)], ['9007199254740994', '9223372036854775807']); + const body = { decisions: [{ id: 'toolu_01A', approved: true }] }; + let response = await postJson(`${host}/questions/9007199254740992/decide`, body); + assert.equal(response.status, 409); + assert.equal((await response.json()).message, 'row 9007199254740992 is an advice - nothing to decide'); + response = await postJson(`${host}/questions/9007199254740995/decide`, body); + assert.equal(response.status, 404); + assert.equal((await response.json()).message, 'row 9007199254740995 is not in the record'); + } finally { + controller.abort(); + clear(); + } +}); + +test('health tells a cursor past the whole numbers a double holds in its digits', async () => { + // the health reply is rendered by the host, which renders no number past 2**53 - 1: the feed's cursor is a number + // up to there and its digits, as text, beyond - the same reply from both packs + const clear = configure(BASE); + try { + put(adviceEvent(), 1, 2 ** 53 - 1); + await aq.feed.pollOnce(); + let info = await aq.questionHealth({ type: 'info' }); + assert.equal(info.feed, 9007199254740991); + for (const row of exactRows(VECTORS.exact_cases[0])) aq.reader().put(row); + await aq.feed.pollOnce(); + info = await aq.questionHealth({ type: 'info' }); + assert.equal(info.feed, '9223372036854775807'); + assert.deepEqual(info.rows, { advice: 2, open: 2, answered: 1, expired: 1 }); + assert.equal(JSON.parse(JSON.stringify(info)).feed, '9223372036854775807', "the host's renderer takes the map"); + } finally { + clear(); + } +}); + /** Read SSE frames from a fetch body: each frame is the lines before a blank line. */ function frames(response) { const reader = response.body.getReader(); @@ -525,6 +896,24 @@ test('a decision is forwarded and the row is re-read as the recorder left it', a } }); +test('a whole number past a double in a decision and in a row is sent with every digit', async () => { + // the click forwards the decisions and answers with the row: a whole number past Number.MAX_SAFE_INTEGER - a BigInt in + // this pack - goes to the reply endpoint and to the invoker with every digit, where JSON.stringify alone refuses one + const clear = configure({ ...BASE, [aq.REPLY_TOKEN]: 'channel-app-bearer' }); + try { + const calls = [{ id: 'toolu_01A', name: 'transfer_units', route: 'demo.units.transfer', wait: true, input: { units: 2n ** 60n + 1n } }]; + const row = put(waitEvent({ ticket: 't-answer', base: replyUrl, calls }), 1, 1); + const request = new AsyncHttpRequest().setMethod('POST').setUrl(`/questions/${row.id}/decide`).setPathParameter('id', String(row.id)) + .setBody({ decisions: [{ id: 'toolu_01A', answer: 9007199254740993n }] }); + const answered = await aq.questionDecide({}, request.toMap()); + assert.equal(answered.getStatus(), 200); + assert.ok(reply.texts.at(-1).includes('"answer":9007199254740993'), reply.texts.at(-1)); + assert.ok(answered.body.includes('"units":1152921504606846977'), answered.body); + } finally { + clear(); + } +}); + test('the transcripts are browsed from the audit store', async () => { const clear = configure(BASE); try { @@ -554,6 +943,17 @@ test('the transcripts are browsed from the audit store', async () => { assert.equal((await getJson(`${host}/transcripts/${'f'.repeat(32)}`))[0], 404); assert.equal((await getJson(`${host}/transcripts/not-a-conversation`))[0], 400); assert.equal((await getJson(`${host}/transcripts?before=yesterday`))[0], 400); + // before is a time by the one reader of both packs: at an offset it is the same instant - the plus sign of an + // offset is %2B in a URL, where a bare + is a space - and a time without an offset is none + const [atAnOffsetStatus, atAnOffset] = await getJson(`${host}/transcripts?before=2026-11-19T12:00:00%2B01:00&limit=1`); + assert.equal(atAnOffsetStatus, 200); + assert.deepEqual(atAnOffset.conversations.map((c) => c.conversation), [CONVERSATION_B]); + for (const text of ['2026-11-19T12:00:00+01:00', '2026-11-19T11:00:00', '2026-11-19T11:00:00z', '2026-11-19%2011:00:00Z', + '2026-11-19T11Z', '20261119T110000Z']) { + const [refusedStatus, refused] = await getJson(`${host}/transcripts?before=${text}`); + assert.equal(refusedStatus, 400, text); + assert.equal(refused.message, 'before must be an ISO-8601 time', text); + } assert.equal((await getJson(`${host}/transcripts?limit=x`))[0], 400); } finally { clear(); @@ -585,6 +985,10 @@ test('the oauth2 mode guards every read and the click', async () => { [status, config] = await getJson(`${host}/questions?since=0`, bearer); assert.equal(status, 200); assert.deepEqual(config.rows.map((r) => r.id), [1]); + // the token loses the white space of the number rule around it and no other: a next-line character is part of it + // in both packs, where the other runtime's own trim took it off and let the token pass + assert.equal((await getJson(`${host}/questions?since=0`, { authorization: `Bearer ${token}\u00a0` }))[0], 200); + assert.equal((await getJson(`${host}/questions?since=0`, { authorization: `Bearer ${token}\u0085` }))[0], 401); assert.equal((await getJson(`${host}/transcripts`, bearer))[0], 200); response = await postJson(`${host}/questions/${row.id}/decide`, { decisions, decided_by: 'spoof' }, bearer); assert.equal(response.status, 200); diff --git a/test/ask-person.test.mjs b/test/ask-person.test.mjs index ba744683..8367a25f 100644 --- a/test/ask-person.test.mjs +++ b/test/ask-person.test.mjs @@ -2,9 +2,13 @@ * Ask a person - the main flow (extensions/ask-person/ask-person.mjs). * * The shared contract file test/vectors/ask-person-vectors.json (byte-identical in mercury-python) pins the pure - * half: the ticket issued, verified, tampered, expired and rotated; the message validated in its fixed order and - * the event built; the re-advice and the resume requests; the outcomes; the row a message becomes in the question - * record, the state an answer leaves and the record's transitions on the reference store. The tests after the vector + * half: the ticket issued, verified, tampered, expired and rotated, and the payloads a key holder signed that are not + * the canonical one; the message validated in its fixed order and the event built; the re-advice and the resume + * requests; the outcomes; the row a message becomes in the question record, the state an answer leaves and the + * record's transitions on the reference store; a number, a duration and a switch read by the one rule of both packs; + * a time read by their one reader, the white space around a text, and whole numbers past the ones a double holds + * written to the record with every digit. + * The tests after the vector * runs drive the function on the bus with channels that take, refuse and miss the event - the record written before * they are told - and the reply page and endpoint over the host against a fake engine: the page's shell and the wait * read without resuming, the decisions forwarded with who decided prefixed to each note and the answer recorded, an @@ -14,19 +18,21 @@ * name, the health route and the inspect command. */ import assert from 'node:assert/strict'; -import { createHash, generateKeyPairSync } from 'node:crypto'; +import { createHash, createHmac, generateKeyPairSync } from 'node:crypto'; import { readFileSync } from 'node:fs'; import http from 'node:http'; import { after, before, test } from 'node:test'; import { fileURLToPath } from 'node:url'; -import { AppException, appConfig, defaultRegistry, EventApiServer, FunctionRegistry, isoUtc, Platform, PostOffice } from 'mercury-composable'; +import { + AppException, appConfig, AsyncHttpRequest, defaultRegistry, EventApiServer, FunctionRegistry, isoUtc, Platform, PostOffice +} from 'mercury-composable'; import * as ask from '../extensions/ask-person/ask-person.mjs'; const VECTORS_FILE = new URL('./vectors/ask-person-vectors.json', import.meta.url); // the reply page and endpoint are rest.yaml entries: the host reads the extension's file (RFC-0018) const REST_YAML = fileURLToPath(new URL('../extensions/ask-person/resources/rest.yaml', import.meta.url)); // the Python twin runs the same file: change it in both packs or in neither -const VECTORS_SHA256 = '969f01fac46a3af11632fc6343fe4379386393dd183b0ed3b5c4e1ec5ac3b9b5'; +const VECTORS_SHA256 = '5b62f4f1b0461b43774eab877902b4af1a37e4e1a92fecd42cdfdd1f18ba9dad'; const VECTORS = JSON.parse(readFileSync(VECTORS_FILE, 'utf8')); const KEY = 'test-key-current'; @@ -74,20 +80,34 @@ const ticketFor = ({ graph = 'order-assistant', cid = 'order-1002-case', turn = const listen = (server) => new Promise((resolveListen) => server.listen(0, '127.0.0.1', () => resolveListen(`http://127.0.0.1:${server.address().port}`))); const close = (server) => new Promise((resolveClose) => server.close(() => resolveClose())); -const readJson = (req) => new Promise((resolveBody) => { +const readText = (req) => new Promise((resolveBody) => { const chunks = []; req.on('data', (c) => chunks.push(c)); - req.on('end', () => resolveBody(chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : {})); + req.on('end', () => resolveBody(Buffer.concat(chunks).toString())); }); +/** What stands at a place of a value: the keys and the indexes that lead to it. */ +const at = (value, place) => place.reduce((inner, step) => inner[step], value); + +/** + * A copy of an exact case's value with each whole number at the place the case names - a BigInt, as the wire codec + * hands a number past Number.MAX_SAFE_INTEGER to a function; the vector file gives the digits as text, since a JSON + * number that large is not exact in every reader. + */ +function placed(value, numbers) { + const copy = structuredClone(value); + for (const number of numbers) at(copy, number.place.slice(0, -1))[number.place.at(-1)] = BigInt(number.digits); + return copy; +} + // --- the shared vectors ------------------------------------------------------------------------- test('the vector file is the one the Python twin runs', () => { assert.equal(createHash('sha256').update(readFileSync(VECTORS_FILE)).digest('hex'), VECTORS_SHA256); assert.equal(VECTORS.contract, 'ask-person'); - assert.equal(VECTORS.version, 3); + assert.equal(VECTORS.version, 5); for (const section of ['ticket_cases', 'verify_cases', 'message_cases', 'readvice_cases', 'reply_cases', 'outcome_cases', - 'record_cases', 'answer_cases', 'transition_cases']) { + 'record_cases', 'answer_cases', 'transition_cases', 'number_cases', 'switch_cases', 'time_cases', 'text_cases', 'exact_cases']) { assert.ok(VECTORS[section].length > 0, section); } }); @@ -182,6 +202,100 @@ for (const c of VECTORS.transition_cases) { }); } +// a value read as a whole number and as a duration: the one rule of both packs and of every extension +for (const c of VECTORS.number_cases) { + test(`number: ${c.name}`, () => { + assert.equal(ask.wholeNumber(c.value), c.whole); + assert.equal(ask.durationMs(c.value), c.duration_ms); + }); +} + +// a switch: true or false, the default for no value and an empty one, and null - refused - for any other +for (const c of VECTORS.switch_cases) { + test(`switch: ${c.name}`, () => { + const [on, off] = c.switch === 'default' ? [true, false] : [c.switch, c.switch]; + assert.equal(ask.switchValue(c.value, true), on); + assert.equal(ask.switchValue(c.value, false), off); + if (c.value === null) assert.equal(ask.switchValue(undefined, true), true, 'a key that is not set is no value'); + }); +} + +// a time a caller supplies, by the one reader of both packs: the instant to the millisecond and the text written back +// for it - or no time at all, and a stamp the store gave as text is then kept as it came +for (const c of VECTORS.time_cases) { + test(`time: ${c.name}`, () => { + const moment = ask.parseIso(c.text); + const stamped = ask.rowFromRecord(record({ requested_at: c.text })).requested_at; + if (c.ms === null) { + assert.equal(moment, null); + assert.equal(stamped, c.text); + } else { + assert.equal(moment.getTime(), c.ms); + assert.equal(isoUtc(moment), c.stamp); + assert.equal(stamped, c.stamp); + } + }); +} + +// the white space around a text - the 24 characters of the number rule and no other - and what it decides: a setting's +// text loses it, and a required text of nothing else is missing, in both packs alike +for (const c of VECTORS.text_cases) { + test(`text: ${c.name}`, () => { + const clear = configure({ ...BASE, [ask.OAUTH2_AUDIENCE]: c.text }); + try { + assert.equal(clear.settings.oauth2Audience, c.trimmed); + } finally { + clear(); + } + const message = approvalMessage({ summary: c.text, requested_at: '2026-11-19T09:12:04.118Z' }); + if (c.blank) { + assert.throws(() => ask.validateMessage(message), (e) => e instanceof AppException && e.status === 400 && e.message === 'summary is required'); + } else { + assert.equal(ask.validateMessage(message).summary, c.text); + } + }); +} + +test('the white space of a number and of a text is the same 24 characters', () => { + // the white space around a number and the white space a blank text is made of are one set: no character of the basic + // plane is the one and a character of a name, or the reverse + const message = approvalMessage({ requested_at: '2026-11-19T09:12:04.118Z' }); + const blank = (text) => { + try { + ask.validateMessage({ ...message, summary: text }); + return false; + } catch (error) { + if (!(error instanceof AppException)) throw error; + return true; + } + }; + const units = Array.from({ length: 0x10000 }, (_unused, code) => String.fromCharCode(code)); + const aroundANumber = units.filter((ch) => ask.wholeNumber(`${ch}5${ch}`) === 5); + assert.deepEqual(units.filter(blank), aroundANumber); + assert.equal(aroundANumber.length, 24); +}); + +test('a wait ends before the year 10000 whenever it was requested', () => { + // requested_at is now when the message names none: a ttl that carries now past the year 9999 is the 400 a + // requested_at of that year gets - where the expiry was a time no pack writes - and a message that was never + // validated is refused the same way when its event is built + const tooLate = (e) => e instanceof AppException && e.status === 400 && e.message === 'ttl must end before the year 10000'; + assert.throws(() => ask.validateMessage(approvalMessage({ ttl: '2913000d' })), tooLate); + const message = ask.validateMessage(approvalMessage({ ttl: '2800000d' })); + const event = ask.buildEvent(message, Buffer.from(KEY), REPLY_URL); + assert.equal(ask.parseIso(event.expires_at).getTime() - ask.parseIso(event.requested_at).getTime(), 2_800_000 * 86_400_000); + assert.throws(() => ask.buildEvent({ ...message, ttl_ms: Number.MAX_SAFE_INTEGER }, Buffer.from(KEY), REPLY_URL), tooLate); +}); + +test('an expiry before 1970 is its whole seconds below', () => { + // the expiry a ticket carries is the floor of its seconds: a quarter of a second before 1970 is -1 in both packs, + // where cutting the fraction off gives 0 and the two would issue different tickets + const message = ask.validateMessage(approvalMessage({ requested_at: '1969-12-31T23:59:58.250Z', ttl: 1 })); + const event = ask.buildEvent(message, Buffer.from(KEY), REPLY_URL); + assert.equal(event.expires_at, '1969-12-31T23:59:59.250Z'); + assert.equal(ask.verifyTicket(event.ticket, [Buffer.from(KEY)], -10).e, -1); +}); + test('the duration grammar and the default requested_at', () => { assert.equal(ask.durationMs('500ms'), 500); assert.equal(ask.durationMs('30m'), 1_800_000); @@ -238,6 +352,40 @@ test('a ticket has one spelling', () => { assert.deepEqual([...lengths].sort((a, b) => a - b), [0, 2, 3]); }); +/** A ticket whose payload part is these bytes, signed with the current key: what a key holder can make. */ +function signed(payload) { + const part = (data) => data.toString('base64url'); + return `v1.${part(payload)}.${part(createHmac('sha256', Buffer.from(KEY)).update(payload).digest())}`; +} + +test('a signed payload has one spelling', () => { + // the payload under a valid signature is the canonical JSON of a wait's five fields: the issuer's own bytes verify, + // and the same wait spelled another way - or nested deeper than the decoder reads - is malformed + const now = 1795089600; + const payload = { g: 'order-assistant', c: 'order-1002-case', t: 2, k: 'approval', e: now + 3600 }; + const canonical = ask.canonicalJson(payload); + const bytes = (text) => Buffer.from(text, 'utf8'); + assert.deepEqual(ask.verifyTicket(signed(bytes(canonical)), [Buffer.from(KEY)], now), payload); + const others = [ + bytes(canonical.replace('"t":2', '"t":2.0')), + bytes(canonical.replace('"t":2', '"t":-0')), + bytes(canonical.replace('"t":2', '"t":9007199254740992')), + bytes(canonical.replace('order-1002', String.raw`order-\u0031002`)), + bytes(canonical.replace('order-1002', String.raw`order-\ud800`)), + Buffer.concat([bytes(canonical.slice(0, 6)), Buffer.from([0xff]), bytes(canonical.slice(6))]), + bytes(canonical.replace('"t":2', '"t":2,"t":2')), + bytes(canonical.replaceAll(',', ', ')), + bytes(JSON.stringify(payload)), + bytes(`${canonical}\n`), + bytes(canonical.replace('"t":2', `"t":${'9'.repeat(5000)}`)), + bytes('['.repeat(100_000) + ']'.repeat(100_000)) + ]; + for (const other of others) { + assert.throws(() => ask.verifyTicket(signed(other), [Buffer.from(KEY)], now), + (e) => e instanceof ask.TicketError && e.status === 400 && e.message === 'Ticket is malformed', other.subarray(0, 80).toString('latin1')); + } +}); + // --- configuration -------------------------------------------------------------------------------- test('the settings read lists and pairs in both forms', () => { @@ -262,7 +410,7 @@ test('the settings read lists and pairs in both forms', () => { } }); -for (const [values, names] of [ +for (const [values, names, given] of [ [{ [ask.TICKET_KEY]: '' }, 'ask.ticket.key is not set'], [{ [ask.REPLY_URL]: 'ask.example.test' }, 'ask.reply.url must be the public base'], [{ [ask.REPLY_AUTH]: 'basic' }, 'ask.reply.auth must be one of none, oauth2'], @@ -274,9 +422,44 @@ for (const [values, names] of [ [{ [ask.GRAPHS]: [{ id: 'g', entry: 'ftp://x' }] }, 'the entry of g must be an http or https URL'], [{ [ask.GRAPHS]: [{ id: 'g' }] }, 'ask.graphs entries need id and entry'], [{ [ask.CHANNEL_ENDPOINTS]: 'nonsense' }, 'ask.channel.endpoints takes route=url pairs'], - [{ [ask.CHANNEL_TIMEOUT]: '0' }, 'ask.channel.timeout must be a duration'] + [{ [ask.CHANNEL_TIMEOUT]: '0' }, 'ask.channel.timeout must be a duration'], + // a switch is true or false: any other value stops the boot instead of leaving the switch off + [{ [ask.ENABLED]: 'maybe' }, 'ask.enabled must be true or false', 'maybe'], + [{ [ask.ENABLED]: 'yes' }, 'ask.enabled must be true or false', 'yes'], + [{ [ask.ENABLED]: 1 }, 'ask.enabled must be true or false', 'the number 1'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}ssl`]: 'off' }, 'ask.audit.postgres.ssl must be true or false', 'off'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}ssl`]: ' false' }, 'ask.audit.postgres.ssl must be true or false', 'a space before false'], + // a number is ASCII digits: the digits of another script, a sign and a number past 2**53 - 1 are refused + [{ [ask.AUDIT_INSTANCES]: '\u0663' }, 'ask.audit.instances must be a whole number >= 1', 'an Arabic-Indic digit'], + [{ [ask.AUDIT_INSTANCES]: '+3' }, 'ask.audit.instances must be a whole number >= 1', 'a plus sign'], + [{ [ask.AUDIT_INSTANCES]: 9007199254740992 }, 'ask.audit.instances must be a whole number >= 1', 'one past the largest whole number'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}timeout.ms`]: '\uff15\uff10\uff10' }, 'ask.audit.postgres.timeout.ms must be a whole number >= 1', 'fullwidth digits'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}port`]: '\u0665\u0664\u0663\u0662' }, 'ask.audit.postgres.port must be a port number', 'Arabic-Indic digits'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}port`]: 5432.5 }, 'ask.audit.postgres.port must be a port number', 'a fraction'], + // a duration is such a number and, right after it, a unit + [{ [ask.CHANNEL_TIMEOUT]: '\u0663s' }, 'ask.channel.timeout must be a duration', 'an Arabic-Indic digit'], + [{ [ask.CHANNEL_TIMEOUT]: '2 s' }, 'ask.channel.timeout must be a duration', 'a space before the unit'], + [{ [ask.ENGINE_TIMEOUT]: '1.5m' }, 'ask.engine.timeout must be a duration', 'a fraction'], + [{ [ask.AUDIT_SWEEP]: '9007199254741s' }, 'ask.audit.sweep must be a duration', 'a second past the most milliseconds'], + [{ [ask.AUDIT_TIMEOUT]: '9'.repeat(5000) }, 'ask.audit.timeout must be a duration', 'five thousand digits'], + // a setting that sets a timer takes no more than a timer holds in both packs: 2147483647 ms + [{ [ask.CHANNEL_TIMEOUT]: '2147483648ms' }, 'ask.channel.timeout must be a duration', 'a millisecond past what a timer holds'], + [{ [ask.ENGINE_TIMEOUT]: '25d' }, 'ask.engine.timeout must be a duration', '25 days'], + [{ [ask.AUDIT_SWEEP]: '30d' }, 'ask.audit.sweep must be a duration', '30 days'], + [{ [ask.AUDIT_TIMEOUT]: 2147484 }, 'ask.audit.timeout must be a duration', 'a second past what a timer holds'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}timeout.ms`]: 2147483648 }, 'ask.audit.postgres.timeout.ms must be a whole number >= 1', 'a millisecond past what a timer holds'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}timeout.ms`]: '9007199254740991' }, 'ask.audit.postgres.timeout.ms must be a whole number >= 1', 'the largest whole number'], + // a port is 1 to 65535 + [{ [`${ask.AUDIT_POSTGRES_PREFIX}port`]: 65536 }, 'ask.audit.postgres.port must be a port number', 'one past the highest port'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}port`]: '70000' }, 'ask.audit.postgres.port must be a port number', '70000'], + [{ [`${ask.AUDIT_POSTGRES_PREFIX}port`]: 0 }, 'ask.audit.postgres.port must be a port number', 'port 0'], + // a setting's text is trimmed by the white space of the number rule: any other character is part of it + [{ [ask.REPLY_AUTH]: '\u0085none' }, 'ask.reply.auth must be one of none, oauth2', 'a next-line character before'], + [{ [ask.REPLY_AUTH]: 'none\ufeff' }, 'ask.reply.auth must be one of none, oauth2', 'a byte order mark after'], + [{ [ask.AUDIT]: '\u001fmemory' }, 'ask.audit must be one of memory, postgres', 'a unit separator before'], + [{ [ask.REPLY_URL]: '\ufeffhttps://ask.example.test' }, 'ask.reply.url must be the public base', 'a byte order mark before'] ]) { - test(`the boot fails by name: ${names}`, () => { + test(`the boot fails by name: ${names}${given ? ` - ${given}` : ''}`, () => { for (const [key, value] of Object.entries({ ...BASE, ...values })) appConfig().set(key, value); try { assert.throws(() => ask.configure(), (e) => e instanceof ask.AskError && e.message.includes(names)); @@ -296,6 +479,106 @@ test('a disabled extension loads without a key', () => { } }); +test('the settings read a number, a duration and a switch by the one rule', () => { + // the text a ${NAME:default} reference resolves to and the value a YAML file holds are read alike: a switch in any + // letter case, a whole number or a duration with white space around it + const clear = configure({ ...BASE, [ask.ENABLED]: 'TRUE', [ask.CHANNEL_TIMEOUT]: ' 1500ms ', [ask.ENGINE_TIMEOUT]: 90.0, + [ask.AUDIT_SWEEP]: '007s', [ask.AUDIT_TIMEOUT]: '2', [ask.AUDIT_INSTANCES]: ' 3\n', [`${ask.AUDIT_POSTGRES_PREFIX}ssl`]: 'False', + [`${ask.AUDIT_POSTGRES_PREFIX}port`]: ' 6543 ', [`${ask.AUDIT_POSTGRES_PREFIX}timeout.ms`]: 2500.0 }); + try { + const s = clear.settings; + assert.equal(s.enabled, true); + assert.equal(s.channelTimeoutMs, 1500); + assert.equal(s.engineTimeoutMs, 90_000); + assert.equal(s.auditSweepMs, 7000); + assert.equal(s.auditTimeoutMs, 2000); + assert.equal(s.auditInstances, 3); + assert.equal(s.auditPostgres.ssl, false); + assert.equal(s.auditPostgres.port, 6543); + assert.equal(s.auditPostgres.statement_timeout, 2500); + const off = configure({ [ask.ENABLED]: 'false', [`${ask.AUDIT_POSTGRES_PREFIX}ssl`]: '' }); + assert.equal(off.settings.enabled, false); + assert.notEqual(off.settings.auditPostgres.ssl, false, 'an empty value is the default'); + } finally { + clear(); + } +}); + +test('a setting that sets a timer takes the longest wait a timer holds', () => { + // 2147483647 ms is the longest delay a timer holds, so it is the most such a setting takes in both packs - in any + // unit - and a port is at most 65535 + const clear = configure({ ...BASE, [ask.CHANNEL_TIMEOUT]: '2147483647ms', [ask.ENGINE_TIMEOUT]: '2147483s', [ask.AUDIT_SWEEP]: '24d', + [ask.AUDIT_TIMEOUT]: 2147483, [`${ask.AUDIT_POSTGRES_PREFIX}timeout.ms`]: '2147483647', [`${ask.AUDIT_POSTGRES_PREFIX}port`]: 65535 }); + try { + const s = clear.settings; + assert.equal(s.channelTimeoutMs, 2_147_483_647); + assert.equal(s.engineTimeoutMs, 2_147_483_000); + assert.equal(s.auditSweepMs, 2_073_600_000); + assert.equal(s.auditTimeoutMs, 2_147_483_000); + assert.equal(s.auditPostgres.statement_timeout, 2147483647); + assert.equal(s.auditPostgres.port, 65535); + appConfig().set(`${ask.AUDIT_POSTGRES_PREFIX}port`, '1'); + assert.equal(ask.configure().auditPostgres.port, 1); + } finally { + clear(); + } +}); + +test("a setting's text is trimmed by the white space of the number rule", () => { + // a setting's text loses the 24 characters around it and no other, so both packs read one key, one list of names + // and one mode from the same file: a byte order mark, a next-line character or a separator - white space to one + // runtime's own trim only - is part of the value + const clear = configure({ ...BASE, [ask.TICKET_KEY]: '\u00a0key\u3000', [ask.PREVIOUS_KEY]: '\ufeffold\u0085', [ask.REPLY_AUTH]: '\u2028none\t', + [ask.CHANNELS]: 'a.route\u0085,\u2003b.route\u00a0, \ufeff ,\u001f', [ask.OAUTH2_AUDIENCE]: '\u001caudience\ufeff', + [ask.GRAPHS]: '\u205fg1\u1680=\u2000http://e/1\u200a, g\u0085=http://e/2\ufeff', + [ask.CHANNEL_ENDPOINTS]: [{ route: '\tb.route\u2029', url: '\u202fhttp://peer/api/event\n' }] }); + try { + const s = clear.settings; + assert.deepEqual(s.keys.map(String), ['key', '\ufeffold\u0085']); + assert.equal(s.auth, 'none'); + assert.deepEqual(s.channels, ['a.route\u0085', 'b.route', '\ufeff', '\u001f']); + assert.equal(s.oauth2Audience, '\u001caudience\ufeff'); + assert.deepEqual(s.graphs, { g1: 'http://e/1', 'g\u0085': 'http://e/2\ufeff' }); + assert.deepEqual(s.channelEndpoints, { 'b.route': 'http://peer/api/event' }); + } finally { + clear(); + } +}); + +test('a graph and a route may carry the name of a member every object has', () => { + // the allowlist and the endpoints are tables of the names the configuration gives, whatever they are: kept as the + // table's own keys, where a plain assignment loses __proto__ and a plain lookup finds constructor + const clear = configure({ ...BASE, [ask.GRAPHS]: [{ id: '__proto__', entry: 'http://e/p' }, { id: 'constructor', entry: 'http://e/c' }], + [ask.CHANNEL_ENDPOINTS]: '__proto__=http://peer/api/event, toString=http://other/api/event' }); + try { + const s = clear.settings; + assert.deepEqual(Object.entries(s.graphs), [['__proto__', 'http://e/p'], ['constructor', 'http://e/c']]); + assert.deepEqual(Object.entries(s.channelEndpoints), [['__proto__', 'http://peer/api/event'], ['toString', 'http://other/api/event']]); + const payload = { g: '__proto__', c: 'order-1002-case', t: 2, k: 'approval', e: 1795252324 }; + assert.equal(ask.readviceRequest(payload, s.graphs).url, 'http://e/p'); + assert.throws(() => ask.readviceRequest({ ...payload, g: 'toString' }, s.graphs), + (e) => e instanceof ask.ReplyError && e.status === 404 && e.message === 'graph toString is not configured for replies'); + } finally { + clear(); + } +}); + +test('a channel named as a member every object has is a route nobody serves', async () => { + // a channel has an endpoint only when the configuration gives it one: a route named constructor or __proto__ with + // none is looked for in this process and, as nobody serves it, reported as any missing route + const clear = configure({ ...BASE, [ask.CHANNELS]: ['constructor', '__proto__', 'ask.test.nobody'] }); + const registry = new FunctionRegistry(); + ask.resetPostOffice(new PostOffice(undefined, {}, registry)); + const event = ask.buildEvent(ask.validateMessage(approvalMessage()), Buffer.from(KEY), REPLY_URL); + try { + assert.deepEqual(await ask.deliver(event, clear.settings), clear.settings.channels.map((route) => ({ route, ok: false, status: 404 }))); + } finally { + ask.resetPostOffice(undefined); + await registry.bus.close(); + clear(); + } +}); + // --- the function on the bus --------------------------------------------------------------------- test('the fan-out records the event, then takes, refuses and misses channels on the default registry', async () => { @@ -395,6 +678,7 @@ test('health reports the setup', async () => { class FakeEngine { constructor() { this.requests = []; + this.texts = []; // each graph request as it arrived: a number past a double shows every digit only here this.jwks = { keys: [] }; this.server = http.createServer(async (req, res) => { const url = new URL(req.url, 'http://127.0.0.1'); @@ -404,10 +688,13 @@ class FakeEngine { } const graph = /^\/api\/graph\/([^/]+)$/.exec(url.pathname); if (req.method === 'POST' && graph) { - const body = await readJson(req); + const text = await readText(req); + const body = text ? JSON.parse(text) : {}; const cid = req.headers['x-correlation-id']; this.requests.push({ graph: graph[1], cid, body }); + this.texts.push(text); const send = (status, payload) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(payload)); }; + if (cid === 'slow-case') await new Promise((resolveWait) => setTimeout(resolveWait, 100)); // an engine that takes its time if (cid === 'expired-case') return send(410, { type: 'nothing-waiting', cid }); if ('decisions' in body) return send(200, { type: 'answer', turn: body.turn + 1, run: 'resume', message: 'Your refund has been issued.' }); return send(200, { type: 'approval', turn: body.turn, run: 'resume', calls: CALLS, message: "A tool call waits for a supervisor's decision.", cid }); @@ -502,6 +789,32 @@ test('the page refuses bad tickets and reports an expired wait', async () => { } }); +test('a graph named as a member every object has is not configured', async () => { + // a graph id from a ticket matches the names the allowlist gives and no other: constructor, toString and __proto__ + // are members every object has, and none of them is a graph + const clear = configure({ ...BASE, [ask.GRAPHS]: graphs() }); + try { + engine.requests.length = 0; + const decisions = [{ id: 'toolu_01A', approved: true }]; + for (const graph of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) { + const ticket = ticketFor({ graph }); + const refusal = `graph ${graph} is not configured for replies`; + let response = await fetch(`${host}/ask/${ticket}`); + assert.equal(response.status, 404, graph); + assert.ok((await response.text()).includes(refusal), graph); + response = await fetch(`${host}/ask/${ticket}/wait`); + assert.equal(response.status, 404, graph); + assert.equal((await response.json()).message, refusal, graph); + response = await fetch(`${host}/ask/reply`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ticket, decisions }) }); + assert.equal(response.status, 404, graph); + assert.equal((await response.json()).message, refusal, graph); + } + assert.equal(engine.requests.length, 0, 'no ticket above reached the engine'); + } finally { + clear(); + } +}); + test('a reply resumes the graph with who decided on each note', async () => { const clear = configure({ ...BASE, [ask.GRAPHS]: graphs() }); try { @@ -646,6 +959,40 @@ test('the oauth2 mode validates an access token and the page learns how to sign } }); +test('a bearer is trimmed by the white space of the number rule', async () => { + // the token after Bearer loses the 24 characters around it and no other, and is compared as its bytes: a next-line + // character, a separator or a byte order mark is part of the token in both packs - one runtime's own trim took it + // off and let the token pass + const clear = configure({ ...BASE, [ask.APP_TOKEN]: APP_TOKEN }); + const via = async (header) => (await ask.identify(new AsyncHttpRequest().setHeader('authorization', header), clear.settings, 'operator-9', true)).via; + try { + assert.equal(await via(`Bearer ${APP_TOKEN}`), 'app'); + assert.equal(await via(`Bearer \u00a0${APP_TOKEN}\u3000`), 'app'); + assert.equal(await via(`Bearer ${APP_TOKEN}\u0085`), 'none'); + assert.equal(await via(`Bearer ${APP_TOKEN}\u001f`), 'none'); + assert.equal(await via(`Bearer ${APP_TOKEN}\ufeff`), 'none'); + assert.equal(await via('Bearer caf\u00e9'), 'none'); + assert.equal(await via('Bearer \u2003'), 'none'); + } finally { + clear(); + } +}); + +test('the engine has its time at the longest wait a timer holds', async () => { + // ask.engine.timeout at the most a timer holds: the request to the engine is given that long and no longer - a + // second more would carry the timer past what it holds, which aborts the request at once, before a graph that + // takes a tenth of a second has answered + const clear = configure({ ...BASE, [ask.GRAPHS]: graphs(), [ask.ENGINE_TIMEOUT]: '2147483647ms' }); + try { + const body = { ticket: ticketFor({ cid: 'slow-case' }), decisions: [{ id: 'toolu_01A', approved: true }] }; + const response = await fetch(`${host}/ask/reply`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + assert.equal(response.status, 200); + assert.equal((await response.json()).type, 'answer'); + } finally { + clear(); + } +}); + // --- the PostgreSQL store on a recording fake of the pool ------------------------------------------- class FakePool { @@ -741,6 +1088,107 @@ test('the postgres store runs the statements and maps the records', async () => assert.equal(ask.failure(Object.assign(new Error('x'), { severity: 'ERROR', code: '23505' })), 'Error sqlstate=23505'); }); +test('a row past the whole numbers a double holds is told by the number it has', async () => { + // the record's id and seq are BIGINT columns, which pg gives as text: a row is told by the numbers it has - in the + // row, in the recorder's answer as it crosses the bus and in its log line - never by the nearest number a double holds + const big = record({ id: '9223372036854775807', seq: '9007199254740993' }); + const row = ask.rowFromRecord(big); + assert.deepEqual([String(row.id), String(row.seq)], ['9223372036854775807', '9007199254740993']); + assert.deepEqual([ask.rowFromRecord(record()).id, ask.rowFromRecord(record()).seq], [7, 12], 'a number a double holds stays a number'); + const clear = configure({ ...BASE, [ask.AUDIT_TIMEOUT]: '2s' }); + const registry = new FunctionRegistry(); + registry.register(ask.AUDIT_ROUTE, ask.questionAudit, { instances: 1, isPrivate: true }); + const event = ask.buildEvent(ask.validateMessage(approvalMessage()), Buffer.from(KEY), REPLY_URL); + try { + ask.resetStore(new ask.PostgresQuestionStore(new FakePool([big]))); + const answer = await ask.questionAudit({}, { record: event }); + assert.deepEqual(Object.fromEntries(Object.entries(answer).map(([name, value]) => [name, String(value)])), + { recorded: 'true', id: '9223372036854775807', seq: '9007199254740993', state: 'open' }); + ask.resetPostOffice(new PostOffice(undefined, {}, registry)); + assert.equal(await ask.record({ record: event }, clear.settings), true, 'the answer crosses the bus with its numbers'); + } finally { + ask.resetPostOffice(undefined); + ask.resetStore(); + await registry.bus.close(); + clear(); + } +}); + +// a whole number past 9007199254740991 in a waiting call's input, and in a decision: the record's message and decisions +// columns are given the text both packs write, every digit in it - JSON.stringify alone refuses such a number, and the +// question was not recorded +for (const c of VECTORS.exact_cases) { + test(`exact: ${c.name}`, async () => { + const event = ask.buildEvent(ask.validateMessage(placed(c.message, c.numbers)), Buffer.from(c.key), c.reply_url); + assert.equal(event.ticket, c.ticket); + const pool = new FakePool([record()]); + ask.resetStore(new ask.PostgresQuestionStore(pool)); + try { + assert.equal((await ask.questionAudit({}, { record: event })).recorded, true); + assert.equal(pool.log.at(-1)[1][7], c.record); + const answer = { graph_id: event.graph_id, correlation_id: event.correlation_id, turn: event.turn, + decisions: placed(c.decisions, c.decision_numbers), who: 'operator-9', status: 200, body: { type: 'answer' } }; + assert.equal((await ask.questionAudit({}, { answer })).recorded, true); + assert.equal(pool.log.at(-1)[1][1], c.decisions_record); + } finally { + ask.resetStore(); + } + }); +} + +test('a whole number past a double crosses the bus to the channels and the record', async () => { + // the same message through the function: the channel is handed every number as it was sent, and the row the + // recorder keeps - in memory, and through the statements of the PostgreSQL store - is the event the channel got + const c = VECTORS.exact_cases[0]; + const taken = []; + defaultRegistry.register('ask.test.exact', async (_h, body) => { + taken.push(body); + return { stored: true }; + }, { instances: 1 }); + const store = recorder(); + const clear = configure({ ...BASE, [ask.CHANNELS]: ['ask.test.exact'] }); + try { + const result = await ask.personAsk({}, placed(c.message, c.numbers)); + assert.deepEqual(result, { delivered: [{ route: 'ask.test.exact', ok: true, status: 200 }], recorded: true, ticket: c.ticket, + link: `${REPLY_URL}/ask/${c.ticket}`, expires_at: c.expires_at }); + for (const number of c.numbers) assert.equal(String(at(taken[0], number.place)), number.digits, number.place.join('.')); + const rows = await store.since(0, 10); + for (const number of c.numbers) assert.equal(String(at(rows[0].message, number.place)), number.digits, number.place.join('.')); + const pool = new FakePool([record()]); + ask.resetStore(new ask.PostgresQuestionStore(pool)); + assert.equal((await ask.personAsk({}, placed(c.message, c.numbers))).recorded, true, 'the PostgreSQL store behind the bus'); + assert.equal(pool.log.at(-1)[1][7], c.record); + } finally { + ask.resetStore(); + clear(); + await defaultRegistry.bus.close(); + await ask.shutdown(); + } +}); + +test('a whole number past a double in a decision reaches the engine and the record', async () => { + // a decision that carries such a number: the resume the engine receives and the answer on the row hold every digit + const c = VECTORS.exact_cases[0]; + const store = recorder(); + const clear = configure({ ...BASE, [ask.GRAPHS]: `ledger-assistant=${engineUrl}/api/graph/ledger-assistant` }); + try { + const event = ask.buildEvent(ask.validateMessage(placed(c.message, c.numbers)), Buffer.from(KEY), REPLY_URL); + await store.record(event, isoUtc()); + const ticket = ticketFor({ graph: event.graph_id, cid: event.correlation_id, turn: event.turn }); + const request = new AsyncHttpRequest().setMethod('POST').setUrl('/ask/reply').setBody({ ticket, decisions: placed(c.decisions, c.decision_numbers) }); + const reply = await ask.askReply({}, request.toMap()); + assert.equal(reply.getStatus(), 200, String(reply.body)); + for (const number of c.decision_numbers) assert.ok(engine.texts.at(-1).includes(`:${number.digits}`), engine.texts.at(-1)); + const rows = await store.since(0, 10); + assert.equal(rows[0].state, 'answered'); + for (const number of c.decision_numbers) assert.equal(String(at(rows[0].decisions, number.place)), number.digits); + } finally { + clear(); + await defaultRegistry.bus.close(); + await ask.shutdown(); + } +}); + test('a configured driver that is not installed stops the boot by name', async () => { const clear = configure({ ...BASE, [ask.AUDIT]: 'postgres' }); try { diff --git a/test/vectors/agent-question-vectors.json b/test/vectors/agent-question-vectors.json index 6196d473..365a5b4b 100644 --- a/test/vectors/agent-question-vectors.json +++ b/test/vectors/agent-question-vectors.json @@ -1,7 +1,7 @@ { "contract": "agent-question", - "version": 4, - "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full. Version 4 (the numbers a request names): row_id_cases pin the row a decision names in /questions/{id}/decide, and cursor_cases where a device's stream starts - its Last-Event-ID, else its since parameter, else the beginning. Each is one to nineteen ASCII digits from start to end and no larger than 9223372036854775807, the largest number the record's BIGINT id and seq columns hold; anything else is the exact 400. The number read is given as text, since a JSON number past 2^53 is not exact in every reader.", + "version": 6, + "description": "The agent-question app's shared vectors (RFC-0014, build plan steps 3 and 10): the pure half of extensions/agent-question, run by mercury-python and mercury-nodejs against the same file. Version 3 (round 4): the app reads the question record the main flow keeps and writes nothing - the row a message becomes, the state an answer leaves and the record's transitions moved to the ask-person vectors (version 2). intake_cases pin the event the intake accepts (what it answers the main flow) or the exact 400 that refuses it. click_cases pin the request the automated click sends to the reply endpoint the link names. feed_cases pin the pages the replay and the history read over a fixed set of rows: since(seq, limit) - the rows whose sequence passed the cursor, oldest first, with the cursor to continue from - and before(seq, limit) - the rows before the cursor, newest first, with the cursor of the older page (every row when the cursor is null); more says a page was full. Version 4 (the numbers a request names): row_id_cases pin the row a decision names in /questions/{id}/decide, and cursor_cases where a device's stream starts - its Last-Event-ID, else its since parameter, else the beginning. Each is one to nineteen ASCII digits from start to end and no larger than 9223372036854775807, the largest number the record's BIGINT id and seq columns hold; anything else is the exact 400. The number read is given as text, since a JSON number past 2^53 is not exact in every reader. Version 5 (one rule for a number, a duration and a switch; a row told by the number it has). number_cases and switch_cases are the ask-person vectors' (version 4), read by this app's own readers: a whole number, a duration in milliseconds, a switch. intake_cases gain a turn in each spelling the rule reads - the answer carries the whole number - and in spellings it refuses. list_cases pin what GET /questions asks for, from its parameters as the request wrote them: whether it pages back (before is named, though empty), the cursor - since and before are numbers of the record, read as a row id is, digits from start to end - and the page size, a whole number held between 1 and 1000; or the exact 400. page_size_cases pin a page size against a default and a most, as the transcripts' limit is read. exact_cases pin rows whose id and sequence are past 9007199254740991, with every id, sequence and cursor given as text, since a JSON number that large is not exact in every reader: the rows as the database holds them and the queries as feed_cases have them; a page holds the rows by the numbers they have, in their order, with the cursor to continue from, and what a client is sent carries every digit. Version 6 (one reader of a time; a turn the record holds; blank by one rule). time_cases and text_cases are the ask-person vectors' (version 5), read by this app's own readers: a time a caller supplies - the transcripts' before, an event's requested_at and expires_at - as the instant in milliseconds from 1970-01-01T00:00:00Z and the text both packs write for it, or null where the text is no time; and the white space around a text, the 24 characters of the number rule. intake_cases gain a requested_at and an expires_at in the spellings the rule reads and in spellings it refuses, the exact 400; a turn up to 2147483647, the largest the record's INTEGER column holds, and the 400 past it (the largest turn of version 5 was 9007199254740991); required texts that are blank, and texts of characters that are not white space.", "intake_cases": [ { "name": "an approval", @@ -408,815 +408,5940 @@ }, "status": 400, "error": "details must be text" + }, + { + "name": "a turn written as a float with a whole value is that turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.0, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn written in ASCII digits is that turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn with white space around its digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "\t2 ", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a turn of zero", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 0, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 0 + } + }, + { + "name": "the largest turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "an advice's turn written in ASCII digits", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "3", + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 3 + } + }, + { + "name": "a turn one past the largest", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a negative turn", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -1, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a fraction", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.5, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in Arabic-Indic digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "٢", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a plus sign", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "+2", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a point in text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2.0", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of empty text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn with a fraction", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3.5, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a requested_at at an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at to the minute", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at with a fraction of nine digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118999999Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an expires_at at an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T10:12:04.118+01:00", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an expires_at in the last second of the year 9999", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice's requested_at at an offset", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T10:40:12.004+01:00" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice with an expires_at that is no time: an advice has no expiry, and none is read", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": "never" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "a requested_at that is a word", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at without an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with a lower-case z", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with a space for the T", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19 09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at with white space around it", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": " 2026-11-19T09:12:04.118Z\n", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at on the 30th of February", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-30T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at to the hour", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at of empty text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "an advice's requested_at in the basic format", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "20261119T094012Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a requested_at that is a number is not text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": 1795079524, + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "requested_at must be text" + }, + { + "name": "an expires_at that is a word", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at without an offset", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at with a lower-case t", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21t09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at at hour 24", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T24:00:00Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at in the year 10000", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "10000-01-01T00:00:00.000Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at in the year 0000 at an offset that puts the instant in the year 0001", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "0000-12-31T23:30:00-01:00", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at as JavaScript writes the year 10000", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "+010000-01-01T00:00:00.000Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "calls that are empty are told before an expires_at that is no time", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "calls must be a non-empty list for an approval or a question" + }, + { + "name": "an expires_at that is no time is told before a requested_at that is none", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "an expires_at that is no time is told before details that are not text", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "tomorrow", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "details": 5 + }, + "status": 400, + "error": "expires_at must be an ISO-8601 time" + }, + { + "name": "details that are not text are told before a requested_at that is no time", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "yesterday", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "details": 5 + }, + "status": 400, + "error": "details must be text" + }, + { + "name": "graph_id of a no-break space", + "event": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "description of an ideographic space", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": " ", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "correlation_id of the line and the paragraph separator", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "

", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "correlation_id is required" + }, + { + "name": "summary of every white-space character", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\t\n\u000b\f\r              

   ", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of a byte order mark, a character of a name", + "event": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "", + "turn": 2 + } + }, + { + "name": "correlation_id of a next-line character, a character of a name", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "description of a file separator, a character of a name", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "an advice's summary of a unit separator, a character of a name", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "\u001f", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2 + } + }, + { + "name": "the largest turn, in ASCII digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483647", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "accepted": { + "accepted": true, + "kind": "approval", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "an advice's turn, the largest", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "accepted": { + "accepted": true, + "kind": "advice", + "graph_id": "order-assistant", + "turn": 2147483647 + } + }, + { + "name": "a turn one past the largest, in ASCII digits", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483648", + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of 4294967296", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 4294967296, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of the largest whole number", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740991, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest whole number", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740992, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn one past the largest", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + } + ], + "click_cases": [ + { + "name": "an approval with a note", + "link": "https://ask.example.test/ask/v1.payload.mac", + "ticket": "v1.payload.mac", + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "url": "https://ask.example.test/ask/reply", + "body": { + "ticket": "v1.payload.mac", + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "decided_by": "operator-17" + } + }, + { + "name": "a question's answer", + "link": "https://ask.example.test/ask/v1.plan.mac", + "ticket": "v1.plan.mac", + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "who": "owner-3", + "url": "https://ask.example.test/ask/reply", + "body": { + "ticket": "v1.plan.mac", + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "decided_by": "owner-3" + } + }, + { + "name": "a link on a path prefix", + "link": "https://gateway.example.test/agents/ask/v1.x.y", + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": false + } + ], + "who": "operator-17", + "url": "https://gateway.example.test/agents/ask/reply", + "body": { + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": false + } + ], + "decided_by": "operator-17" + } + }, + { + "name": "a link that is not a resume link", + "link": "https://ask.example.test/questions/app", + "ticket": "v1.x.y", + "decisions": [ + { + "id": "c1", + "approved": true + } + ], + "who": "operator-17", + "status": 409, + "error": "the row's link does not name a reply endpoint" + } + ], + "feed_cases": [ + { + "name": "the replay and the history over seven rows", + "rows": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered" + }, + { + "id": 2, + "seq": 2, + "kind": "advice", + "state": null + }, + { + "id": 3, + "seq": 5, + "kind": "question", + "state": "open" + }, + { + "id": 4, + "seq": 4, + "kind": "approval", + "state": "expired" + }, + { + "id": 5, + "seq": 7, + "kind": "approval", + "state": "open" + }, + { + "id": 6, + "seq": 6, + "kind": "advice", + "state": null + }, + { + "id": 7, + "seq": 1, + "kind": "approval", + "state": "answered" + } + ], + "queries": [ + { + "before": null, + "limit": 3, + "ids": [ + 5, + 6, + 3 + ], + "seqs": [ + 7, + 6, + 5 + ], + "next": 5, + "more": true + }, + { + "before": 5, + "limit": 3, + "ids": [ + 4, + 1, + 2 + ], + "seqs": [ + 4, + 3, + 2 + ], + "next": 2, + "more": true + }, + { + "before": 2, + "limit": 3, + "ids": [ + 7 + ], + "seqs": [ + 1 + ], + "next": 1, + "more": false + }, + { + "before": 1, + "limit": 3, + "ids": [], + "seqs": [], + "next": null, + "more": false + }, + { + "since": 4, + "limit": 10, + "ids": [ + 3, + 6, + 5 + ], + "seqs": [ + 5, + 6, + 7 + ], + "next": 7, + "more": false + }, + { + "since": 0, + "limit": 2, + "ids": [ + 7, + 2 + ], + "seqs": [ + 1, + 2 + ], + "next": 2, + "more": true + }, + { + "since": 7, + "limit": 5, + "ids": [], + "seqs": [], + "next": 7, + "more": false + } + ] + } + ], + "row_id_cases": [ + { + "name": "digits", + "id": "7", + "row": "7" + }, + { + "name": "zero", + "id": "0", + "row": "0" + }, + { + "name": "leading zeros are digits", + "id": "007", + "row": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "id": "0000000000000000007", + "row": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "id": "9007199254740993", + "row": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "id": "9223372036854775807", + "row": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "id": "9223372036854775808", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "nineteen nines", + "id": "9999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "twenty digits", + "id": "00000000000000000007", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "four hundred digits", + "id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before and after", + "id": " 7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space after", + "id": "7 ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space before", + "id": " 7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space alone", + "id": " ", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a newline after", + "id": "7\n", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a tab before", + "id": "\t7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a space between digits", + "id": "1 0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a minus sign", + "id": "-3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a plus sign", + "id": "+7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "minus zero", + "id": "-0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an underscore between digits", + "id": "1_0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a thousands separator", + "id": "1,000", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fraction", + "id": "1.0", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a decimal point alone", + "id": "1.", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an exponent", + "id": "1e3", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "id": "0x10", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a binary prefix", + "id": "0b11", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an octal prefix", + "id": "0o17", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a letter", + "id": "x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "digits then a letter", + "id": "7x", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word NaN", + "id": "NaN", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "the word Infinity", + "id": "Infinity", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "id": "٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "id": "७", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "id": "7", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "id": "𝟟", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "id": "²", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "id": "1٣", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "an empty id", + "id": "", + "status": 400, + "error": "the row id must be a whole number" + }, + { + "name": "no id", + "id": null, + "status": 400, + "error": "the row id must be a whole number" + } + ], + "cursor_cases": [ + { + "name": "digits", + "last_event_id": "7", + "since": null, + "cursor": "7" + }, + { + "name": "zero", + "last_event_id": "0", + "since": null, + "cursor": "0" + }, + { + "name": "leading zeros are digits", + "last_event_id": "007", + "since": null, + "cursor": "7" + }, + { + "name": "nineteen digits, as many as the largest number has", + "last_event_id": "0000000000000000007", + "since": null, + "cursor": "7" + }, + { + "name": "a number past the whole numbers a double holds exactly", + "last_event_id": "9007199254740993", + "since": null, + "cursor": "9007199254740993" + }, + { + "name": "the largest number a BIGINT column holds", + "last_event_id": "9223372036854775807", + "since": null, + "cursor": "9223372036854775807" + }, + { + "name": "one more than the largest number", + "last_event_id": "9223372036854775808", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "nineteen nines", + "last_event_id": "9999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "twenty digits", + "last_event_id": "00000000000000000007", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "four hundred digits", + "last_event_id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before and after", + "last_event_id": " 7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space after", + "last_event_id": "7 ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space before", + "last_event_id": " 7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space alone", + "last_event_id": " ", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a newline after", + "last_event_id": "7\n", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a tab before", + "last_event_id": "\t7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a space between digits", + "last_event_id": "1 0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a minus sign", + "last_event_id": "-3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a plus sign", + "last_event_id": "+7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "minus zero", + "last_event_id": "-0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an underscore between digits", + "last_event_id": "1_0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a thousands separator", + "last_event_id": "1,000", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fraction", + "last_event_id": "1.0", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a decimal point alone", + "last_event_id": "1.", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an exponent", + "last_event_id": "1e3", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a hexadecimal prefix", + "last_event_id": "0x10", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a binary prefix", + "last_event_id": "0b11", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an octal prefix", + "last_event_id": "0o17", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a letter", + "last_event_id": "x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "digits then a letter", + "last_event_id": "7x", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word NaN", + "last_event_id": "NaN", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "the word Infinity", + "last_event_id": "Infinity", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an Arabic-Indic digit (U+0663)", + "last_event_id": "٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a Devanagari digit (U+096D)", + "last_event_id": "७", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a fullwidth digit (U+FF17)", + "last_event_id": "7", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a mathematical double-struck digit (U+1D7DF)", + "last_event_id": "𝟟", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a superscript two (U+00B2)", + "last_event_id": "²", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "an ASCII digit then an Arabic-Indic one", + "last_event_id": "1٣", + "since": null, + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "no Last-Event-ID and no since: the beginning", + "last_event_id": null, + "since": null, + "cursor": "0" + }, + { + "name": "an empty Last-Event-ID is none", + "last_event_id": "", + "since": null, + "cursor": "0" + }, + { + "name": "since when there is no Last-Event-ID", + "last_event_id": null, + "since": "5", + "cursor": "5" + }, + { + "name": "since when the Last-Event-ID is empty", + "last_event_id": "", + "since": "5", + "cursor": "5" + }, + { + "name": "an empty since is none", + "last_event_id": null, + "since": "", + "cursor": "0" + }, + { + "name": "the Last-Event-ID wins over since", + "last_event_id": "7", + "since": "5", + "cursor": "7" + }, + { + "name": "a Last-Event-ID of zero wins over since", + "last_event_id": "0", + "since": "5", + "cursor": "0" + }, + { + "name": "a Last-Event-ID that is not a cursor is refused though since is one", + "last_event_id": "x", + "since": "5", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since that is not a cursor", + "last_event_id": null, + "since": "x", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a minus sign", + "last_event_id": null, + "since": "-3", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since with a fraction", + "last_event_id": null, + "since": "1.0", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since past the largest number", + "last_event_id": null, + "since": "9223372036854775808", + "status": 400, + "error": "Last-Event-ID must be a whole number" + }, + { + "name": "a since of the largest number", + "last_event_id": null, + "since": "9223372036854775807", + "cursor": "9223372036854775807" + } + ], + "number_cases": [ + { + "name": "ASCII digits", + "value": "512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a single digit", + "value": "1", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "zero as text", + "value": "0", + "whole": 0, + "duration_ms": 0 + }, + { + "name": "leading zeros", + "value": "007", + "whole": 7, + "duration_ms": 7000 + }, + { + "name": "forty leading zeros", + "value": "00000000000000000000000000000000000000001", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a tab and a newline around", + "value": "\t512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "no-break spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "an ideographic space before", + "value": " 512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a line separator before", + "value": "
512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a space inside", + "value": "5 12", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark after", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after", + "value": "512…", + "whole": null, + "duration_ms": null + }, + { + "name": "a file separator before", + "value": "\u001c512", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit separator after", + "value": "512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "a zero-width space before", + "value": "​512", + "whole": null, + "duration_ms": null + }, + { + "name": "empty text", + "value": "", + "whole": null, + "duration_ms": null + }, + { + "name": "blank text", + "value": " ", + "whole": null, + "duration_ms": null + }, + { + "name": "a plus sign", + "value": "+5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign", + "value": "-5", + "whole": null, + "duration_ms": null + }, + { + "name": "an underscore", + "value": "5_0", + "whole": null, + "duration_ms": null + }, + { + "name": "a point in text", + "value": "5.0", + "whole": null, + "duration_ms": null + }, + { + "name": "an exponent in text", + "value": "5e2", + "whole": null, + "duration_ms": null + }, + { + "name": "hexadecimal text", + "value": "0x10", + "whole": null, + "duration_ms": null + }, + { + "name": "a word", + "value": "five", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic digit", + "value": "٣", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic digits", + "value": "٥١٢", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then Arabic-Indic", + "value": "5٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth digits", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a Devanagari digit", + "value": "५", + "whole": null, + "duration_ms": null + }, + { + "name": "a mathematical bold digit", + "value": "𝟓", + "whole": null, + "duration_ms": null + }, + { + "name": "superscript two", + "value": "²", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then superscript", + "value": "5²", + "whole": null, + "duration_ms": null + }, + { + "name": "subscript two", + "value": "₂", + "whole": null, + "duration_ms": null + }, + { + "name": "a circled digit", + "value": "①", + "whole": null, + "duration_ms": null + }, + { + "name": "a vulgar fraction", + "value": "½", + "whole": null, + "duration_ms": null + }, + { + "name": "a Roman numeral", + "value": "Ⅷ", + "whole": null, + "duration_ms": null + }, + { + "name": "an ideographic number", + "value": "五", + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as text", + "value": "9007199254740991", + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest as text", + "value": "9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines", + "value": "99999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "four hundred nines", + "value": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "a number", + "value": 512, + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "zero", + "value": 0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative number", + "value": -5, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number", + "value": 9007199254740991, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest", + "value": 9007199254740992, + "whole": null, + "duration_ms": null + }, + { + "name": "a number of twenty nines", + "value": 99999999999999999999, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a whole value", + "value": 16000.0, + "whole": 16000, + "duration_ms": 16000000 + }, + { + "name": "float zero", + "value": 0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "negative zero", + "value": -0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative float with a whole value", + "value": -1.0, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a fraction", + "value": 2.5, + "whole": null, + "duration_ms": null + }, + { + "name": "a float just above a whole value", + "value": 5.000000000000001, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as a float", + "value": 9007199254740991.0, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "a float above the largest", + "value": 1e+16, + "whole": null, + "duration_ms": null + }, + { + "name": "a huge float", + "value": 1e+300, + "whole": null, + "duration_ms": null + }, + { + "name": "true", + "value": true, + "whole": null, + "duration_ms": null + }, + { + "name": "false", + "value": false, + "whole": null, + "duration_ms": null + }, + { + "name": "null", + "value": null, + "whole": null, + "duration_ms": null + }, + { + "name": "a list", + "value": [ + 5 + ], + "whole": null, + "duration_ms": null + }, + { + "name": "a map", + "value": { + "value": 5 + }, + "whole": null, + "duration_ms": null + }, + { + "name": "minutes", + "value": "30m", + "whole": null, + "duration_ms": 1800000 + }, + { + "name": "hours", + "value": "12h", + "whole": null, + "duration_ms": 43200000 + }, + { + "name": "days", + "value": "2d", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "seconds", + "value": "45s", + "whole": null, + "duration_ms": 45000 + }, + { + "name": "zero days", + "value": "0d", + "whole": null, + "duration_ms": 0 + }, + { + "name": "spaces around a duration", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "a space before the unit", + "value": "2 d", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case unit", + "value": "2D", + "whole": null, + "duration_ms": null + }, + { + "name": "an unknown unit", + "value": "2w", + "whole": null, + "duration_ms": null + }, + { + "name": "two units", + "value": "1d12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fraction of an hour", + "value": "1.5h", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit alone", + "value": "d", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic hours", + "value": "٣h", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth hours", + "value": "12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth unit", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before a duration", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after a duration", + "value": "2d…", + "whole": null, + "duration_ms": null + }, + { + "name": "days past the most milliseconds", + "value": "104249991374d", + "whole": null, + "duration_ms": null + }, + { + "name": "a day more past the most milliseconds", + "value": "104249991375d", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines of days", + "value": "99999999999999999999d", + "whole": null, + "duration_ms": null + }, + { + "name": "a range of pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages and ranges", + "value": "1-3,7", + "whole": null, + "duration_ms": null + }, + { + "name": "pages in the order named", + "value": "7,1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with spaces", + "value": " 2 - 3 , 1 ", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with no-break spaces", + "value": "1 - 3", + "whole": null, + "duration_ms": null + }, + { + "name": "two pages without a comma", + "value": "1 3", + "whole": null, + "duration_ms": null + }, + { + "name": "a space inside a page of a range", + "value": "1 0-12", + "whole": null, + "duration_ms": null + }, + { + "name": "line breaks around a hyphen", + "value": "1\n-\n3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a byte order mark", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a next-line character", + "value": "1…-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic page", + "value": "1-٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth hyphen", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an en dash", + "value": "1–3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range from page zero", + "value": "0-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range to the largest page", + "value": "1-9007199254740991", + "whole": null, + "duration_ms": null + }, + { + "name": "a range beyond the largest page", + "value": "1-9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "milliseconds", + "value": "500ms", + "whole": null, + "duration_ms": 500 + }, + { + "name": "zero milliseconds", + "value": "0ms", + "whole": null, + "duration_ms": 0 + }, + { + "name": "leading zeros and a unit", + "value": "007m", + "whole": null, + "duration_ms": 420000 + }, + { + "name": "spaces around milliseconds", + "value": " 250ms ", + "whole": null, + "duration_ms": 250 + }, + { + "name": "a space before ms", + "value": "500 ms", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case ms", + "value": "500MS", + "whole": null, + "duration_ms": null + }, + { + "name": "ms alone", + "value": "ms", + "whole": null, + "duration_ms": null + }, + { + "name": "ms then s", + "value": "5mss", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit before the number", + "value": "s5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign and a unit", + "value": "-5s", + "whole": null, + "duration_ms": null + }, + { + "name": "a float and a unit", + "value": "5.0s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most milliseconds", + "value": "9007199254740991ms", + "whole": null, + "duration_ms": 9007199254740991 + }, + { + "name": "one millisecond more", + "value": "9007199254740992ms", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds", + "value": "9007199254740s", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more", + "value": "9007199254741s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds without a unit", + "value": "9007199254740", + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more without a unit", + "value": "9007199254741", + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a number", + "value": 9007199254740, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more as a number", + "value": 9007199254741, + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a float", + "value": 9007199254740.0, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "the most minutes", + "value": "150119987579m", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one minute more", + "value": "150119987580m", + "whole": null, + "duration_ms": null + }, + { + "name": "the most hours", + "value": "2501999792h", + "whole": null, + "duration_ms": 9007199251200000 + }, + { + "name": "one hour more", + "value": "2501999793h", + "whole": null, + "duration_ms": null + }, + { + "name": "the most days", + "value": "104249991d", + "whole": null, + "duration_ms": 9007199222400000 + }, + { + "name": "one day more", + "value": "104249992d", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines of seconds", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999s", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0009 around a number, white space in both runtimes", + "value": "\t512\t", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000A around a number, white space in both runtimes", + "value": "\n512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000B around a number, white space in both runtimes", + "value": "\u000b512\u000b", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000C around a number, white space in both runtimes", + "value": "\f512\f", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000D around a number, white space in both runtimes", + "value": "\r512\r", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0020 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+00A0 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+1680 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2001 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2002 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2003 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2004 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2005 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2006 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2007 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2008 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2009 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+200A around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2028 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2029 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+202F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+205F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+3000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0009 around a duration, white space in both runtimes", + "value": "\t2d\t", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+00A0 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+2029 around a duration, white space in both runtimes", + "value": "
2d
", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+3000 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+001C around a number, white space in neither or in one runtime", + "value": "\u001c512\u001c", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001D around a number, white space in neither or in one runtime", + "value": "\u001d512\u001d", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001E around a number, white space in neither or in one runtime", + "value": "\u001e512\u001e", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001F around a number, white space in neither or in one runtime", + "value": "\u001f512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0085 around a number, white space in neither or in one runtime", + "value": "…512…", + "whole": null, + "duration_ms": null + }, + { + "name": "U+180E around a number, white space in neither or in one runtime", + "value": "᠎512᠎", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200B around a number, white space in neither or in one runtime", + "value": "​512​", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200C around a number, white space in neither or in one runtime", + "value": "‌512‌", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200D around a number, white space in neither or in one runtime", + "value": "‍512‍", + "whole": null, + "duration_ms": null + }, + { + "name": "U+2060 around a number, white space in neither or in one runtime", + "value": "⁠512⁠", + "whole": null, + "duration_ms": null + }, + { + "name": "U+FEFF around a number, white space in neither or in one runtime", + "value": "512", + "whole": null, + "duration_ms": null + } + ], + "switch_cases": [ + { + "name": "the boolean true", + "value": true, + "switch": true + }, + { + "name": "the boolean false", + "value": false, + "switch": false + }, + { + "name": "the text true", + "value": "true", + "switch": true + }, + { + "name": "the text false", + "value": "false", + "switch": false + }, + { + "name": "TRUE in upper case", + "value": "TRUE", + "switch": true + }, + { + "name": "FALSE in upper case", + "value": "FALSE", + "switch": false + }, + { + "name": "True with a capital", + "value": "True", + "switch": true + }, + { + "name": "False with a capital", + "value": "False", + "switch": false + }, + { + "name": "tRuE in mixed case", + "value": "tRuE", + "switch": true + }, + { + "name": "fAlSe in mixed case", + "value": "fAlSe", + "switch": false + }, + { + "name": "no value", + "value": null, + "switch": "default" + }, + { + "name": "an empty value", + "value": "", + "switch": "default" + }, + { + "name": "a blank value", + "value": " ", + "switch": null + }, + { + "name": "a space before true", + "value": " true", + "switch": null + }, + { + "name": "a space after true", + "value": "true ", + "switch": null + }, + { + "name": "a newline after false", + "value": "false\n", + "switch": null + }, + { + "name": "yes", + "value": "yes", + "switch": null + }, + { + "name": "no", + "value": "no", + "switch": null + }, + { + "name": "on", + "value": "on", + "switch": null + }, + { + "name": "off", + "value": "off", + "switch": null + }, + { + "name": "the text 1", + "value": "1", + "switch": null + }, + { + "name": "the text 0", + "value": "0", + "switch": null + }, + { + "name": "the letter t", + "value": "t", + "switch": null + }, + { + "name": "the letter f", + "value": "f", + "switch": null + }, + { + "name": "enabled", + "value": "enabled", + "switch": null + }, + { + "name": "maybe", + "value": "maybe", + "switch": null + }, + { + "name": "truefalse", + "value": "truefalse", + "switch": null + }, + { + "name": "the number 1", + "value": 1, + "switch": null + }, + { + "name": "the number 0", + "value": 0, + "switch": null + }, + { + "name": "the number 1.0", + "value": 1.0, + "switch": null + }, + { + "name": "a list holding true", + "value": [ + true + ], + "switch": null + }, + { + "name": "an empty list", + "value": [], + "switch": null + }, + { + "name": "a map", + "value": { + "value": true + }, + "switch": null + }, + { + "name": "fullwidth true", + "value": "true", + "switch": null + }, + { + "name": "true with a Cyrillic e", + "value": "truе", + "switch": null + }, + { + "name": "true with a dotted capital I after it", + "value": "trueİ", + "switch": null + } + ], + "list_cases": [ + { + "name": "nothing named: the replay from the beginning", + "query": {}, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since a cursor", + "query": { + "since": "5" + }, + "paging": false, + "cursor": "5", + "limit": 200 + }, + { + "name": "an empty since is the beginning", + "query": { + "since": "" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since zero", + "query": { + "since": "0" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "since with leading zeros", + "query": { + "since": "007" + }, + "paging": false, + "cursor": "7", + "limit": 200 + }, + { + "name": "since a number past the whole numbers a double holds exactly", + "query": { + "since": "9007199254740993" + }, + "paging": false, + "cursor": "9007199254740993", + "limit": 200 + }, + { + "name": "since the largest number the record holds", + "query": { + "since": "9223372036854775807" + }, + "paging": false, + "cursor": "9223372036854775807", + "limit": 200 + }, + { + "name": "since one past the largest number the record holds", + "query": { + "since": "9223372036854775808" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since twenty digits", + "query": { + "since": "00000000000000000007" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since in Arabic-Indic digits", + "query": { + "since": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since in fullwidth digits", + "query": { + "since": "3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since a superscript digit", + "query": { + "since": "³" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a space before and after", + "query": { + "since": " 5 " + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a newline after", + "query": { + "since": "5\n" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a plus sign", + "query": { + "since": "+5" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a minus sign", + "query": { + "since": "-5" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with a fraction", + "query": { + "since": "5.0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with an exponent", + "query": { + "since": "5e0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since with an underscore", + "query": { + "since": "5_0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "since a word", + "query": { + "since": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before, empty: the newest page", + "query": { + "before": "" + }, + "paging": true, + "cursor": null, + "limit": 200 + }, + { + "name": "before a cursor", + "query": { + "before": "5", + "limit": "3" + }, + "paging": true, + "cursor": "5", + "limit": 3 + }, + { + "name": "before zero", + "query": { + "before": "0" + }, + "paging": true, + "cursor": "0", + "limit": 200 + }, + { + "name": "before a number past the whole numbers a double holds exactly", + "query": { + "before": "9007199254740993" + }, + "paging": true, + "cursor": "9007199254740993", + "limit": 200 + }, + { + "name": "before the largest number the record holds", + "query": { + "before": "9223372036854775807" + }, + "paging": true, + "cursor": "9223372036854775807", + "limit": 200 + }, + { + "name": "before one past the largest number the record holds", + "query": { + "before": "9223372036854775808" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before in Arabic-Indic digits", + "query": { + "before": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before with a space around", + "query": { + "before": " 5 " + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before a word", + "query": { + "before": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "before is read, and since is not, when both are named", + "query": { + "before": "5", + "since": "2" + }, + "paging": true, + "cursor": "5", + "limit": 200 + }, + { + "name": "an empty before is the newest page though since is named", + "query": { + "before": "", + "since": "2" + }, + "paging": true, + "cursor": null, + "limit": 200 + }, + { + "name": "a since that is no number is not read when the request pages back", + "query": { + "before": "5", + "since": "x" + }, + "paging": true, + "cursor": "5", + "limit": 200 + }, + { + "name": "a before that is no number is refused though since is one", + "query": { + "before": "x", + "since": "2" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit", + "query": { + "since": "5", + "limit": "1" + }, + "paging": false, + "cursor": "5", + "limit": 1 + }, + { + "name": "an empty limit is the default", + "query": { + "limit": "" + }, + "paging": false, + "cursor": "0", + "limit": 200 + }, + { + "name": "a limit of zero is one row", + "query": { + "limit": "0" + }, + "paging": false, + "cursor": "0", + "limit": 1 + }, + { + "name": "a limit past the most a page takes", + "query": { + "limit": "5000" + }, + "paging": false, + "cursor": "0", + "limit": 1000 + }, + { + "name": "the largest whole number as a limit", + "query": { + "limit": "9007199254740991" + }, + "paging": false, + "cursor": "0", + "limit": 1000 + }, + { + "name": "a limit one past the largest whole number", + "query": { + "limit": "9007199254740992" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit of twenty nines", + "query": { + "limit": "99999999999999999999" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with white space around it", + "query": { + "limit": " 3\t" + }, + "paging": false, + "cursor": "0", + "limit": 3 + }, + { + "name": "a limit with leading zeros", + "query": { + "limit": "007" + }, + "paging": false, + "cursor": "0", + "limit": 7 + }, + { + "name": "a limit in Arabic-Indic digits", + "query": { + "limit": "٣" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a plus sign", + "query": { + "limit": "+3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a minus sign", + "query": { + "limit": "-3" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a fraction", + "query": { + "limit": "3.0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit with a space inside", + "query": { + "limit": "1 0" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit that is a word", + "query": { + "limit": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a limit that is no number is refused when the request pages back", + "query": { + "before": "", + "limit": "x" + }, + "status": 400, + "error": "since, before and limit must be whole numbers" + }, + { + "name": "a parameter the entry does not know is not read", + "query": { + "since": "5", + "order": "x" + }, + "paging": false, + "cursor": "5", + "limit": 200 } ], - "click_cases": [ + "page_size_cases": [ { - "name": "an approval with a note", - "link": "https://ask.example.test/ask/v1.payload.mac", - "ticket": "v1.payload.mac", - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "who": "operator-17", - "url": "https://ask.example.test/ask/reply", - "body": { - "ticket": "v1.payload.mac", - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "decided_by": "operator-17" - } + "name": "no limit is the default", + "limit": null, + "default": 50, + "most": 200, + "size": 50 }, { - "name": "a question's answer", - "link": "https://ask.example.test/ask/v1.plan.mac", - "ticket": "v1.plan.mac", - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ], - "who": "owner-3", - "url": "https://ask.example.test/ask/reply", - "body": { - "ticket": "v1.plan.mac", - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ], - "decided_by": "owner-3" - } + "name": "an empty limit is the default", + "limit": "", + "default": 50, + "most": 200, + "size": 50 }, { - "name": "a link on a path prefix", - "link": "https://gateway.example.test/agents/ask/v1.x.y", - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": false - } - ], - "who": "operator-17", - "url": "https://gateway.example.test/agents/ask/reply", - "body": { - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": false - } - ], - "decided_by": "operator-17" - } + "name": "a limit", + "limit": "7", + "default": 50, + "most": 200, + "size": 7 }, { - "name": "a link that is not a resume link", - "link": "https://ask.example.test/questions/app", - "ticket": "v1.x.y", - "decisions": [ - { - "id": "c1", - "approved": true - } - ], - "who": "operator-17", - "status": 409, - "error": "the row's link does not name a reply endpoint" + "name": "a limit of zero is one", + "limit": "0", + "default": 50, + "most": 200, + "size": 1 + }, + { + "name": "a limit past the most", + "limit": "500", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "the most", + "limit": "200", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "one past the most", + "limit": "201", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "the largest whole number", + "limit": "9007199254740991", + "default": 50, + "most": 200, + "size": 200 + }, + { + "name": "one past the largest whole number", + "limit": "9007199254740992", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "four hundred nines", + "limit": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "white space around it", + "limit": " 7\n", + "default": 50, + "most": 200, + "size": 7 + }, + { + "name": "leading zeros", + "limit": "007", + "default": 50, + "most": 200, + "size": 7 + }, + { + "name": "Arabic-Indic digits", + "limit": "٧", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "fullwidth digits", + "limit": "7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a plus sign", + "limit": "+7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a minus sign", + "limit": "-7", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a fraction", + "limit": "7.0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "an exponent", + "limit": "7e0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "an underscore", + "limit": "7_0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a space inside", + "limit": "7 0", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a word", + "limit": "seven", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a blank", + "limit": " ", + "default": 50, + "most": 200, + "size": null + }, + { + "name": "a byte order mark before", + "limit": "7", + "default": 50, + "most": 200, + "size": null } ], - "feed_cases": [ + "exact_cases": [ { - "name": "the replay and the history over seven rows", + "name": "five rows whose ids and sequences are past the whole numbers a double holds exactly", "rows": [ { - "id": 1, - "seq": 3, + "id": "9007199254740993", + "seq": "9223372036854775806", "kind": "approval", - "state": "answered" + "state": "open" }, { - "id": 2, - "seq": 2, + "id": "9007199254740992", + "seq": "9007199254740993", "kind": "advice", "state": null }, { - "id": 3, - "seq": 5, + "id": "9223372036854775807", + "seq": "9007199254740992", "kind": "question", "state": "open" }, { - "id": 4, - "seq": 4, - "kind": "approval", - "state": "expired" - }, - { - "id": 5, - "seq": 7, + "id": "7", + "seq": "9007199254740991", "kind": "approval", - "state": "open" - }, - { - "id": 6, - "seq": 6, - "kind": "advice", - "state": null + "state": "answered" }, { - "id": 7, - "seq": 1, + "id": "9007199254740994", + "seq": "9223372036854775807", "kind": "approval", - "state": "answered" + "state": "expired" } ], "queries": [ { - "before": null, - "limit": 3, + "since": "0", + "limit": 10, + "ids": [ + "7", + "9223372036854775807", + "9007199254740992", + "9007199254740993", + "9007199254740994" + ], + "seqs": [ + "9007199254740991", + "9007199254740992", + "9007199254740993", + "9223372036854775806", + "9223372036854775807" + ], + "next": "9223372036854775807", + "more": false + }, + { + "since": "9007199254740991", + "limit": 2, "ids": [ - 5, - 6, - 3 + "9223372036854775807", + "9007199254740992" ], "seqs": [ - 7, - 6, - 5 + "9007199254740992", + "9007199254740993" ], - "next": 5, + "next": "9007199254740993", "more": true }, { - "before": 5, - "limit": 3, + "since": "9007199254740992", + "limit": 2, "ids": [ - 4, - 1, - 2 + "9007199254740992", + "9007199254740993" ], "seqs": [ - 4, - 3, - 2 + "9007199254740993", + "9223372036854775806" ], - "next": 2, + "next": "9223372036854775806", "more": true }, { - "before": 2, - "limit": 3, + "since": "9223372036854775806", + "limit": 5, "ids": [ - 7 + "9007199254740994" ], "seqs": [ - 1 + "9223372036854775807" ], - "next": 1, + "next": "9223372036854775807", "more": false }, { - "before": 1, - "limit": 3, + "since": "9223372036854775807", + "limit": 5, "ids": [], "seqs": [], - "next": null, + "next": "9223372036854775807", "more": false }, { - "since": 4, - "limit": 10, + "before": null, + "limit": 2, "ids": [ - 3, - 6, - 5 + "9007199254740994", + "9007199254740993" ], "seqs": [ - 5, - 6, - 7 + "9223372036854775807", + "9223372036854775806" ], - "next": 7, - "more": false + "next": "9223372036854775806", + "more": true }, { - "since": 0, + "before": "9223372036854775807", "limit": 2, "ids": [ - 7, - 2 + "9007199254740993", + "9007199254740992" ], "seqs": [ - 1, - 2 + "9223372036854775806", + "9007199254740993" ], - "next": 2, + "next": "9007199254740993", "more": true }, { - "since": 7, + "before": "9223372036854775806", + "limit": 2, + "ids": [ + "9007199254740992", + "9223372036854775807" + ], + "seqs": [ + "9007199254740993", + "9007199254740992" + ], + "next": "9007199254740992", + "more": true + }, + { + "before": "9007199254740993", + "limit": 5, + "ids": [ + "9223372036854775807", + "7" + ], + "seqs": [ + "9007199254740992", + "9007199254740991" + ], + "next": "9007199254740991", + "more": false + }, + { + "before": "9007199254740992", + "limit": 5, + "ids": [ + "7" + ], + "seqs": [ + "9007199254740991" + ], + "next": "9007199254740991", + "more": false + }, + { + "before": "9007199254740991", "limit": 5, "ids": [], "seqs": [], - "next": 7, + "next": null, "more": false } - ] + ], + "latest": "9223372036854775807" } ], - "row_id_cases": [ + "time_cases": [ + { + "name": "a time in UTC to the second", + "text": "2026-11-20T10:00:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a time in UTC to the millisecond", + "text": "2026-11-20T10:00:00.123Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a time in UTC to the minute", + "text": "2026-11-20T10:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a fraction of one digit", + "text": "2026-11-20T10:00:00.1Z", + "ms": 1795168800100, + "stamp": "2026-11-20T10:00:00.100Z" + }, + { + "name": "a fraction of two digits", + "text": "2026-11-20T10:00:00.12Z", + "ms": 1795168800120, + "stamp": "2026-11-20T10:00:00.120Z" + }, + { + "name": "a fraction of six digits is cut after the third", + "text": "2026-11-20T10:00:00.123456Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction of nine digits is cut after the third", + "text": "2026-11-20T10:00:00.123456789Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction that would round up is cut", + "text": "2026-11-20T10:00:00.9996Z", + "ms": 1795168800999, + "stamp": "2026-11-20T10:00:00.999Z" + }, + { + "name": "a fraction of nine nines", + "text": "2026-11-20T23:59:59.999999999Z", + "ms": 1795219199999, + "stamp": "2026-11-20T23:59:59.999Z" + }, + { + "name": "a fraction of zeros", + "text": "2026-11-20T10:00:00.000Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset ahead of UTC", + "text": "2026-11-20T10:00:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset behind UTC", + "text": "2026-11-20T10:00:00-08:00", + "ms": 1795197600000, + "stamp": "2026-11-20T18:00:00.000Z" + }, + { + "name": "an offset of half an hour", + "text": "2026-11-20T10:00:00+05:30", + "ms": 1795149000000, + "stamp": "2026-11-20T04:30:00.000Z" + }, + { + "name": "an offset of three quarters of an hour", + "text": "2026-11-20T10:00:00.5+05:45", + "ms": 1795148100500, + "stamp": "2026-11-20T04:15:00.500Z" + }, + { + "name": "the largest offset ahead of UTC", + "text": "2026-11-20T10:00:00+23:59", + "ms": 1795082460000, + "stamp": "2026-11-19T10:01:00.000Z" + }, + { + "name": "the largest offset behind UTC", + "text": "2026-11-20T10:00:00-23:59", + "ms": 1795255140000, + "stamp": "2026-11-21T09:59:00.000Z" + }, + { + "name": "an offset of plus nothing", + "text": "2026-11-20T10:00:00+00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset of minus nothing", + "text": "2026-11-20T10:00:00-00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "to the minute at an offset", + "text": "2026-11-20T10:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year before", + "text": "2026-01-01T00:30:00+01:00", + "ms": 1767223800000, + "stamp": "2025-12-31T23:30:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year after", + "text": "2026-12-31T23:30:00-01:00", + "ms": 1798763400000, + "stamp": "2027-01-01T00:30:00.000Z" + }, + { + "name": "an offset that crosses the 29th of February", + "text": "2024-03-01T00:00:00+00:01", + "ms": 1709251140000, + "stamp": "2024-02-29T23:59:00.000Z" + }, + { + "name": "midnight", + "text": "2026-11-20T00:00:00Z", + "ms": 1795132800000, + "stamp": "2026-11-20T00:00:00.000Z" + }, + { + "name": "the last second of a day", + "text": "2026-11-20T23:59:59Z", + "ms": 1795219199000, + "stamp": "2026-11-20T23:59:59.000Z" + }, + { + "name": "the 29th of February of a leap year", + "text": "2024-02-29T12:00:00Z", + "ms": 1709208000000, + "stamp": "2024-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 2000", + "text": "2000-02-29T12:00:00Z", + "ms": 951825600000, + "stamp": "2000-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 0004", + "text": "0004-02-29T12:00:00Z", + "ms": -62035848000000, + "stamp": "0004-02-29T12:00:00.000Z" + }, + { + "name": "the 31st of January", + "text": "2026-01-31T12:00:00Z", + "ms": 1769860800000, + "stamp": "2026-01-31T12:00:00.000Z" + }, + { + "name": "the 30th of April", + "text": "2026-04-30T12:00:00Z", + "ms": 1777550400000, + "stamp": "2026-04-30T12:00:00.000Z" + }, + { + "name": "the 31st of December", + "text": "2026-12-31T12:00:00Z", + "ms": 1798718400000, + "stamp": "2026-12-31T12:00:00.000Z" + }, + { + "name": "the first instant of 1970", + "text": "1970-01-01T00:00:00Z", + "ms": 0, + "stamp": "1970-01-01T00:00:00.000Z" + }, + { + "name": "an instant before 1970", + "text": "1969-12-31T23:59:59.250Z", + "ms": -750, + "stamp": "1969-12-31T23:59:59.250Z" + }, + { + "name": "a year before 1000", + "text": "0999-12-31T23:59:59Z", + "ms": -30610224001000, + "stamp": "0999-12-31T23:59:59.000Z" + }, + { + "name": "a year of two significant digits", + "text": "0033-04-03T15:00:00+02:00", + "ms": -61117758000000, + "stamp": "0033-04-03T13:00:00.000Z" + }, + { + "name": "the first instant both packs write", + "text": "0001-01-01T00:00:00Z", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant both packs write", + "text": "9999-12-31T23:59:59.999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the last instant, with a longer fraction", + "text": "9999-12-31T23:59:59.999999999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written at an offset", + "text": "0001-01-01T00:01:00+00:01", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written at an offset", + "text": "9999-12-31T23:58:59.999-00:01", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written a day later at the largest offset", + "text": "0001-01-01T23:59:00+23:59", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written a day earlier at the largest offset", + "text": "9999-12-31T00:00:59.999-23:59", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "no offset", + "text": "2026-11-20T10:00:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, to the minute", + "text": "2026-11-20T10:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, with a fraction", + "text": "2026-11-20T10:00:00.123", + "ms": null, + "stamp": null + }, + { + "name": "a date alone", + "text": "2026-11-20", + "ms": null, + "stamp": null + }, + { + "name": "a time alone", + "text": "10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case t", + "text": "2026-11-20t10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case z", + "text": "2026-11-20T10:00:00z", + "ms": null, + "stamp": null + }, + { + "name": "a space for the T", + "text": "2026-11-20 10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an underscore for the T", + "text": "2026-11-20_10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space before", + "text": " 2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a newline after", + "text": "2026-11-20T10:00:00Z\n", + "ms": null, + "stamp": null + }, + { + "name": "a carriage return and a newline after", + "text": "2026-11-20T10:00:00Z\r\n", + "ms": null, + "stamp": null + }, + { + "name": "a tab before", + "text": "\t2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a no-break space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a byte order mark before", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a next-line character after", + "text": "2026-11-20T10:00:00Z…", + "ms": null, + "stamp": null + }, + { + "name": "a NUL after", + "text": "2026-11-20T10:00:00Z\u0000", + "ms": null, + "stamp": null + }, + { + "name": "a space before the offset", + "text": "2026-11-20T10:00:00 +01:00", + "ms": null, + "stamp": null + }, + { + "name": "a space before the Z", + "text": "2026-11-20T10:00:00 Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format", + "text": "20261120T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format of the time alone", + "text": "2026-11-20T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "a week date", + "text": "2026-W47-5", + "ms": null, + "stamp": null + }, + { + "name": "a week date with a time", + "text": "2026-W47-5T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an ordinal date", + "text": "2026-324T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the hour alone", + "text": "2026-11-20T10Z", + "ms": null, + "stamp": null + }, + { + "name": "a comma for the point", + "text": "2026-11-20T10:00:00,5Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of the minute", + "text": "2026-11-20T10:00.5Z", + "ms": null, + "stamp": null + }, + { + "name": "a point without digits", + "text": "2026-11-20T10:00:00.Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of ten digits", + "text": "2026-11-20T10:00:00.1234567891Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset in hours alone", + "text": "2026-11-20T10:00:00+01", + "ms": null, + "stamp": null + }, + { + "name": "an offset without its colon", + "text": "2026-11-20T10:00:00+0100", + "ms": null, + "stamp": null + }, + { + "name": "an offset with seconds", + "text": "2026-11-20T10:00:00+01:00:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset of one digit an hour", + "text": "2026-11-20T10:00:00+1:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset without a sign", + "text": "2026-11-20T10:00:0001:00", + "ms": null, + "stamp": null + }, + { + "name": "a zone's name after the offset", + "text": "2026-11-20T10:00:00+01:00[Europe/Paris]", + "ms": null, + "stamp": null + }, + { + "name": "a Z and an offset", + "text": "2026-11-20T10:00:00Z+01:00", + "ms": null, + "stamp": null + }, + { + "name": "two Zs", + "text": "2026-11-20T10:00:00ZZ", + "ms": null, + "stamp": null + }, + { + "name": "UTC for the Z", + "text": "2026-11-20T10:00:00UTC", + "ms": null, + "stamp": null + }, + { + "name": "GMT after a space", + "text": "2026-11-20T10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date of the HTTP kind", + "text": "Fri, 20 Nov 2026 10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date with slashes", + "text": "2026/11/20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a date with points", + "text": "2026.11.20T10:00:00Z", + "ms": null, + "stamp": null + }, { - "name": "digits", - "id": "7", - "row": "7" + "name": "the day before the month", + "text": "20-11-2026T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "zero", - "id": "0", - "row": "0" + "name": "a time with points", + "text": "2026-11-20T10.00.00Z", + "ms": null, + "stamp": null }, { - "name": "leading zeros are digits", - "id": "007", - "row": "7" + "name": "the seconds from 1970 in digits", + "text": "1795168800", + "ms": null, + "stamp": null }, { - "name": "nineteen digits, as many as the largest number has", - "id": "0000000000000000007", - "row": "7" + "name": "the milliseconds from 1970 in digits", + "text": "1795168800000", + "ms": null, + "stamp": null }, { - "name": "a number past the whole numbers a double holds exactly", - "id": "9007199254740993", - "row": "9007199254740993" + "name": "a word", + "text": "yesterday", + "ms": null, + "stamp": null }, { - "name": "the largest number a BIGINT column holds", - "id": "9223372036854775807", - "row": "9223372036854775807" + "name": "the word now", + "text": "now", + "ms": null, + "stamp": null }, { - "name": "one more than the largest number", - "id": "9223372036854775808", - "status": 400, - "error": "the row id must be a whole number" + "name": "empty text", + "text": "", + "ms": null, + "stamp": null }, { - "name": "nineteen nines", - "id": "9999999999999999999", - "status": 400, - "error": "the row id must be a whole number" + "name": "a T alone", + "text": "T", + "ms": null, + "stamp": null }, { - "name": "twenty digits", - "id": "00000000000000000007", - "status": 400, - "error": "the row id must be a whole number" + "name": "two times", + "text": "2026-11-20T10:00:00Z2026-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "four hundred digits", - "id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", - "status": 400, - "error": "the row id must be a whole number" + "name": "a time and a word", + "text": "2026-11-20T10:00:00Z tomorrow", + "ms": null, + "stamp": null }, { - "name": "a space before and after", - "id": " 7 ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 30th of February", + "text": "2026-02-30T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space after", - "id": "7 ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of a common year", + "text": "2026-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space before", - "id": " 7", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of the year 1900", + "text": "1900-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space alone", - "id": " ", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 29th of February of the year 2100", + "text": "2100-02-29T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a newline after", - "id": "7\n", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 31st of April", + "text": "2026-04-31T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a tab before", - "id": "\t7", - "status": 400, - "error": "the row id must be a whole number" + "name": "the 31st of November", + "text": "2026-11-31T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a space between digits", - "id": "1 0", - "status": 400, - "error": "the row id must be a whole number" + "name": "a month of nothing", + "text": "2026-00-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a minus sign", - "id": "-3", - "status": 400, - "error": "the row id must be a whole number" + "name": "a thirteenth month", + "text": "2026-13-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a plus sign", - "id": "+7", - "status": 400, - "error": "the row id must be a whole number" + "name": "a day of nothing", + "text": "2026-11-00T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "minus zero", - "id": "-0", - "status": 400, - "error": "the row id must be a whole number" + "name": "a 32nd day", + "text": "2026-11-32T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "an underscore between digits", - "id": "1_0", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 24, minute nothing", + "text": "2026-11-20T24:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a thousands separator", - "id": "1,000", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 24", + "text": "2026-11-20T24:30:00Z", + "ms": null, + "stamp": null }, { - "name": "a fraction", - "id": "1.0", - "status": 400, - "error": "the row id must be a whole number" + "name": "hour 25", + "text": "2026-11-20T25:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a decimal point alone", - "id": "1.", - "status": 400, - "error": "the row id must be a whole number" + "name": "minute 60", + "text": "2026-11-20T10:60:00Z", + "ms": null, + "stamp": null }, { - "name": "an exponent", - "id": "1e3", - "status": 400, - "error": "the row id must be a whole number" + "name": "second 60, a leap second", + "text": "2026-12-31T23:59:60Z", + "ms": null, + "stamp": null }, { - "name": "a hexadecimal prefix", - "id": "0x10", - "status": 400, - "error": "the row id must be a whole number" + "name": "second 61", + "text": "2026-11-20T10:00:61Z", + "ms": null, + "stamp": null }, { - "name": "a binary prefix", - "id": "0b11", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset of 24 hours", + "text": "2026-11-20T10:00:00+24:00", + "ms": null, + "stamp": null }, { - "name": "an octal prefix", - "id": "0o17", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset with 60 minutes", + "text": "2026-11-20T10:00:00+01:60", + "ms": null, + "stamp": null }, { - "name": "a letter", - "id": "x", - "status": 400, - "error": "the row id must be a whole number" + "name": "an offset of 99 hours", + "text": "2026-11-20T10:00:00-99:59", + "ms": null, + "stamp": null }, { - "name": "digits then a letter", - "id": "7x", - "status": 400, - "error": "the row id must be a whole number" + "name": "the year nothing", + "text": "0000-01-01T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "the word NaN", - "id": "NaN", - "status": 400, - "error": "the row id must be a whole number" + "name": "the last day of the year nothing", + "text": "0000-12-31T23:59:59Z", + "ms": null, + "stamp": null }, { - "name": "the word Infinity", - "id": "Infinity", - "status": 400, - "error": "the row id must be a whole number" + "name": "the year nothing, at an offset that puts the instant in the year 0001", + "text": "0000-12-31T23:30:00-01:00", + "ms": null, + "stamp": null }, { - "name": "an Arabic-Indic digit (U+0663)", - "id": "٣", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of five digits", + "text": "10000-01-01T00:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a Devanagari digit (U+096D)", - "id": "७", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of six digits with a sign", + "text": "+002026-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a fullwidth digit (U+FF17)", - "id": "7", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year before nothing", + "text": "-0001-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a mathematical double-struck digit (U+1D7DF)", - "id": "𝟟", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of two digits", + "text": "26-11-20T10:00:00Z", + "ms": null, + "stamp": null }, { - "name": "a superscript two (U+00B2)", - "id": "²", - "status": 400, - "error": "the row id must be a whole number" + "name": "a year of three digits", + "text": "999-12-31T23:59:59Z", + "ms": null, + "stamp": null }, { - "name": "an ASCII digit then an Arabic-Indic one", - "id": "1٣", - "status": 400, - "error": "the row id must be a whole number" + "name": "a month of one digit", + "text": "2026-1-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of one digit", + "text": "2026-11-2T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an hour of one digit", + "text": "2026-11-20T9:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minute of one digit", + "text": "2026-11-20T10:0:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a second of one digit", + "text": "2026-11-20T10:00:0Z", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts before the year 0001", + "text": "0001-01-01T00:00:00+00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day before the year 0001", + "text": "0001-01-01T23:58:59.999+23:59", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts past the year 9999", + "text": "9999-12-31T23:59:59-00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day past the year 9999", + "text": "9999-12-31T00:01:00-23:59", + "ms": null, + "stamp": null + }, + { + "name": "Arabic-Indic digits in the year", + "text": "٢٠٢٦-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an Arabic-Indic digit in the second", + "text": "2026-11-20T10:00:0٠Z", + "ms": null, + "stamp": null + }, + { + "name": "fullwidth digits in the day", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the fraction", + "text": "2026-11-20T10:00:00.1Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the offset", + "text": "2026-11-20T10:00:00+01:00", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth colon", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth T", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth Z", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minus sign of the mathematical kind in the offset", + "text": "2026-11-20T10:00:00−01:00", + "ms": null, + "stamp": null + }, + { + "name": "an en dash in the date", + "text": "2026–11–20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a superscript digit", + "text": "2026-11-20T10:00:0²Z", + "ms": null, + "stamp": null + }, + { + "name": "a lone surrogate after", + "text": "2026-11-20T10:00:00Z\ud800", + "ms": null, + "stamp": null + } + ], + "text_cases": [ + { + "name": "empty text", + "text": "", + "trimmed": "", + "blank": true + }, + { + "name": "a name", + "text": "order-assistant", + "trimmed": "order-assistant", + "blank": false + }, + { + "name": "a name with a space inside", + "text": "order assistant", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "U+0009 alone, white space in both runtimes", + "text": "\t", + "trimmed": "", + "blank": true + }, + { + "name": "U+0009 around a name, white space in both runtimes", + "text": "\tname\t", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000A alone, white space in both runtimes", + "text": "\n", + "trimmed": "", + "blank": true + }, + { + "name": "U+000A around a name, white space in both runtimes", + "text": "\nname\n", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000B alone, white space in both runtimes", + "text": "\u000b", + "trimmed": "", + "blank": true + }, + { + "name": "U+000B around a name, white space in both runtimes", + "text": "\u000bname\u000b", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000C alone, white space in both runtimes", + "text": "\f", + "trimmed": "", + "blank": true + }, + { + "name": "U+000C around a name, white space in both runtimes", + "text": "\fname\f", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000D alone, white space in both runtimes", + "text": "\r", + "trimmed": "", + "blank": true + }, + { + "name": "U+000D around a name, white space in both runtimes", + "text": "\rname\r", + "trimmed": "name", + "blank": false + }, + { + "name": "U+0020 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+0020 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+00A0 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+00A0 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+1680 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+1680 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2001 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2001 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2002 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2002 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2003 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2003 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2004 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2004 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2005 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2005 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2006 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2006 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2007 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2007 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "an empty id", - "id": "", - "status": 400, - "error": "the row id must be a whole number" + "name": "U+2008 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "no id", - "id": null, - "status": 400, - "error": "the row id must be a whole number" - } - ], - "cursor_cases": [ + "name": "U+2008 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, { - "name": "digits", - "last_event_id": "7", - "since": null, - "cursor": "7" + "name": "U+2009 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "zero", - "last_event_id": "0", - "since": null, - "cursor": "0" + "name": "U+2009 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "leading zeros are digits", - "last_event_id": "007", - "since": null, - "cursor": "7" + "name": "U+200A alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "nineteen digits, as many as the largest number has", - "last_event_id": "0000000000000000007", - "since": null, - "cursor": "7" + "name": "U+200A around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a number past the whole numbers a double holds exactly", - "last_event_id": "9007199254740993", - "since": null, - "cursor": "9007199254740993" + "name": "U+2028 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true }, { - "name": "the largest number a BIGINT column holds", - "last_event_id": "9223372036854775807", - "since": null, - "cursor": "9223372036854775807" + "name": "U+2028 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false }, { - "name": "one more than the largest number", - "last_event_id": "9223372036854775808", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2029 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true }, { - "name": "nineteen nines", - "last_event_id": "9999999999999999999", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2029 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false }, { - "name": "twenty digits", - "last_event_id": "00000000000000000007", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+202F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "four hundred digits", - "last_event_id": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+202F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a space before and after", - "last_event_id": " 7 ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+205F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a space after", - "last_event_id": "7 ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+205F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a space before", - "last_event_id": " 7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+3000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a space alone", - "last_event_id": " ", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+3000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false }, { - "name": "a newline after", - "last_event_id": "7\n", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001C alone, a character of a name", + "text": "\u001c", + "trimmed": "\u001c", + "blank": false }, { - "name": "a tab before", - "last_event_id": "\t7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001C around a name, a character of a name", + "text": "\u001cname\u001c", + "trimmed": "\u001cname\u001c", + "blank": false }, { - "name": "a space between digits", - "last_event_id": "1 0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001D alone, a character of a name", + "text": "\u001d", + "trimmed": "\u001d", + "blank": false }, { - "name": "a minus sign", - "last_event_id": "-3", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001D around a name, a character of a name", + "text": "\u001dname\u001d", + "trimmed": "\u001dname\u001d", + "blank": false }, { - "name": "a plus sign", - "last_event_id": "+7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001E alone, a character of a name", + "text": "\u001e", + "trimmed": "\u001e", + "blank": false }, { - "name": "minus zero", - "last_event_id": "-0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001E around a name, a character of a name", + "text": "\u001ename\u001e", + "trimmed": "\u001ename\u001e", + "blank": false }, { - "name": "an underscore between digits", - "last_event_id": "1_0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001F alone, a character of a name", + "text": "\u001f", + "trimmed": "\u001f", + "blank": false }, { - "name": "a thousands separator", - "last_event_id": "1,000", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+001F around a name, a character of a name", + "text": "\u001fname\u001f", + "trimmed": "\u001fname\u001f", + "blank": false }, { - "name": "a fraction", - "last_event_id": "1.0", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0085 alone, a character of a name", + "text": "…", + "trimmed": "…", + "blank": false }, { - "name": "a decimal point alone", - "last_event_id": "1.", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0085 around a name, a character of a name", + "text": "…name…", + "trimmed": "…name…", + "blank": false }, { - "name": "an exponent", - "last_event_id": "1e3", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+FEFF alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false }, { - "name": "a hexadecimal prefix", - "last_event_id": "0x10", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+FEFF around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false }, { - "name": "a binary prefix", - "last_event_id": "0b11", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+180E alone, a character of a name", + "text": "᠎", + "trimmed": "᠎", + "blank": false }, { - "name": "an octal prefix", - "last_event_id": "0o17", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+180E around a name, a character of a name", + "text": "᠎name᠎", + "trimmed": "᠎name᠎", + "blank": false }, { - "name": "a letter", - "last_event_id": "x", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200B alone, a character of a name", + "text": "​", + "trimmed": "​", + "blank": false }, { - "name": "digits then a letter", - "last_event_id": "7x", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200B around a name, a character of a name", + "text": "​name​", + "trimmed": "​name​", + "blank": false }, { - "name": "the word NaN", - "last_event_id": "NaN", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200C alone, a character of a name", + "text": "‌", + "trimmed": "‌", + "blank": false }, { - "name": "the word Infinity", - "last_event_id": "Infinity", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200C around a name, a character of a name", + "text": "‌name‌", + "trimmed": "‌name‌", + "blank": false }, { - "name": "an Arabic-Indic digit (U+0663)", - "last_event_id": "٣", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200D alone, a character of a name", + "text": "‍", + "trimmed": "‍", + "blank": false }, { - "name": "a Devanagari digit (U+096D)", - "last_event_id": "७", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+200D around a name, a character of a name", + "text": "‍name‍", + "trimmed": "‍name‍", + "blank": false }, { - "name": "a fullwidth digit (U+FF17)", - "last_event_id": "7", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2060 alone, a character of a name", + "text": "⁠", + "trimmed": "⁠", + "blank": false }, { - "name": "a mathematical double-struck digit (U+1D7DF)", - "last_event_id": "𝟟", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+2060 around a name, a character of a name", + "text": "⁠name⁠", + "trimmed": "⁠name⁠", + "blank": false }, { - "name": "a superscript two (U+00B2)", - "last_event_id": "²", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0000 alone, a character of a name", + "text": "\u0000", + "trimmed": "\u0000", + "blank": false }, { - "name": "an ASCII digit then an Arabic-Indic one", - "last_event_id": "1٣", - "since": null, - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "U+0000 around a name, a character of a name", + "text": "\u0000name\u0000", + "trimmed": "\u0000name\u0000", + "blank": false }, { - "name": "no Last-Event-ID and no since: the beginning", - "last_event_id": null, - "since": null, - "cursor": "0" + "name": "U+007F alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false }, { - "name": "an empty Last-Event-ID is none", - "last_event_id": "", - "since": null, - "cursor": "0" + "name": "U+007F around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false }, { - "name": "since when there is no Last-Event-ID", - "last_event_id": null, - "since": "5", - "cursor": "5" + "name": "every white-space character and nothing else", + "text": "\t\n\u000b\f\r              

   ", + "trimmed": "", + "blank": true }, { - "name": "since when the Last-Event-ID is empty", - "last_event_id": "", - "since": "5", - "cursor": "5" + "name": "every white-space character around a name", + "text": "\t\n\u000b\f\r              

   name\t\n\u000b\f\r              

   ", + "trimmed": "name", + "blank": false }, { - "name": "an empty since is none", - "last_event_id": null, - "since": "", - "cursor": "0" + "name": "white space before a name only", + "text": " \t name", + "trimmed": "name", + "blank": false }, { - "name": "the Last-Event-ID wins over since", - "last_event_id": "7", - "since": "5", - "cursor": "7" + "name": "white space after a name only", + "text": "name\r\n", + "trimmed": "name", + "blank": false }, { - "name": "a Last-Event-ID of zero wins over since", - "last_event_id": "0", - "since": "5", - "cursor": "0" + "name": "white space inside a name is kept", + "text": " order assistant ", + "trimmed": "order assistant", + "blank": false }, { - "name": "a Last-Event-ID that is not a cursor is refused though since is one", - "last_event_id": "x", - "since": "5", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a byte order mark inside white space", + "text": "  ", + "trimmed": "", + "blank": false }, { - "name": "a since that is not a cursor", - "last_event_id": null, - "since": "x", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "white space inside two byte order marks", + "text": " ", + "trimmed": " ", + "blank": false }, { - "name": "a since with a minus sign", - "last_event_id": null, - "since": "-3", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a next-line character after white space", + "text": "name …", + "trimmed": "name …", + "blank": false }, { - "name": "a since with a fraction", - "last_event_id": null, - "since": "1.0", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "a unit separator before white space", + "text": "\u001f name", + "trimmed": "\u001f name", + "blank": false }, { - "name": "a since past the largest number", - "last_event_id": null, - "since": "9223372036854775808", - "status": 400, - "error": "Last-Event-ID must be a whole number" + "name": "fifty spaces", + "text": " ", + "trimmed": "", + "blank": true }, { - "name": "a since of the largest number", - "last_event_id": null, - "since": "9223372036854775807", - "cursor": "9223372036854775807" + "name": "a name between fifty spaces", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "a lone surrogate between spaces", + "text": " \ud800 ", + "trimmed": "\ud800", + "blank": false } ] } diff --git a/test/vectors/ask-person-vectors.json b/test/vectors/ask-person-vectors.json index 0346e62a..fd07c673 100644 --- a/test/vectors/ask-person-vectors.json +++ b/test/vectors/ask-person-vectors.json @@ -1,7 +1,7 @@ { "contract": "ask-person", - "version": 3, - "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from. Version 3 (a ticket has one spelling): a ticket is well-formed only when it has the three parts and its payload and signature parts are canonical base64url without padding - the alphabet from start to end, and the one spelling the encoder gives the bytes - the signature as long as the MAC (32 bytes, 43 characters); a ticket that is not well-formed is the 400 whatever it resembles, and the 403 is a well-formed ticket that no key signs. ticket_cases gain a payload part of each length base64url without padding can have (4n characters, 4n+2 and 4n+3) and one that holds - and _; verify_cases gain the mangled tickets made from them - a newline, a character more or fewer, padding, the standard alphabet, bits left over in a last character, a part missing, empty or added, another version - each with the status it gets. One earlier case changed with the rule: the signature of 'a tampered signature' left bits over in its last character, so it is now tampered in canonical form (403) and its earlier ticket is the case after it (400).", + "version": 5, + "description": "The ask-a-person main flow's shared vectors (RFC-0014, build plan step 1): the pure half of extensions/ask-person, run by mercury-python and mercury-nodejs against the same file. ticket_cases pin the ticket a payload and a key produce (v1..: the canonical JSON of the payload - keys sorted, no spaces, Unicode kept - and its HMAC-SHA256, both base64url without padding). verify_cases pin how a ticket is read with a list of keys (the current key first, then the previous one) at a given time: the payload, or the exact status and message that refuse it (400 malformed or another version, 403 no key signs it, 410 expired). message_cases pin the message a hold node sends - validated in a fixed order - and the event the channels receive, with requested_at given so the ticket, the link and expires_at are deterministic; or the exact 400 that refuses it. readvice_cases and reply_cases pin the requests the reply page and endpoint send to the engine's entry (the allowlist by graph id, the correlation id header, the turn, the decisions with who decided and when prefixed to each tool call's note; a question's answer unchanged), or the exact refusal. outcome_cases pin what the invoker gets back from the engine's status and body. No HTTP is exchanged by these cases; the transports are tested by each pack against a fake engine. Version 2 (round 4 - the question record): record_cases pin the row a message event becomes in the record (a wait open with its ticket, link and expiry; an advice with none and no state); answer_cases pin the state an answer's outcome leaves (the engine accepted it: answered; nothing was waiting: expired; a refusal or an engine that did not answer: open); transition_cases pin the record's transitions on a scripted sequence - a wait upserted on (graph_id, correlation_id, turn) unless an older message lands late, an advice appended, the first accepted decision standing, the expiry sweep, the change sequence a feed reads from. Version 3 (a ticket has one spelling): a ticket is well-formed only when it has the three parts and its payload and signature parts are canonical base64url without padding - the alphabet from start to end, and the one spelling the encoder gives the bytes - the signature as long as the MAC (32 bytes, 43 characters); a ticket that is not well-formed is the 400 whatever it resembles, and the 403 is a well-formed ticket that no key signs. ticket_cases gain a payload part of each length base64url without padding can have (4n characters, 4n+2 and 4n+3) and one that holds - and _; verify_cases gain the mangled tickets made from them - a newline, a character more or fewer, padding, the standard alphabet, bits left over in a last character, a part missing, empty or added, another version - each with the status it gets. One earlier case changed with the rule: the signature of 'a tampered signature' left bits over in its last character, so it is now tampered in canonical form (403) and its earlier ticket is the case after it (400). Version 4 (one rule for a number, a duration, a switch and a payload). number_cases pin how a value is read as a whole number (whole) and as a duration (duration_ms, in milliseconds), null where it spells none: a whole number is a JSON number with a whole value or ASCII digits, at most 9007199254740991 - the largest whole number both runtimes hold exactly - with the white space both runtimes' trim takes ignored around it and none inside; a duration is such a number of seconds, or such a number and right after it one of ms, s, m, h, d, at most 9007199254740991 milliseconds. The first 101 values are the LLM helper's numbers.probes as they stood when this version was written, with the same verdicts but for the durations between that many milliseconds and that many seconds, which the helper holds in seconds. switch_cases pin a switch: true or false for the boolean and for the text in any letter case, \"default\" for no value and an empty one, null for any other value, which a setting refuses by name. message_cases gain a turn and a ttl in each spelling the rule reads - the event carries the whole number - and in spellings it refuses, and a graph id and a correlation id with a lone surrogate, which no ticket can carry: the exact 400, for an advice too. ticket_cases gain the escapes of the canonical form and the largest numbers. verify_cases gain payloads a key holder signed (their names begin 'signed:'): the signed bytes are the canonical JSON of a wait's five fields or the ticket is malformed - a float for a whole number, a number past 9007199254740991, an escape the canonical form does not write, a key twice, a space, another order of the keys, bytes that are not UTF-8. readvice_cases and reply_cases gain graphs named as members every object has (constructor, toString, __proto__): a graph is one the allowlist names or it is the 404. Version 5 (one reader of a time; an expiry both packs can write; a turn the record holds; blank by one rule; every digit of a number in the record). time_cases pin a time a caller supplies: ms, the instant in milliseconds from 1970-01-01T00:00:00Z, and stamp, the text both packs write for that instant - or null for both where the text is no time. A time is a date YYYY-MM-DD, an upper-case T, a time HH:MM or HH:MM:SS with a fraction of one to nine digits at most, then Z or +HH:MM or -HH:MM, and nothing before or after it: a date the calendar has, hour 0 to 23, minute and second 0 to 59, an offset of at most 23:59, the years 0001 to 9999 as written and in UTC; the instant is read to the millisecond, a longer fraction cut. text_cases pin the white space around a text: trimmed, the text without it, and blank, whether nothing is left - the 24 characters of the number rule and no other, so U+FEFF, U+0085 and U+001C to U+001F are characters of a name. message_cases gain requested_at in the spellings the rule reads - the event keeps it as written, the expiry is written in UTC - and in spellings it refuses; a wait whose expiry is not before the year 10000, the exact 400; an expiry before 1970, whose whole seconds in the ticket are the floor; a turn up to 2147483647, the largest the record's INTEGER column holds, and the 400 past it (the largest turn of version 4 was 9007199254740991); required texts that are blank, and texts of characters that are not white space. transition_cases gain a row whose re-advices and whose sweep write their times in another spelling - at an offset, without the milliseconds: the record orders them by their instants, as the reference store compares two stamps, never by their texts. exact_cases pin a whole number past 9007199254740991 in a waiting call's input and in a decision: numbers gives each as text with the place it stands at, since a JSON number that large is not exact in every reader; record is the text the record's message column is given and decisions_record its decisions column's - compact JSON with every digit, the event's members in the order kind, graph_id, description, correlation_id, turn, node, summary, details, calls, ttl, requested_at, expires_at, ticket, link.", "ticket_cases": [ { "name": "an approval's ticket", @@ -86,6 +86,90 @@ "e": 1795252324 }, "ticket": "v1.eyJjIjoiUTM-UTI_IiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.2LiQLRopPATfnlsnqRn6KdQUuCLCTv5UzQGjbVFdlRI" + }, + { + "name": "a quote and a backslash are escaped", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order \"1002\" \\ case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFwgY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.GR8d2xz5bNOEa_TUKFGANpAWtfHxPm1b5Or4NF02bqA" + }, + { + "name": "a newline and a tab are their short escapes", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order\n1002\tcase", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXJcbjEwMDJcdGNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.pZlZ_ZnjOBaIDhzCdU3l7Zr_iV4quX42LJ202abpIYM" + }, + { + "name": "another control character is its escape in lower case", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order\u001f1002\u0001case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMWYxMDAyXHUwMDAxY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.m_GsIvRbWNSIf7ZzqBt8FbezFm-O90Uqp-oB3I3WaMs" + }, + { + "name": "a slash, DEL and the line separators are kept as they are", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order/1002

case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIvMTAwMn_igKjigKljYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.c9orOPgIZ-_RXuyP0hCRchJ5N0zL87cAvA_kqKnqDcU" + }, + { + "name": "a character beyond the basic plane is kept as its four bytes", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-𝟟-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc" + }, + { + "name": "the largest turn and the largest expiry", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 9007199254740991, + "k": "approval", + "e": 9007199254740991 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTF9.YOygqOmGcUTFzMJXK_t1qSLPeYKxqcFAks2zdUVsGjw" + }, + { + "name": "a turn of zero and an expiry before 1970", + "key": "test-key-current", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 0, + "k": "approval", + "e": -1 + }, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjowfQ.oGlE32krFfNiMWxa7Ygr8HdE5LH4rqPv-E0vF0A95kw" } ], "verify_cases": [ @@ -868,1474 +952,908 @@ "ticket": "v2.%%%.###", "status": 400, "message": "Ticket version v2 is not supported" - } - ], - "message_cases": [ + }, { - "name": "an approval", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", - "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + "name": "signed: the canonical payload", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 } }, { - "name": "a question (ttl as whole seconds)", - "message": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks a plan", - "correlation_id": "release-42", - "turn": 4, - "summary": "Which plan should the release follow? (A, B, C)", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan should the release follow?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks a plan", - "correlation_id": "release-42", - "turn": 4, - "summary": "Which plan should the release follow? (A, B, C)", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan should the release follow?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-19T10:12:04.118Z", - "ticket": "v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0", - "link": "https://ask.example.test/ask/v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0" - } + "name": "signed: not JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.bm90IGpzb24.ROl00bnQzmhac2gP22AzeMfexP9GI2k3O2VTbcPl2a8", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "an advice (no ticket, no link)", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - } + "name": "signed: not UTF-8", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.__4A.jslaip2VSlkFPr2NzSIa3g1e9h-bwiMJH1xPT0kBiZY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "an advice without a turn", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - } + "name": "signed: an empty object", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.e30.-5tNnrDX2FBbAa_APRnOWVYrqmKCSV4RD8631glbTGY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a reply url with a trailing slash", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test/", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", - "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" - } + "name": "signed: a list", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.WzEsMl0.DiKEAHsFCm5kKY15aTArnwLoMPq2pZMSYdG6s2yBODk", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "not a map", - "message": [ - "kind" + "name": "signed: null", + "keys": [ + "test-key-current", + "test-key-previous" ], - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "now": 1795089600, + "ticket": "v1.bnVsbA.06fp24QIKWX6G_jrtUTCgOxGBGjLL3C5FXFs30QUwFU", "status": 400, - "error": "person.ask takes a map" + "message": "Ticket is malformed" }, { - "name": "kind missing", - "message": { - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a string", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.InRleHQi.3UzZEX0R5kTKLEB7gIBlhmYPW2n6Wh5RD-y-Wo9fzVQ", "status": 400, - "error": "kind must be one of approval, question, advice" + "message": "Ticket is malformed" }, { - "name": "kind unknown", - "message": { - "kind": "notice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a number", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.Nw.Lu7WpkxbLGUnBhCMSz7W6xgIPDhjbKnUoytvGn__KTI", "status": 400, - "error": "kind must be one of approval, question, advice" + "message": "Ticket is malformed" }, { - "name": "graph_id missing", - "message": { - "kind": "approval", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: an expiry of NaN", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoieSIsImUiOk5hTiwiZyI6IngiLCJrIjoiYXBwcm92YWwiLCJ0IjoxfQ.yS7IyfOd8Tzr_bjEExb4PMTZcq0scFKp9W_qLSRKMOs", "status": 400, - "error": "graph_id is required" + "message": "Ticket is malformed" }, { - "name": "graph_id blank", - "message": { - "kind": "approval", - "graph_id": " ", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: an expiry of Infinity", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoieSIsImUiOkluZmluaXR5LCJnIjoieCIsImsiOiJhcHByb3ZhbCIsInQiOjF9.aqoKnTCecoiL1bkRtPdA0FT_2cXTASK468Y3cNQdpkM", "status": 400, - "error": "graph_id is required" + "message": "Ticket is malformed" }, { - "name": "description not text", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": 7, - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a byte order mark first", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.77u_eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.KO4I7eeVZ2IqWOHBaznxzx0BB6ZF-ivEDDhHV4816ZA", "status": 400, - "error": "description must be text" + "message": "Ticket is malformed" }, { - "name": "correlation_id missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: fifty lists inside one another", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.W1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tdXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXQ.68v26kHOHbqmS8fKkyVY930v2hAq7laEV7RRlv4alWQ", "status": 400, - "error": "correlation_id is required" + "message": "Ticket is malformed" }, { - "name": "summary missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a lone surrogate written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHVkODAwLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.k-8bmO6BJxooR0hOMSF2JNeHFw0RsidIitAx-A9PRrQ", "status": 400, - "error": "summary is required" + "message": "Ticket is malformed" }, { - "name": "node not text", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": [ - "assist" - ], - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a character beyond the basic plane written as two escapes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHVkODM1XHVkZmRmLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.wcHeDEQKr2o3A3vwgAecxOw_b-uDsJUBAFrQ7FIBWZM", "status": 400, - "error": "node must be text" + "message": "Ticket is malformed" }, { - "name": "requested_at not a time", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "yesterday" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "status": 400, - "error": "requested_at must be an ISO-8601 time" + "name": "signed: a character beyond the basic plane as its four bytes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc", + "payload": { + "c": "order-𝟟-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } }, { - "name": "turn missing for an approval", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a letter written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItXHUwMDMxMDAyLWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.1h5PT3WbXboZOyg06glzBWDzuWyaYzochHhx_snMTHE", "status": 400, - "error": "turn is required for an approval or a question" + "message": "Ticket is malformed" }, { - "name": "turn negative", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": -1, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a slash written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcLzEwMDItY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.bdxQXR-1x85Tj_Pt_7O9ya-bKwr73uARDYKkZJVA4zE", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "turn a boolean", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": true, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a slash as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIvMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.C95J7CdTpKHcwwtCmSQXKsEU2yH3sIcye6V13DH5TRU", + "payload": { + "c": "order/1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a control character as its escape in lower case", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMWYxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.MgReFMdWicN0x7C9sKHACyuWqWKF7hIGmC6qaEO_od8", + "payload": { + "c": "order\u001f1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a control character as its escape in upper case", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMUYxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kTBJ8voi3WZYsd_yH_eX5Qwa_Ng0bnXlr9E0JC8UTb8", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "calls empty", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", - "status": 400, - "error": "calls must be a non-empty list of the waiting calls, each with an id" + "name": "signed: a newline as its short escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcbjEwMDIiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.m-Kg3uK5cl0zYfxwV4RMzS4K3SeQCyuAsMnMi685czQ", + "payload": { + "c": "order\n1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } }, { - "name": "a call without an id", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "name": "issue_refund" - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a newline as its long escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTAwMGExMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.QNpa6i5QZVOQi42QnAeEj2HzrrFw4E59OlCtESfBbKQ", "status": 400, - "error": "calls must be a non-empty list of the waiting calls, each with an id" + "message": "Ticket is malformed" }, { - "name": "ttl missing", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a control character as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIfMTAwMiIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.r7uf2ysEz80iPDz5XxkTgr5kjsdiVeyRiEjZzLjmW2o", "status": 400, - "error": "ttl is required for an approval or a question" + "message": "Ticket is malformed" }, { - "name": "ttl not a duration", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "soon", - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a quote and a backslash as their escapes", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFwgY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.GR8d2xz5bNOEa_TUKFGANpAWtfHxPm1b5Or4NF02bqA", + "payload": { + "c": "order \"1002\" \\ case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: the line separator as it is", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXLigKgxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.8SRh-QxTDqbtwl2J9LlGYOqKGtfp3be4KDiHfpfWIEo", + "payload": { + "c": "order
1002", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: the line separator written as an escape", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXJcdTIwMjgxMDAyIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.4A7jLlw5Ot2MSZHy-OZgvGy6uvIBDQwvUAW-xUfQFw4", "status": 400, - "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + "message": "Ticket is malformed" }, { - "name": "ttl zero", - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": 0, - "requested_at": "2026-11-19T09:12:04.118Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2.0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuMH0.Buni_FQQuNebaqNHBVQSHsMzZDsYv5taQ4HmjDW2aC0", "status": 400, - "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + "message": "Ticket is malformed" }, { - "name": "an advice with calls", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ] - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2e0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJlMH0.EXNh7SLEeRdhBB9yLQjXf0ztUSAu7zlts2PW6V_E-jA", "status": 400, - "error": "an advice carries no calls and no ttl" + "message": "Ticket is malformed" }, { - "name": "an advice with a ttl", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z", - "ttl": "1d" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of -0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0wfQ.t0Z96QA09f7Fs7w8uH-DtdII1SIO_E74azmzcAyiTTg", "status": 400, - "error": "an advice carries no calls and no ttl" + "message": "Ticket is malformed" }, { - "name": "an advice with a negative turn", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": -2, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": "The next question, if any, is expected within two minutes.", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of -0.0", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0wLjB9.Hdzz4MCHHjNRZg2UoSAkximTxKQApZSmXsyH2wG00Bw", "status": 400, - "error": "turn must be a whole number >= 0" + "message": "Ticket is malformed" }, { - "name": "details not text on an advice", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 3, - "node": "acknowledge", - "summary": "Your decision was received; the assistant is issuing the refund", - "details": { - "text": "x" - }, - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "key": "test-key-current", - "reply_url": "https://ask.example.test", + "name": "signed: a turn of 2.5", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuNX0.6hTexIwyTqB87MbblGlZ0g-Y8lAfOFnTuhkQ_lfQZrw", "status": 400, - "error": "details must be text" - } - ], - "readvice_cases": [ + "message": "Ticket is malformed" + }, { - "name": "the re-advice of an approval", + "name": "signed: a turn as text", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOiIyIn0.r9Pr8an7lzVoSbWH5du0ZNGWHN07hTgMkbBPfHgNKsE", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of true", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOnRydWV9.8y1fY5L1tmL8twjGmnj6rlEoEka9JNnMx7FP8RJKGM4", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of -1", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOi0xfQ.t_5U9OvYP8MS3k8FsnQviJTWvzxjOAHIGxyYn_CFWNI", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of 02", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjAyfQ.eFi-AAL7j8W0VAas-WShkqNMQEhmNK1Bg9xRWRA-ms0", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of +2", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOisyfQ.rqre1Dj1d0n3BtqPZAu6sPeXRQCi-OmmisxtO0qBtqE", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a turn of zero", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", "payload": { - "g": "order-assistant", "c": "order-1002-case", - "t": 2, + "e": 1795252324, + "g": "order-assistant", "k": "approval", - "e": 1795252324 - }, - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2 - } + "t": 0 } }, { - "name": "a graph that is not in the allowlist", + "name": "signed: the largest turn", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTF9.x4rtsZ8qc79zrxBWmhePxTuWzdHLRcL-QmrCe8q6oEY", "payload": { - "g": "other-graph", "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 404, - "error": "graph other-graph is not configured for replies" - } - ], - "reply_cases": [ - { - "name": "an approval with a note", - "payload": { + "e": 1795252324, "g": "order-assistant", - "c": "order-1002-case", - "t": 2, "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed the loss" - } - ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z] Carrier confirmed the loss" - } - ] - } + "t": 9007199254740991 } }, { - "name": "a refusal without a note", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": false - } + "name": "signed: a turn one past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTJ9.kxCAfBasWDD3pkc6H8SszyX_j7BPRWbEpsEF49Y_vCY", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a refusal with an empty note", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "" - } + "name": "signed: a turn two past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": false, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjkwMDcxOTkyNTQ3NDA5OTN9.QoYoVLDFCdZ86w9p64eM3blS72R6lCeCse70LKZTzRM", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a question's answer travels unchanged", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } + "name": "signed: a turn of 1e400", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/plan-assistant", - "headers": { - "x-correlation-id": "release-42" - }, - "body": { - "turn": 4, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B" - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjFlNDAwfQ.U9WDcaPnmUuREFVHV8aqb8z3mXbiIg8cZZu8RRp-ae4", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a question's answer may be any JSON value", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": { - "plan": "B", - "why": "cheaper" - } - } + "name": "signed: an expiry as a float", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/plan-assistant", - "headers": { - "x-correlation-id": "release-42" - }, - "body": { - "turn": 4, - "decisions": [ - { - "id": "toolu_02B", - "answer": { - "plan": "B", - "why": "cheaper" - } - } - ] - } - } + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNC4wLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.VlujmHfAxLXNRRJnHQOkogwuC6aFOoViVmNfdm2GnxE", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "a turn with a tool call and a question", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true - }, - { - "id": "toolu_02B", - "answer": "A" - } + "name": "signed: an expiry with a fraction", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "request": { - "url": "http://127.0.0.1:8085/api/graph/order-assistant", - "headers": { - "x-correlation-id": "order-1002-case" - }, - "body": { - "turn": 2, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" - }, - { - "id": "toolu_02B", - "answer": "A" - } - ] - } - } - }, - { - "name": "decisions empty", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MS43OTUyNTIzMjQ1ZTksImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ._4-4WTxVVVvW41JW9bztvzacZ1sKTF_wIQbX77cLPyc", "status": 400, - "error": "decisions must be a non-empty list, one per waiting call" + "message": "Ticket is malformed" }, { - "name": "decisions not a list", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": { - "id": "toolu_01A", - "approved": true - }, - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "name": "signed: an expiry of 1e400", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MWU0MDAsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.CsPmH8fzZwR9ZmGTeE73v0d1AGiR96m53RGdNsha-r8", "status": 400, - "error": "decisions must be a non-empty list, one per waiting call" + "message": "Ticket is malformed" }, { - "name": "a decision without an id", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "approved": true - } + "name": "signed: an expiry of 2^63", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTIyMzM3MjAzNjg1NDc3NTgwOCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OTqB4M-8N37lVBEE-Ih3Ck3qsSoWfuL3--MwyoXdh5I", "status": 400, - "error": "each decision needs the id of its call" + "message": "Ticket is malformed" }, { - "name": "a decision with approved and answer", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "answer": "x" - } + "name": "signed: an expiry as text", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6IjE3OTUyNTIzMjQiLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Zjvz7EDRmcXbOYO_CLwZb-P20Kb9EBkPLBu0kivWCgI", "status": 400, - "error": "each decision carries approved (with an optional note) or answer, not both" + "message": "Ticket is malformed" }, { - "name": "a decision with neither", + "name": "signed: the largest expiry", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.AWE1LPsfSWCa1dDJyCjnMPXSqkd-QNKxGJHmb_G8cNc", "payload": { - "g": "order-assistant", "c": "order-1002-case", - "t": 2, + "e": 9007199254740991, + "g": "order-assistant", "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "note": "x" - } - ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 400, - "error": "each decision carries approved (with an optional note) or answer" + "t": 2 + } }, { - "name": "approved not a boolean", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": "yes" - } + "name": "signed: an expiry one past the largest", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6OTAwNzE5OTI1NDc0MDk5MiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.yBLFHRodxObWt3skCvW9wWjO6Xj38BEeGl4Innh915c", "status": 400, - "error": "approved must be true or false" + "message": "Ticket is malformed" }, { - "name": "note not text", - "payload": { - "g": "order-assistant", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": 5 - } + "name": "signed: an expiry before 1970", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 400, - "error": "note must be text" + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "status": 410, + "message": "Ticket expired" }, { - "name": "an answer with a note", - "payload": { - "g": "plan-assistant", - "c": "release-42", - "t": 4, - "k": "question", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_02B", - "answer": "B", - "note": "x" - } + "name": "signed: the smallest expiry", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTkwMDcxOTkyNTQ3NDA5OTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.qbuNc20XwqIFfnyjYZMI2FOY1kqiw2dbJgIk1YaZm2A", + "status": 410, + "message": "Ticket expired" + }, + { + "name": "signed: an expiry one before the smallest", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTkwMDcxOTkyNTQ3NDA5OTIsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.t6TnZlsjLDfISHMFr1IEgl9MfLCc5WJqQqRpeCmSBFg", "status": 400, - "error": "a question's decision carries an answer and no note" + "message": "Ticket is malformed" }, { - "name": "a graph that is not in the allowlist", - "payload": { - "g": "other-graph", - "c": "order-1002-case", - "t": 2, - "k": "approval", - "e": 1795252324 - }, - "decisions": [ - { - "id": "toolu_01A", - "approved": true - } + "name": "signed: a key twice", + "keys": [ + "test-key-current", + "test-key-previous" ], - "who": "operator-17", - "at": "2026-11-19T10:00:00.000Z", - "graphs": { - "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", - "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" - }, - "status": 404, - "error": "graph other-graph is not configured for replies" - } - ], - "outcome_cases": [ + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im90aGVyIiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.1nHPP2jJqHIH_5l-hFKy9fpZTz-fzCg-ymmQiVYBdqw", + "status": 400, + "message": "Ticket is malformed" + }, { - "name": "the graph answered", - "engine": { - "status": 200, - "body": "{\"type\": \"answer\", \"turn\": 3, \"run\": \"resume\", \"message\": \"Your refund has been issued.\"}", - "error": null - }, - "status": 200, - "body": { - "type": "answer", - "turn": 3, - "run": "resume", - "message": "Your refund has been issued." - } + "name": "signed: the same member twice", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsInQiOjJ9.2M42UaCQBQSKj2A5sQV4bzPSfK-1qPNwvHQzDINDBOE", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the model asked again", - "engine": { - "status": 200, - "body": "{\"type\": \"approval\", \"turn\": 4, \"calls\": []}", - "error": null - }, - "status": 200, - "body": { - "type": "approval", - "turn": 4, - "calls": [] - } + "name": "signed: spaces in the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjogIm9yZGVyLTEwMDItY2FzZSIsICJlIjogMTc5NTI1MjMyNCwgImciOiAib3JkZXItYXNzaXN0YW50IiwgImsiOiAiYXBwcm92YWwiLCAidCI6IDJ9.cA3ehwKiJDWNXXY5ne1-tIOR9cASyGzkX3UQF3c6lEw", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "nothing waiting (the gate)", - "engine": { - "status": 410, - "body": "{\"type\": \"nothing-waiting\"}", - "error": null - }, - "status": 410, - "body": { - "type": "nothing-waiting" - } + "name": "signed: the keys in the order the issuer was given", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJnIjoib3JkZXItYXNzaXN0YW50IiwiYyI6Im9yZGVyLTEwMDItY2FzZSIsInQiOjIsImsiOiJhcHByb3ZhbCIsImUiOjE3OTUyNTIzMjR9.ch6DP8ypFCC8mmqOlFvXpxxmteDiTPn7jBzP1BztXBQ", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph refused the decisions", - "engine": { - "status": 400, - "body": "{\"type\": \"error\", \"message\": \"unknown call id\"}", - "error": null - }, + "name": "signed: a newline after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9Cg.d4fIk4wBrIoB5ryV5IeKjrkwlIpDFrgQ5Eibuh9xYoA", "status": 400, - "body": { - "type": "error", - "message": "unknown call id" - } + "message": "Ticket is malformed" }, { - "name": "the graph failed", - "engine": { - "status": 500, - "body": "{\"type\": \"error\", \"message\": \"boom\"}", - "error": null - }, - "status": 500, - "body": { - "type": "error", - "message": "boom" - } + "name": "signed: a space before the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.IHsiYyI6Im9yZGVyLTEwMDItY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.MlU6vRYBN36ku7vez4bG9VHcZatTKBT93MvewHvtIHw", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered text", - "engine": { - "status": 200, - "body": "OK", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: a NUL after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9AA.6IfmZmO88QqddIjFJJQly51s3mwyAQXKc-r-sz42e50", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered a JSON list", - "engine": { - "status": 200, - "body": "[1,2]", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: text after the JSON", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9IHg.brgUNDGy0f_GfxNACVKcUonrwxmvVx6-ZxMU0P9AwQ4", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph answered nothing", - "engine": { - "status": 200, - "body": "", - "error": null - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph answered outside the contract" - } + "name": "signed: a byte that is not UTF-8 in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt_y1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.Isq6uRxWMQUHh_wUVwyfqfZdfc2xZHeQv36szG-MMNU", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph did not answer", - "engine": { - "status": null, - "body": null, - "error": "ClientConnectorError" - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - ClientConnectorError" - } + "name": "signed: an overlong slash in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItwK8tY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.BKZ6c78UWw1imOM0tV8c-07BLVuGmt0m7rJRIrt1n1I", + "status": 400, + "message": "Ticket is malformed" }, { - "name": "the graph timed out", - "engine": { - "status": null, - "body": null, - "error": "TimeoutError" - }, - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - TimeoutError" + "name": "signed: a surrogate half as three bytes in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt7aCALWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.TxYuW2Zuydc9sTegMsfH0EYTUfri9mibELSAHUgHYPA", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: the replacement character in the correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXIt77-9LWNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.i6SKozUKCKr5H-DeWlkMdYMn8AqbaetlD_pxV6RPlvw", + "payload": { + "c": "order-�-case", + "e": 1795252324, + "g": "order-assistant", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: an extra key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsIngiOjF9.CJtL4wrVaExlaCLG66DzT0DL6k-qmvnVG9Nk3v80OYg", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a key missing", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.lWEUB06BXS-lYJDXzOl31Xq9Gl3bT2Obx2VxvLAsjD0", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: the kind of an advice", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhZHZpY2UiLCJ0IjoyfQ.pDBtatNmV76BvYBM675o4UpACrpJTVGIzVwxSfJGxHw", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: an empty graph id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.FNSX-0tn7JKahBhdJ8EaBK_ST3OWkBoTnwgLuqo3W00", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: an empty correlation id", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoiIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.Clib_tF9GX0vi1AR5gr5tdqbhL7IxyBbniaFFFmZ4U4", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a graph id of one space", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiAiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.HJbo3PavPatcne6hF596ML5Aj9Ng1LL-8EfRKnqGcFU", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": " ", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: __proto__ as a key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIsIl9fcHJvdG9fXyI6eyJ4IjoxfX0.MQc0qp-_GyyKFLzs15YtnrCx8YrMyYlP51VNoLKjMes", + "status": 400, + "message": "Ticket is malformed" + }, + { + "name": "signed: a graph named __proto__", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Il9fcHJvdG9fXyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.V5QoTy4aXCZwu6aoWLUgrFioYX8Q5ULOj84eaeouRBs", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "__proto__", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a graph named constructor", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6ImNvbnN0cnVjdG9yIiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.f-jwzRiwY2Ub2g1wSfxUk3wfxgp2dqvNnzOXOdjj3o4", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "constructor", + "k": "approval", + "t": 2 + } + }, + { + "name": "signed: a question", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjJ9.ZfNIavj-5ybPN3JaMXwtI3DMDkPsoD2v4qoCPc-86dI", + "payload": { + "c": "order-1002-case", + "e": 1795252324, + "g": "order-assistant", + "k": "question", + "t": 2 } + }, + { + "name": "signed: a turn of 2.0 under the previous key", + "keys": [ + "test-key-current", + "test-key-previous" + ], + "now": 1795089600, + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIuMH0.KnsTR1e3Bv5HE14J9TToWAZ2jjrZihcUSD8o3nbx0AY", + "status": 400, + "message": "Ticket is malformed" } ], - "record_cases": [ + "message_cases": [ { "name": "an approval", - "event": { + "message": { "kind": "approval", "graph_id": "order-assistant", "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", "turn": 2, "node": "assist", - "summary": "A refund waits for the supervisor's decision", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", "calls": [ { "id": "toolu_01A", @@ -2350,74 +1868,47 @@ } ], "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" + "requested_at": "2026-11-19T09:12:04.118Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": [ - "order-assistant", - "order-1002-case", - 2 - ], - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "approval", "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", "turn": 2, - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac", - "description": "Customer-support assistant: a refund waits for a supervisor", - "summary": "A refund waits for the supervisor's decision", - "details": null, - "message": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" - }, - "state": "open", + } + ], + "ttl": "2d", "requested_at": "2026-11-19T09:12:04.118Z", "expires_at": "2026-11-21T09:12:04.118Z", - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" } }, { - "name": "a question", - "event": { + "name": "a question (ttl as whole seconds)", + "message": { "kind": "question", "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", + "description": "Planning assistant: the owner picks a plan", "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", + "turn": 4, + "summary": "Which plan should the release follow? (A, B, C)", "calls": [ { "id": "toolu_02B", @@ -2425,7 +1916,7 @@ "ask": true, "wait": true, "input": { - "question": "Which plan?", + "question": "Which plan should the release follow?", "options": [ "A", "B", @@ -2435,905 +1926,10030 @@ } ], "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" + "requested_at": "2026-11-19T09:12:04.118Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": [ - "plan-assistant", - "release-42", - 1 - ], - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "question", "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks a plan", "correlation_id": "release-42", - "turn": 1, - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac", - "description": "Planning assistant: the owner picks one of the plans", - "summary": "The planning assistant asks which plan to follow", - "details": null, - "message": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", - "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan?", - "options": [ - "A", - "B", - "C" - ] - } + "turn": 4, + "summary": "Which plan should the release follow? (A, B, C)", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan should the release follow?", + "options": [ + "A", + "B", + "C" + ] } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" - }, - "state": "open", - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-19T10:12:04.118Z", + "ticket": "v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0", + "link": "https://ask.example.test/ask/v1.eyJjIjoicmVsZWFzZS00MiIsImUiOjE3OTUwODMxMjQsImciOiJwbGFuLWFzc2lzdGFudCIsImsiOiJxdWVzdGlvbiIsInQiOjR9.yZC3ozsEy46UIquX4_vu7VWETFPpqF-GKlUFXh8AkG0" } }, { - "name": "an advice with a turn", - "event": { + "name": "an advice (no ticket, no link)", + "message": { "kind": "advice", "graph_id": "order-assistant", "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", "requested_at": "2026-11-19T09:40:12.004Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": null, - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "advice", "graph_id": "order-assistant", - "correlation_id": "order-1002-case", - "turn": 2, - "ticket": null, - "link": null, "description": "Customer-support assistant: a refund waits for a supervisor", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "state": null, - "requested_at": "2026-11-19T09:40:12.004Z", - "expires_at": null, - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" } }, { - "name": "an advice without a turn or a requested_at takes now", - "event": { + "name": "an advice without a turn", + "message": { "kind": "advice", "graph_id": "order-assistant", - "description": "Customer-support assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" }, - "now": "2026-11-19T09:12:05.000Z", - "key": null, - "row": { + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { "kind": "advice", "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", "correlation_id": "order-1002-case", - "turn": null, - "ticket": null, - "link": null, - "description": "Customer-support assistant", - "summary": "Nightly: the queue is empty", - "details": null, - "message": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant", - "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" - }, - "state": null, - "requested_at": "2026-11-19T09:12:05.000Z", - "expires_at": null, - "updated_at": "2026-11-19T09:12:05.000Z", - "answered_at": null, - "answered_by": null, - "decisions": null, - "outcome": null + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" } - } - ], - "answer_cases": [ - { - "name": "the engine answered", - "status": 200, - "body": { - "type": "answer", - "turn": 3, - "message": "Your refund has been issued." - }, - "state": "answered" - }, - { - "name": "the model asked again", - "status": 200, - "body": { - "type": "approval", - "turn": 4, - "calls": [] - }, - "state": "answered" }, { - "name": "the loop refused the decision - the graph re-advised with the error", - "status": 200, - "body": { - "type": "approval", + "name": "a reply url with a trailing slash", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", "turn": 2, - "error": "not a call waiting for approval" - }, - "state": "open" - }, - { - "name": "nothing waiting by status", - "status": 410, - "body": { - "type": "nothing-waiting" + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "expired" + "key": "test-key-current", + "reply_url": "https://ask.example.test/", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } }, { - "name": "nothing waiting by type", - "status": 200, - "body": { - "type": "nothing-waiting" - }, - "state": "expired" + "name": "not a map", + "message": [ + "kind" + ], + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "person.ask takes a map" }, { - "name": "the ticket expired at the reply endpoint", - "status": 410, - "body": { - "type": "expired", - "message": "Ticket expired" + "name": "kind missing", + "message": { + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "expired" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "kind must be one of approval, question, advice" }, { - "name": "the reply endpoint refused the decisions", + "name": "kind unknown", + "message": { + "kind": "notice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", "status": 400, - "body": { - "type": "error", - "message": "each decision needs the id of its call" + "error": "kind must be one of approval, question, advice" + }, + { + "name": "graph_id missing", + "message": { + "kind": "approval", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "graph_id is required" }, { - "name": "the graph did not answer", - "status": 502, - "body": { - "type": "error", - "message": "the graph did not answer - TimeoutError" + "name": "graph_id blank", + "message": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "graph_id is required" }, { - "name": "the reply endpoint did not answer", - "status": 502, - "body": { - "type": "error", - "message": "the reply endpoint did not answer - ClientConnectorError" + "name": "description not text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": 7, + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" }, - "state": "open" + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "description must be text" }, { - "name": "an answer with no body", - "status": 200, - "body": null, - "state": "answered" - } - ], - "transition_cases": [ + "name": "correlation_id missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "correlation_id is required" + }, { - "name": "the reference sequence", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:12:04.118Z", - "expires_at": "2026-11-21T09:12:04.118Z", - "ticket": "v1.payload.mac", - "link": "https://ask.example.test/ask/v1.payload.mac" - }, - "now": "2026-11-19T09:12:05.000Z" - }, - { - "op": "record", - "event": { - "kind": "question", - "graph_id": "plan-assistant", - "description": "Planning assistant: the owner picks one of the plans", - "correlation_id": "release-42", - "turn": 1, - "node": "plan", - "summary": "The planning assistant asks which plan to follow", - "calls": [ - { - "id": "toolu_02B", - "name": "ask_owner", - "ask": true, - "wait": true, - "input": { - "question": "Which plan?", - "options": [ - "A", - "B", - "C" - ] - } - } - ], - "ttl": 3600, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "ticket": "v1.plan.mac", - "link": "https://ask.example.test/ask/v1.plan.mac" - }, - "now": "2026-11-19T09:20:01.000Z" - }, - { - "op": "record", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant", - "correlation_id": "order-1002-case", - "summary": "Nightly: the queue is empty" - }, - "now": "2026-11-19T09:30:00.000Z" - }, - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1002", - "amount": 174.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T09:35:00.000Z", - "expires_at": "2026-11-21T09:35:00.000Z", - "ticket": "v1.payload2.mac", - "link": "https://ask.example.test/ask/v1.payload2.mac" - }, - "now": "2026-11-19T09:35:00.500Z", - "note": "a re-advice for the same turn updates the same row with the new ticket" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1002-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "Carrier confirmed" - } - ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T09:40:00.000Z" - }, - { - "op": "record", - "event": { - "kind": "advice", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1002-case", - "turn": 2, - "node": "decide", - "summary": "The supervisor's decision was received; the assistant continues", - "details": "The assistant runs the decided call and answers the customer", - "requested_at": "2026-11-19T09:40:12.004Z" - }, - "now": "2026-11-19T09:40:12.100Z" - }, - { - "op": "expire", - "now": "2026-11-19T10:30:00.000Z", - "note": "the question's hour is over; the answered wait is untouched" - }, - { - "op": "since", - "seq": 4, - "limit": 10 - }, - { - "op": "since", - "seq": 0, - "limit": 3 - } - ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.payload.mac" - }, - { - "id": 2, - "seq": 2, - "state": "open", - "ticket": "v1.plan.mac" - }, - { - "id": 3, - "seq": 3, - "state": null, - "ticket": null - }, - { - "id": 1, - "seq": 4, - "state": "open", - "ticket": "v1.payload2.mac" - }, - { - "id": 1, - "seq": 5, - "state": "answered", - "answered_by": "operator-17" - }, - { - "id": 4, - "seq": 6, - "state": null, - "ticket": null - }, - { - "expired": [ - { - "id": 2, - "seq": 7 - } - ] - }, - { - "ids": [ - 1, - 4, - 2 - ], - "seqs": [ - 5, - 6, - 7 - ] - }, - { - "ids": [ - 3, - 1, - 4 - ], - "seqs": [ - 3, - 5, - 6 - ] - } - ], - "final": [ - { - "id": 1, - "seq": 5, - "kind": "approval", - "state": "answered", - "ticket": "v1.payload2.mac", - "turn": 2, - "requested_at": "2026-11-19T09:35:00.000Z", - "expires_at": "2026-11-21T09:35:00.000Z", - "updated_at": "2026-11-19T09:40:00.000Z", - "answered_by": "operator-17", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 + "name": "summary missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } } - }, - { - "id": 2, - "seq": 7, - "kind": "question", - "state": "expired", - "ticket": "v1.plan.mac", - "turn": 1, - "requested_at": "2026-11-19T09:20:00.000Z", - "expires_at": "2026-11-19T10:20:00.000Z", - "updated_at": "2026-11-19T10:30:00.000Z", - "answered_by": null, - "outcome": null - }, - { - "id": 3, - "seq": 3, - "kind": "advice", - "state": null, - "ticket": null, - "turn": null, - "requested_at": "2026-11-19T09:30:00.000Z", - "expires_at": null, - "updated_at": "2026-11-19T09:30:00.000Z", - "answered_by": null, - "outcome": null - }, - { - "id": 4, - "seq": 6, - "kind": "advice", - "state": null, - "ticket": null, - "turn": 2, - "requested_at": "2026-11-19T09:40:12.004Z", - "expires_at": null, - "updated_at": "2026-11-19T09:40:12.100Z", - "answered_by": null, - "outcome": null - } - ] + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "summary is required" }, { - "name": "two devices on one card - the first accepted decision stands", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1004-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1004", - "amount": 240.0, - "reason": "Shipment lost in transit" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T10:00:00.000Z", - "expires_at": "2026-11-21T10:00:00.000Z", - "ticket": "v1.two.mac", - "link": "https://ask.example.test/ask/v1.two.mac" - }, - "now": "2026-11-19T10:00:00.200Z" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "from device-2" - } - ], - "who": "device-2", - "status": 410, - "body": { - "type": "nothing-waiting", - "run": "fresh" - }, - "now": "2026-11-19T10:00:01.000Z", - "note": "two devices clicked at once; the engine took the other one's decision, so this one got nothing-waiting, and it lands first: the open row turns expired for a moment" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true, - "note": "from device-1" + "name": "node not text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": [ + "assist" + ], + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "who": "device-1", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T10:00:02.000Z", - "note": "the accepted decision always wins the row" - }, - { - "op": "answer", - "key": [ - "order-assistant", - "order-1004-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": false + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "node must be text" + }, + { + "name": "requested_at not a time", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } - ], - "who": "device-3", - "status": 410, - "body": { - "type": "nothing-waiting", - "run": "fresh" - }, - "now": "2026-11-19T10:00:03.000Z", - "note": "a nothing-waiting after the acceptance changes nothing: the row stands as device-1 left it and the sequence does not move" - }, - { - "op": "since", - "seq": 0, - "limit": 10 - } - ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.two.mac" - }, - { - "id": 1, - "seq": 2, - "state": "expired", - "answered_by": "device-2" - }, - { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "device-1" - }, - { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "device-1" - }, - { - "ids": [ - 1 - ], - "seqs": [ - 3 - ] - } - ], - "final": [ - { - "id": 1, - "seq": 3, - "kind": "approval", - "state": "answered", - "ticket": "v1.two.mac", - "turn": 2, - "requested_at": "2026-11-19T10:00:00.000Z", - "expires_at": "2026-11-21T10:00:00.000Z", - "updated_at": "2026-11-19T10:00:02.000Z", - "answered_by": "device-1", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 + } + ], + "ttl": "2d", + "requested_at": "yesterday" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "turn missing for an approval", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" } } - } - ] + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn is required for an approval or a question" + }, + { + "name": "turn negative", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -1, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "turn a boolean", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": true, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "calls empty", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "a call without an id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "name": "issue_refund" + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "ttl missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl is required for an approval or a question" + }, + { + "name": "ttl not a duration", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "soon", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "an advice with calls", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ] + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "an advice carries no calls and no ttl" + }, + { + "name": "an advice with a ttl", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "ttl": "1d" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "an advice carries no calls and no ttl" + }, + { + "name": "an advice with a negative turn", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -2, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "details not text on an advice", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": { + "text": "x" + }, + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "status": 400, + "error": "details must be text" + }, + { + "name": "a turn written as a float with a whole value is that turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn written in ASCII digits is that turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn with white space around its digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "\t2 ", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "a turn with leading zeros", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "007", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 7, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjd9.n3D1IXY2zZtLLTXz5e69oLXIs7p01zKd6vmYDNCtZTM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjd9.n3D1IXY2zZtLLTXz5e69oLXIs7p01zKd6vmYDNCtZTM" + } + }, + { + "name": "a turn of zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 0, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U" + } + }, + { + "name": "a turn of negative zero is turn zero", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": -0.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 0, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjB9.qDSpHhw2iNBRnIgDQKYhTm9tt4y8w6mgyi6jE8n751U" + } + }, + { + "name": "the largest turn", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "an advice's turn written in ASCII digits", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "3", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 3 + } + }, + { + "name": "a turn one past the largest", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2.5, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "٢", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in fullwidth digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a plus sign", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "+2", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with a point in text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2.0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with an exponent in text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2e0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn with an underscore", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "1_0", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of empty text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn in a list", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": [ + 2 + ], + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn with a fraction", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3.5, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "ttl a float with a whole value is those seconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 3600.0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": 3600, + "expires_at": "2026-11-19T10:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA4MzEyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.hP13VNMw6wipQhNjuqvPk2XOIEeUvx66QRtglEUEt9Y", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA4MzEyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.hP13VNMw6wipQhNjuqvPk2XOIEeUvx66QRtglEUEt9Y" + } + }, + { + "name": "ttl in milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1500ms", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "1500ms", + "expires_at": "2026-11-19T09:12:05.618Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTUyNSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.mscwVj1WR1Vzfn7XbyheoHpIq8BqsVRpHL5v_e4J_tA", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTUyNSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.mscwVj1WR1Vzfn7XbyheoHpIq8BqsVRpHL5v_e4J_tA" + } + }, + { + "name": "ttl with white space around it", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": " 2d\n", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": " 2d\n", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "ttl in ASCII digits without a unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "90", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "90", + "expires_at": "2026-11-19T09:13:34.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTYxNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.l-52oTdrGHesgLlKmDRY8rALzWHSnIG06kgHJQPWdo0", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTYxNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.l-52oTdrGHesgLlKmDRY8rALzWHSnIG06kgHJQPWdo0" + } + }, + { + "name": "ttl with leading zeros", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "007m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "007m", + "expires_at": "2026-11-19T09:19:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTk0NCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.fxl992NeeZ9zR0_gNhs_aXXKac3-yE1Y0bXg-HD6SHw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTA3OTk0NCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.fxl992NeeZ9zR0_gNhs_aXXKac3-yE1Y0bXg-HD6SHw" + } + }, + { + "name": "ttl with a space before its unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2 d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "٣m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in fullwidth digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "3m", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1.5, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl with a fraction and a unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1.5h", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl in an upper-case unit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2D", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of zero as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 0.0, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of zero days", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "0d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl negative", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": -5, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl a boolean", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": true, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl one second past the most milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9007199254741s", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl one past the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 9007199254740992, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "ttl of four hundred digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "a character beyond the basic plane in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-𝟟-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-𝟟-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXIt8J2fny1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.SVeH87ks-Wy5e-kyrnubiBdjj0u9211szctuBE4gywc" + } + }, + { + "name": "a quote, a backslash and a newline in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order \"1002\" \\\ncase", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order \"1002\" \\\ncase", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFxcbmNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.ae0ygxQzrDgNy0KujEN18MKMrR30K1-wwBJB3U8j5To", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXIgXCIxMDAyXCIgXFxcbmNhc2UiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.ae0ygxQzrDgNy0KujEN18MKMrR30K1-wwBJB3U8j5To" + } + }, + { + "name": "a lone surrogate in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone low surrogate at the end of the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\udfdf", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a surrogate pair the wrong way round in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "\udfdf\ud835", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in the graph id", + "message": { + "kind": "approval", + "graph_id": "order-\ud800", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in an advice's correlation id", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in an advice's graph id", + "message": { + "kind": "advice", + "graph_id": "\udc00", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a lone surrogate in the graph id is told before a description that is missing", + "message": { + "kind": "approval", + "graph_id": "order-\ud800", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id must be text without a lone surrogate" + }, + { + "name": "a description that is missing is told before a lone surrogate in the correlation id", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "correlation_id": "order-\ud800", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "a lone surrogate in the correlation id is told before a summary that is missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-\ud800", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id must be text without a lone surrogate" + }, + { + "name": "requested_at at an offset is kept as written, and the expiry is in UTC", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T10:12:04.118+01:00", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at behind UTC, across midnight", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-18T23:42:04.118-09:30" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-18T23:42:04.118-09:30", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at to the minute", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU" + } + }, + { + "name": "requested_at to the minute at an offset", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T10:12+01:00", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.kCkyDIlwoirUDB6f29h1q4pluL_H_ioODtEtNJLpyVU" + } + }, + { + "name": "requested_at with a fraction of one digit", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.1Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.1Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.100Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at with a fraction of nine digits: the expiry to the millisecond, cut", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118999999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118999999Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "requested_at on the 29th of February of a leap year", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1s", + "requested_at": "2024-02-29T23:59:59Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2024-02-29T23:59:59Z", + "turn": 2, + "ttl": "1s", + "expires_at": "2024-03-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTcwOTI1MTIwMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.6MbkxT4XOaqTJcb3A2-LiuvU6WSBCaZE41nNydnozGk", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTcwOTI1MTIwMCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.6MbkxT4XOaqTJcb3A2-LiuvU6WSBCaZE41nNydnozGk" + } + }, + { + "name": "requested_at in the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1h", + "requested_at": "0001-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0001-01-01T00:00:00Z", + "turn": 2, + "ttl": "1h", + "expires_at": "0001-01-01T01:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTYyMTM1NTkzMjAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.DbM_d16cBAoEICw6gK5rwtdOZGZA2q5wM1tOe9WyAM0", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTYyMTM1NTkzMjAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.DbM_d16cBAoEICw6gK5rwtdOZGZA2q5wM1tOe9WyAM0" + } + }, + { + "name": "requested_at in a year before 1000: the expiry's year in four digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "500ms", + "requested_at": "0999-12-31T23:59:59.5Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0999-12-31T23:59:59.5Z", + "turn": 2, + "ttl": "500ms", + "expires_at": "1000-01-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTMwNjEwMjI0MDAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Ci136R-H-WUPsfln4i6s_nyib3xVFjA2S-P32CS-_hw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTMwNjEwMjI0MDAwLCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Ci136R-H-WUPsfln4i6s_nyib3xVFjA2S-P32CS-_hw" + } + }, + { + "name": "an expiry before 1970 with a fraction: its whole seconds are the floor", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1969-12-31T23:59:58.250Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:58.250Z", + "turn": 2, + "ttl": 1, + "expires_at": "1969-12-31T23:59:59.250Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM" + } + }, + { + "name": "an expiry a millisecond before 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1s", + "requested_at": "1969-12-31T23:59:58.999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:58.999Z", + "turn": 2, + "ttl": "1s", + "expires_at": "1969-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6LTEsImciOiJvcmRlci1hc3Npc3RhbnQiLCJrIjoiYXBwcm92YWwiLCJ0IjoyfQ.wBOW5_f_KTnMKg_TLXgDjegSEr4ZRVy2A7xF6O8sxSM" + } + }, + { + "name": "an expiry at the first instant of 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1969-12-31T23:59:59Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1969-12-31T23:59:59Z", + "turn": 2, + "ttl": 1, + "expires_at": "1970-01-01T00:00:00.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.3unpQxjq7ynmWN4PYP1hm3Ov2SyvmaAL0Rp88sFR6xQ", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.3unpQxjq7ynmWN4PYP1hm3Ov2SyvmaAL0Rp88sFR6xQ" + } + }, + { + "name": "an expiry after 1970 with a fraction", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "1970-01-01T00:00:00.500Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1970-01-01T00:00:00.500Z", + "turn": 2, + "ttl": 1, + "expires_at": "1970-01-01T00:00:01.500Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.NJOXt8qoAJxLMSK2AAbi9hNJbz_qajxreewRv0RmdFc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MSwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.NJOXt8qoAJxLMSK2AAbi9hNJbz_qajxreewRv0RmdFc" + } + }, + { + "name": "the last instant a wait can expire at", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "9999-12-31T23:59:58.999Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "9999-12-31T23:59:58.999Z", + "turn": 2, + "ttl": 1, + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "the longest wait from 1970, to the last second of the year 9999", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 253402300799, + "requested_at": "1970-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "1970-01-01T00:00:00Z", + "turn": 2, + "ttl": 253402300799, + "expires_at": "9999-12-31T23:59:59.000Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "the longest wait from the first instant, in milliseconds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "315537897599999ms", + "requested_at": "0001-01-01T00:00:00Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "0001-01-01T00:00:00Z", + "turn": 2, + "ttl": "315537897599999ms", + "expires_at": "9999-12-31T23:59:59.999Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MjUzNDAyMzAwNzk5LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.Wbcpx3kVVpquCiRUUC2DP_jnQgE_QmDDLfRN6OdJGng" + } + }, + { + "name": "an advice's requested_at at an offset is kept as written", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T10:40:12.004+01:00" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T10:40:12.004+01:00", + "turn": 3 + } + }, + { + "name": "requested_at without an offset", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at a date alone", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a lower-case t", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19t09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a lower-case z", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a space for the T", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19 09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a space before", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": " 2026-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a newline after", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04Z\n" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a byte order mark before", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the basic format", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "20261119T091204Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at a week date", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-W47-4" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at to the hour", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at on the 30th of February", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-30T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at on the 29th of February of a common year", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-02-29T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at hour 24", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T24:00:00Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at second 60", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-12-31T23:59:60Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a comma for the point", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04,118Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at with a fraction of ten digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.1180000001Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset of 24 hours", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+24:00" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset without its colon", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+0100" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at at an offset in hours alone", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04+01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in Arabic-Indic digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "٢٠٢٦-11-19T09:12:04Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the year 0000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0000-06-01T00:00:00Z" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at in the year 0000 at an offset that puts the instant in the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0000-12-31T23:30:00-01:00" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at an offset puts before the year 0001", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "0001-01-01T00:00:00+00:01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at an offset puts past the year 9999", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "9999-12-31T23:59:59-00:01" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at of empty text", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "requested_at the seconds from 1970", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "1795079524" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "an advice's requested_at without an offset", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a summary that is missing is told before a requested_at that is no time", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "a requested_at that is no time is told before a turn that is missing", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04" + }, + "status": 400, + "error": "requested_at must be an ISO-8601 time" + }, + { + "name": "a wait that ends in the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2913000d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait that ends at the first instant of the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 1, + "requested_at": "9999-12-31T23:59:59Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait that ends a millisecond past the last instant", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "1ms", + "requested_at": "9999-12-31T23:59:59.999Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait from 1970 to the first second of the year 10000", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 253402300800, + "requested_at": "1970-01-01T00:00:00Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait of the most milliseconds a duration holds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "9007199254740991ms", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a wait of the most seconds a duration holds", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": 9007199254740, + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "ttl must end before the year 10000" + }, + { + "name": "a ttl that is no duration is told before a wait that ends too late", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "0", + "requested_at": "9999-12-31T23:59:59Z" + }, + "status": 400, + "error": "ttl must be a duration such as 30m, 12h or 2d (seconds, s, m, h, d) > 0" + }, + { + "name": "calls that are missing are told before a wait that ends too late", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "ttl": "2913000d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "calls must be a non-empty list of the waiting calls, each with an id" + }, + { + "name": "graph_id of a no-break space", + "message": { + "kind": "approval", + "graph_id": " ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "description of an ideographic space", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": " ", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "description is required" + }, + { + "name": "correlation_id of the line and the paragraph separator", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "

", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "correlation_id is required" + }, + { + "name": "summary of a tab, a newline and a space", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\t\n ", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of every white-space character", + "message": { + "kind": "approval", + "graph_id": "\t\n\u000b\f\r              

   ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "graph_id is required" + }, + { + "name": "an advice's summary of a figure space", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": " ", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "summary is required" + }, + { + "name": "graph_id of a byte order mark, a character of a name", + "message": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Iu-7vyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.VYtphZGvM2eH_Dz7-t-Pi3x-G9vCcABuPrBcZM4plwY", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Iu-7vyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.VYtphZGvM2eH_Dz7-t-Pi3x-G9vCcABuPrBcZM4plwY" + } + }, + { + "name": "correlation_id of a next-line character, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "…", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoiwoUiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.cXRicYp4O_kbACXcBVhkcD12XB796Z8zZPSRB3SdHUc", + "link": "https://ask.example.test/ask/v1.eyJjIjoiwoUiLCJlIjoxNzk1MjUyMzI0LCJnIjoib3JkZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6Mn0.cXRicYp4O_kbACXcBVhkcD12XB796Z8zZPSRB3SdHUc" + } + }, + { + "name": "description of a file separator, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "\u001c", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "summary of a unit separator, a character of a name", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "\u001f", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "\u001f", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.h-dFg4w2pMRjCIhuvs0Brrvl8ZECVTk0Tb5zlwLZqyI" + } + }, + { + "name": "graph_id of a zero-width space, a character of a name", + "message": { + "kind": "approval", + "graph_id": "​", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "​", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IuKAiyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OrhPNe78l87hFwb2Qx8paxqPkFABVbx6KrwFp8fyUZw", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IuKAiyIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.OrhPNe78l87hFwb2Qx8paxqPkFABVbx6KrwFp8fyUZw" + } + }, + { + "name": "an advice's summary of a group and a record separator", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 3, + "node": "acknowledge", + "summary": "\u001d\u001e", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "\u001d\u001e", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 3 + } + }, + { + "name": "graph_id with white space around a name is kept as written", + "message": { + "kind": "approval", + "graph_id": " order-assistant ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": " order-assistant ", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiBvcmRlci1hc3Npc3RhbnTCoCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.cw64YnmxZtgEyt40KmzoeS9DuCpqQP9C_fdjE-c7aAc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6IiBvcmRlci1hc3Npc3RhbnTCoCIsImsiOiJhcHByb3ZhbCIsInQiOjJ9.cw64YnmxZtgEyt40KmzoeS9DuCpqQP9C_fdjE-c7aAc" + } + }, + { + "name": "the largest turn, in ASCII digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483647", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "the largest turn, as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "requested_at": "2026-11-19T09:12:04.118Z", + "turn": 2147483647, + "ttl": "2d", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc", + "link": "https://ask.example.test/ask/v1.eyJjIjoib3JkZXItMTAwMi1jYXNlIiwiZSI6MTc5NTI1MjMyNCwiZyI6Im9yZGVyLWFzc2lzdGFudCIsImsiOiJhcHByb3ZhbCIsInQiOjIxNDc0ODM2NDd9.BLB__eeAaxcyA2VFvl06hDNpAyPcoHDlcDaGgupzktc" + } + }, + { + "name": "an advice's turn, the largest", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483647, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z", + "turn": 2147483647 + } + }, + { + "name": "a turn one past the largest, in ASCII digits", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": "2147483648", + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest, as a float", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648.0, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of 4294967296", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 4294967296, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn of the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740991, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "a turn one past the largest whole number", + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 9007199254740992, + "node": "assist", + "summary": "issue_refund for ORD-1002, 174.00 USD: 'Shipment lost in transit'", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + }, + { + "name": "an advice's turn one past the largest", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2147483648, + "node": "acknowledge", + "summary": "Your decision was received; the assistant is issuing the refund", + "details": "The next question, if any, is expected within two minutes.", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "status": 400, + "error": "turn must be a whole number >= 0" + } + ], + "readvice_cases": [ + { + "name": "the re-advice of an approval", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + }, + { + "name": "a graph that is not in the allowlist", + "payload": { + "g": "other-graph", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph other-graph is not configured for replies" + }, + { + "name": "a graph named constructor is not in the allowlist", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph constructor is not configured for replies" + }, + { + "name": "a graph named toString is not in the allowlist", + "payload": { + "g": "toString", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph toString is not configured for replies" + }, + { + "name": "a graph named valueOf is not in the allowlist", + "payload": { + "g": "valueOf", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph valueOf is not configured for replies" + }, + { + "name": "a graph named hasOwnProperty is not in the allowlist", + "payload": { + "g": "hasOwnProperty", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph hasOwnProperty is not configured for replies" + }, + { + "name": "a graph named __proto__ is not in the allowlist", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph __proto__ is not configured for replies" + }, + { + "name": "a graph named prototype is not in the allowlist", + "payload": { + "g": "prototype", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph prototype is not configured for replies" + }, + { + "name": "a graph the allowlist names __proto__", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant", + "__proto__": "http://127.0.0.1:8085/api/graph/proto" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/proto", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + }, + { + "name": "a graph the allowlist names constructor", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant", + "constructor": "http://127.0.0.1:8085/api/graph/constructor" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/constructor", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2 + } + } + } + ], + "reply_cases": [ + { + "name": "an approval with a note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z] Carrier confirmed the loss" + } + ] + } + } + }, + { + "name": "a refusal without a note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": false + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + } + ] + } + } + }, + { + "name": "a refusal with an empty note", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": false, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + } + ] + } + } + }, + { + "name": "a question's answer travels unchanged", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/plan-assistant", + "headers": { + "x-correlation-id": "release-42" + }, + "body": { + "turn": 4, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B" + } + ] + } + } + }, + { + "name": "a question's answer may be any JSON value", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": { + "plan": "B", + "why": "cheaper" + } + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/plan-assistant", + "headers": { + "x-correlation-id": "release-42" + }, + "body": { + "turn": 4, + "decisions": [ + { + "id": "toolu_02B", + "answer": { + "plan": "B", + "why": "cheaper" + } + } + ] + } + } + }, + { + "name": "a turn with a tool call and a question", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true + }, + { + "id": "toolu_02B", + "answer": "A" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "request": { + "url": "http://127.0.0.1:8085/api/graph/order-assistant", + "headers": { + "x-correlation-id": "order-1002-case" + }, + "body": { + "turn": 2, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "[operator-17 at 2026-11-19T10:00:00.000Z]" + }, + { + "id": "toolu_02B", + "answer": "A" + } + ] + } + } + }, + { + "name": "decisions empty", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "decisions must be a non-empty list, one per waiting call" + }, + { + "name": "decisions not a list", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": { + "id": "toolu_01A", + "approved": true + }, + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "decisions must be a non-empty list, one per waiting call" + }, + { + "name": "a decision without an id", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "approved": true + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision needs the id of its call" + }, + { + "name": "a decision with approved and answer", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "answer": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision carries approved (with an optional note) or answer, not both" + }, + { + "name": "a decision with neither", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "note": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "each decision carries approved (with an optional note) or answer" + }, + { + "name": "approved not a boolean", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": "yes" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "approved must be true or false" + }, + { + "name": "note not text", + "payload": { + "g": "order-assistant", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": 5 + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "note must be text" + }, + { + "name": "an answer with a note", + "payload": { + "g": "plan-assistant", + "c": "release-42", + "t": 4, + "k": "question", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_02B", + "answer": "B", + "note": "x" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 400, + "error": "a question's decision carries an answer and no note" + }, + { + "name": "a graph that is not in the allowlist", + "payload": { + "g": "other-graph", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "status": 404, + "error": "graph other-graph is not configured for replies" + }, + { + "name": "a decision for a graph named constructor, which is not in the allowlist", + "payload": { + "g": "constructor", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "status": 404, + "error": "graph constructor is not configured for replies" + }, + { + "name": "a decision for a graph named __proto__, which is not in the allowlist", + "payload": { + "g": "__proto__", + "c": "order-1002-case", + "t": 2, + "k": "approval", + "e": 1795252324 + }, + "graphs": { + "order-assistant": "http://127.0.0.1:8085/api/graph/order-assistant", + "plan-assistant": "http://127.0.0.1:8085/api/graph/plan-assistant" + }, + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed the loss" + } + ], + "who": "operator-17", + "at": "2026-11-19T10:00:00.000Z", + "status": 404, + "error": "graph __proto__ is not configured for replies" + } + ], + "outcome_cases": [ + { + "name": "the graph answered", + "engine": { + "status": 200, + "body": "{\"type\": \"answer\", \"turn\": 3, \"run\": \"resume\", \"message\": \"Your refund has been issued.\"}", + "error": null + }, + "status": 200, + "body": { + "type": "answer", + "turn": 3, + "run": "resume", + "message": "Your refund has been issued." + } + }, + { + "name": "the model asked again", + "engine": { + "status": 200, + "body": "{\"type\": \"approval\", \"turn\": 4, \"calls\": []}", + "error": null + }, + "status": 200, + "body": { + "type": "approval", + "turn": 4, + "calls": [] + } + }, + { + "name": "nothing waiting (the gate)", + "engine": { + "status": 410, + "body": "{\"type\": \"nothing-waiting\"}", + "error": null + }, + "status": 410, + "body": { + "type": "nothing-waiting" + } + }, + { + "name": "the graph refused the decisions", + "engine": { + "status": 400, + "body": "{\"type\": \"error\", \"message\": \"unknown call id\"}", + "error": null + }, + "status": 400, + "body": { + "type": "error", + "message": "unknown call id" + } + }, + { + "name": "the graph failed", + "engine": { + "status": 500, + "body": "{\"type\": \"error\", \"message\": \"boom\"}", + "error": null + }, + "status": 500, + "body": { + "type": "error", + "message": "boom" + } + }, + { + "name": "the graph answered text", + "engine": { + "status": 200, + "body": "OK", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph answered a JSON list", + "engine": { + "status": 200, + "body": "[1,2]", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph answered nothing", + "engine": { + "status": 200, + "body": "", + "error": null + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph answered outside the contract" + } + }, + { + "name": "the graph did not answer", + "engine": { + "status": null, + "body": null, + "error": "ClientConnectorError" + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - ClientConnectorError" + } + }, + { + "name": "the graph timed out", + "engine": { + "status": null, + "body": null, + "error": "TimeoutError" + }, + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - TimeoutError" + } + } + ], + "record_cases": [ + { + "name": "an approval", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": [ + "order-assistant", + "order-1002-case", + 2 + ], + "row": { + "kind": "approval", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": 2, + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac", + "description": "Customer-support assistant: a refund waits for a supervisor", + "summary": "A refund waits for the supervisor's decision", + "details": null, + "message": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "state": "open", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "a question", + "event": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": [ + "plan-assistant", + "release-42", + 1 + ], + "row": { + "kind": "question", + "graph_id": "plan-assistant", + "correlation_id": "release-42", + "turn": 1, + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac", + "description": "Planning assistant: the owner picks one of the plans", + "summary": "The planning assistant asks which plan to follow", + "details": null, + "message": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "state": "open", + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "an advice with a turn", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": null, + "row": { + "kind": "advice", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": 2, + "ticket": null, + "link": null, + "description": "Customer-support assistant: a refund waits for a supervisor", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "state": null, + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": null, + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + }, + { + "name": "an advice without a turn or a requested_at takes now", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "now": "2026-11-19T09:12:05.000Z", + "key": null, + "row": { + "kind": "advice", + "graph_id": "order-assistant", + "correlation_id": "order-1002-case", + "turn": null, + "ticket": null, + "link": null, + "description": "Customer-support assistant", + "summary": "Nightly: the queue is empty", + "details": null, + "message": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "state": null, + "requested_at": "2026-11-19T09:12:05.000Z", + "expires_at": null, + "updated_at": "2026-11-19T09:12:05.000Z", + "answered_at": null, + "answered_by": null, + "decisions": null, + "outcome": null + } + } + ], + "answer_cases": [ + { + "name": "the engine answered", + "status": 200, + "body": { + "type": "answer", + "turn": 3, + "message": "Your refund has been issued." + }, + "state": "answered" + }, + { + "name": "the model asked again", + "status": 200, + "body": { + "type": "approval", + "turn": 4, + "calls": [] + }, + "state": "answered" + }, + { + "name": "the loop refused the decision - the graph re-advised with the error", + "status": 200, + "body": { + "type": "approval", + "turn": 2, + "error": "not a call waiting for approval" + }, + "state": "open" + }, + { + "name": "nothing waiting by status", + "status": 410, + "body": { + "type": "nothing-waiting" + }, + "state": "expired" + }, + { + "name": "nothing waiting by type", + "status": 200, + "body": { + "type": "nothing-waiting" + }, + "state": "expired" + }, + { + "name": "the ticket expired at the reply endpoint", + "status": 410, + "body": { + "type": "expired", + "message": "Ticket expired" + }, + "state": "expired" + }, + { + "name": "the reply endpoint refused the decisions", + "status": 400, + "body": { + "type": "error", + "message": "each decision needs the id of its call" + }, + "state": "open" + }, + { + "name": "the graph did not answer", + "status": 502, + "body": { + "type": "error", + "message": "the graph did not answer - TimeoutError" + }, + "state": "open" + }, + { + "name": "the reply endpoint did not answer", + "status": 502, + "body": { + "type": "error", + "message": "the reply endpoint did not answer - ClientConnectorError" + }, + "state": "open" + }, + { + "name": "an answer with no body", + "status": 200, + "body": null, + "state": "answered" + } + ], + "transition_cases": [ + { + "name": "the reference sequence", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.payload.mac", + "link": "https://ask.example.test/ask/v1.payload.mac" + }, + "now": "2026-11-19T09:12:05.000Z" + }, + { + "op": "record", + "event": { + "kind": "question", + "graph_id": "plan-assistant", + "description": "Planning assistant: the owner picks one of the plans", + "correlation_id": "release-42", + "turn": 1, + "node": "plan", + "summary": "The planning assistant asks which plan to follow", + "calls": [ + { + "id": "toolu_02B", + "name": "ask_owner", + "ask": true, + "wait": true, + "input": { + "question": "Which plan?", + "options": [ + "A", + "B", + "C" + ] + } + } + ], + "ttl": 3600, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "ticket": "v1.plan.mac", + "link": "https://ask.example.test/ask/v1.plan.mac" + }, + "now": "2026-11-19T09:20:01.000Z" + }, + { + "op": "record", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant", + "correlation_id": "order-1002-case", + "summary": "Nightly: the queue is empty" + }, + "now": "2026-11-19T09:30:00.000Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:35:00.000Z", + "expires_at": "2026-11-21T09:35:00.000Z", + "ticket": "v1.payload2.mac", + "link": "https://ask.example.test/ask/v1.payload2.mac" + }, + "now": "2026-11-19T09:35:00.500Z", + "note": "a re-advice for the same turn updates the same row with the new ticket" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1002-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "Carrier confirmed" + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T09:40:00.000Z" + }, + { + "op": "record", + "event": { + "kind": "advice", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "decide", + "summary": "The supervisor's decision was received; the assistant continues", + "details": "The assistant runs the decided call and answers the customer", + "requested_at": "2026-11-19T09:40:12.004Z" + }, + "now": "2026-11-19T09:40:12.100Z" + }, + { + "op": "expire", + "now": "2026-11-19T10:30:00.000Z", + "note": "the question's hour is over; the answered wait is untouched" + }, + { + "op": "since", + "seq": 4, + "limit": 10 + }, + { + "op": "since", + "seq": 0, + "limit": 3 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.payload.mac" + }, + { + "id": 2, + "seq": 2, + "state": "open", + "ticket": "v1.plan.mac" + }, + { + "id": 3, + "seq": 3, + "state": null, + "ticket": null + }, + { + "id": 1, + "seq": 4, + "state": "open", + "ticket": "v1.payload2.mac" + }, + { + "id": 1, + "seq": 5, + "state": "answered", + "answered_by": "operator-17" + }, + { + "id": 4, + "seq": 6, + "state": null, + "ticket": null + }, + { + "expired": [ + { + "id": 2, + "seq": 7 + } + ] + }, + { + "ids": [ + 1, + 4, + 2 + ], + "seqs": [ + 5, + 6, + 7 + ] + }, + { + "ids": [ + 3, + 1, + 4 + ], + "seqs": [ + 3, + 5, + 6 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 5, + "kind": "approval", + "state": "answered", + "ticket": "v1.payload2.mac", + "turn": 2, + "requested_at": "2026-11-19T09:35:00.000Z", + "expires_at": "2026-11-21T09:35:00.000Z", + "updated_at": "2026-11-19T09:40:00.000Z", + "answered_by": "operator-17", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + }, + { + "id": 2, + "seq": 7, + "kind": "question", + "state": "expired", + "ticket": "v1.plan.mac", + "turn": 1, + "requested_at": "2026-11-19T09:20:00.000Z", + "expires_at": "2026-11-19T10:20:00.000Z", + "updated_at": "2026-11-19T10:30:00.000Z", + "answered_by": null, + "outcome": null + }, + { + "id": 3, + "seq": 3, + "kind": "advice", + "state": null, + "ticket": null, + "turn": null, + "requested_at": "2026-11-19T09:30:00.000Z", + "expires_at": null, + "updated_at": "2026-11-19T09:30:00.000Z", + "answered_by": null, + "outcome": null + }, + { + "id": 4, + "seq": 6, + "kind": "advice", + "state": null, + "ticket": null, + "turn": 2, + "requested_at": "2026-11-19T09:40:12.004Z", + "expires_at": null, + "updated_at": "2026-11-19T09:40:12.100Z", + "answered_by": null, + "outcome": null + } + ] + }, + { + "name": "two devices on one card - the first accepted decision stands", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1004-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1004", + "amount": 240.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:00:00.000Z", + "expires_at": "2026-11-21T10:00:00.000Z", + "ticket": "v1.two.mac", + "link": "https://ask.example.test/ask/v1.two.mac" + }, + "now": "2026-11-19T10:00:00.200Z" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "from device-2" + } + ], + "who": "device-2", + "status": 410, + "body": { + "type": "nothing-waiting", + "run": "fresh" + }, + "now": "2026-11-19T10:00:01.000Z", + "note": "two devices clicked at once; the engine took the other one's decision, so this one got nothing-waiting, and it lands first: the open row turns expired for a moment" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true, + "note": "from device-1" + } + ], + "who": "device-1", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T10:00:02.000Z", + "note": "the accepted decision always wins the row" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1004-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": false + } + ], + "who": "device-3", + "status": 410, + "body": { + "type": "nothing-waiting", + "run": "fresh" + }, + "now": "2026-11-19T10:00:03.000Z", + "note": "a nothing-waiting after the acceptance changes nothing: the row stands as device-1 left it and the sequence does not move" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.two.mac" + }, + { + "id": 1, + "seq": 2, + "state": "expired", + "answered_by": "device-2" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "device-1" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "device-1" + }, + { + "ids": [ + 1 + ], + "seqs": [ + 3 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered", + "ticket": "v1.two.mac", + "turn": 2, + "requested_at": "2026-11-19T10:00:00.000Z", + "expires_at": "2026-11-21T10:00:00.000Z", + "updated_at": "2026-11-19T10:00:02.000Z", + "answered_by": "device-1", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + } + ] + }, + { + "name": "an older message landing late never overwrites a newer row, and an answer needs a recorded wait", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T11:00:00.000Z", + "expires_at": "2026-11-21T11:00:00.000Z", + "ticket": "v1.first.mac", + "link": "https://ask.example.test/ask/v1.first.mac" + }, + "now": "2026-11-19T11:00:00.200Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:59:00.000Z", + "expires_at": "2026-11-21T10:59:00.000Z", + "ticket": "v1.stale.mac", + "link": "https://ask.example.test/ask/v1.stale.mac" + }, + "now": "2026-11-19T11:00:00.300Z", + "note": "a message older than the row lands late (two recorder workers, or a redelivery): the row stands and the sequence does not move" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1007-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1007", + "amount": 60.0, + "reason": "Damaged on arrival" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T11:05:00.000Z", + "expires_at": "2026-11-21T11:05:00.000Z", + "ticket": "v1.newer.mac", + "link": "https://ask.example.test/ask/v1.newer.mac" + }, + "now": "2026-11-19T11:05:00.100Z", + "note": "a newer re-advice updates the row with its ticket" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-1007-case", + 2 + ], + "decisions": [ + { + "id": "toolu_01A", + "approved": true + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 3 + }, + "now": "2026-11-19T11:06:00.000Z" + }, + { + "op": "answer", + "key": [ + "order-assistant", + "order-9999-case", + 7 + ], + "decisions": [ + { + "id": "toolu_09Z", + "approved": true + } + ], + "who": "operator-17", + "status": 200, + "body": { + "type": "answer", + "turn": 8 + }, + "now": "2026-11-19T11:06:30.000Z", + "note": "an answer for a wait that was never recorded: nothing to write, the result is null" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.newer.mac" + }, + { + "id": 1, + "seq": 3, + "state": "answered", + "answered_by": "operator-17" + }, + null, + { + "ids": [ + 1 + ], + "seqs": [ + 3 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 3, + "kind": "approval", + "state": "answered", + "ticket": "v1.newer.mac", + "turn": 2, + "requested_at": "2026-11-19T11:05:00.000Z", + "expires_at": "2026-11-21T11:05:00.000Z", + "updated_at": "2026-11-19T11:06:00.000Z", + "answered_by": "operator-17", + "outcome": { + "status": 200, + "body": { + "type": "answer", + "turn": 3 + } + } + } + ] + }, + { + "name": "times in another spelling are ordered by their instants, never by their texts", + "steps": [ + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:12:04.118+01:00", + "expires_at": "2026-11-21T09:12:04.118Z", + "ticket": "v1.first.mac", + "link": "https://ask.example.test/ask/v1.first.mac" + }, + "now": "2026-11-19T09:12:05.000Z" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:30:00Z", + "expires_at": "2026-11-21T09:30:00.000Z", + "ticket": "v1.second.mac", + "link": "https://ask.example.test/ask/v1.second.mac" + }, + "now": "2026-11-19T09:30:01.000Z", + "note": "a later instant whose text sorts before the row's: the row is updated" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T10:00:00+02:00", + "expires_at": "2026-11-21T08:00:00.000Z", + "ticket": "v1.late.mac", + "link": "https://ask.example.test/ask/v1.late.mac" + }, + "now": "2026-11-19T09:31:00.000Z", + "note": "an earlier instant whose text sorts after the row's: the row is kept" + }, + { + "op": "record", + "event": { + "kind": "approval", + "graph_id": "order-assistant", + "description": "Customer-support assistant: a refund waits for a supervisor", + "correlation_id": "order-1002-case", + "turn": 2, + "node": "assist", + "summary": "A refund waits for the supervisor's decision", + "calls": [ + { + "id": "toolu_01A", + "name": "issue_refund", + "route": "demo.refund.issue", + "wait": true, + "input": { + "order_id": "ORD-1002", + "amount": 174.0, + "reason": "Shipment lost in transit" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:30:00.000+00:00", + "expires_at": "2026-11-21T09:30:00.000Z", + "ticket": "v1.same.mac", + "link": "https://ask.example.test/ask/v1.same.mac" + }, + "now": "2026-11-19T09:32:00.000Z", + "note": "the same instant in another spelling is not older: the row is updated" + }, + { + "op": "expire", + "now": "2026-11-21T10:30:00+01:00", + "note": "the instant of the expiry itself, written at an offset: not past it" + }, + { + "op": "expire", + "now": "2026-11-21T09:30:00.001Z", + "note": "a millisecond past the expiry" + }, + { + "op": "since", + "seq": 0, + "limit": 10 + } + ], + "results": [ + { + "id": 1, + "seq": 1, + "state": "open", + "ticket": "v1.first.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.second.mac" + }, + { + "id": 1, + "seq": 2, + "state": "open", + "ticket": "v1.second.mac" + }, + { + "id": 1, + "seq": 3, + "state": "open", + "ticket": "v1.same.mac" + }, + { + "expired": [] + }, + { + "expired": [ + { + "id": 1, + "seq": 4 + } + ] + }, + { + "ids": [ + 1 + ], + "seqs": [ + 4 + ] + } + ], + "final": [ + { + "id": 1, + "seq": 4, + "kind": "approval", + "state": "expired", + "ticket": "v1.same.mac", + "turn": 2, + "requested_at": "2026-11-19T09:30:00.000+00:00", + "expires_at": "2026-11-21T09:30:00.000Z", + "updated_at": "2026-11-21T09:30:00.001Z", + "answered_by": null, + "outcome": null + } + ] + } + ], + "number_cases": [ + { + "name": "ASCII digits", + "value": "512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a single digit", + "value": "1", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "zero as text", + "value": "0", + "whole": 0, + "duration_ms": 0 + }, + { + "name": "leading zeros", + "value": "007", + "whole": 7, + "duration_ms": 7000 + }, + { + "name": "forty leading zeros", + "value": "00000000000000000000000000000000000000001", + "whole": 1, + "duration_ms": 1000 + }, + { + "name": "spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a tab and a newline around", + "value": "\t512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "no-break spaces around", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "an ideographic space before", + "value": " 512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a line separator before", + "value": "
512", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "a space inside", + "value": "5 12", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark after", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after", + "value": "512…", + "whole": null, + "duration_ms": null + }, + { + "name": "a file separator before", + "value": "\u001c512", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit separator after", + "value": "512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "a zero-width space before", + "value": "​512", + "whole": null, + "duration_ms": null + }, + { + "name": "empty text", + "value": "", + "whole": null, + "duration_ms": null + }, + { + "name": "blank text", + "value": " ", + "whole": null, + "duration_ms": null + }, + { + "name": "a plus sign", + "value": "+5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign", + "value": "-5", + "whole": null, + "duration_ms": null + }, + { + "name": "an underscore", + "value": "5_0", + "whole": null, + "duration_ms": null + }, + { + "name": "a point in text", + "value": "5.0", + "whole": null, + "duration_ms": null + }, + { + "name": "an exponent in text", + "value": "5e2", + "whole": null, + "duration_ms": null + }, + { + "name": "hexadecimal text", + "value": "0x10", + "whole": null, + "duration_ms": null + }, + { + "name": "a word", + "value": "five", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic digit", + "value": "٣", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic digits", + "value": "٥١٢", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then Arabic-Indic", + "value": "5٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth digits", + "value": "512", + "whole": null, + "duration_ms": null + }, + { + "name": "a Devanagari digit", + "value": "५", + "whole": null, + "duration_ms": null + }, + { + "name": "a mathematical bold digit", + "value": "𝟓", + "whole": null, + "duration_ms": null + }, + { + "name": "superscript two", + "value": "²", + "whole": null, + "duration_ms": null + }, + { + "name": "ASCII then superscript", + "value": "5²", + "whole": null, + "duration_ms": null + }, + { + "name": "subscript two", + "value": "₂", + "whole": null, + "duration_ms": null + }, + { + "name": "a circled digit", + "value": "①", + "whole": null, + "duration_ms": null + }, + { + "name": "a vulgar fraction", + "value": "½", + "whole": null, + "duration_ms": null + }, + { + "name": "a Roman numeral", + "value": "Ⅷ", + "whole": null, + "duration_ms": null + }, + { + "name": "an ideographic number", + "value": "五", + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as text", + "value": "9007199254740991", + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest as text", + "value": "9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines", + "value": "99999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "four hundred nines", + "value": "9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "whole": null, + "duration_ms": null + }, + { + "name": "a number", + "value": 512, + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "zero", + "value": 0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative number", + "value": -5, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number", + "value": 9007199254740991, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "one above the largest", + "value": 9007199254740992, + "whole": null, + "duration_ms": null + }, + { + "name": "a number of twenty nines", + "value": 99999999999999999999, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a whole value", + "value": 16000.0, + "whole": 16000, + "duration_ms": 16000000 + }, + { + "name": "float zero", + "value": 0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "negative zero", + "value": -0.0, + "whole": 0, + "duration_ms": 0 + }, + { + "name": "a negative float with a whole value", + "value": -1.0, + "whole": null, + "duration_ms": null + }, + { + "name": "a float with a fraction", + "value": 2.5, + "whole": null, + "duration_ms": null + }, + { + "name": "a float just above a whole value", + "value": 5.000000000000001, + "whole": null, + "duration_ms": null + }, + { + "name": "the largest whole number as a float", + "value": 9007199254740991.0, + "whole": 9007199254740991, + "duration_ms": null + }, + { + "name": "a float above the largest", + "value": 1e+16, + "whole": null, + "duration_ms": null + }, + { + "name": "a huge float", + "value": 1e+300, + "whole": null, + "duration_ms": null + }, + { + "name": "true", + "value": true, + "whole": null, + "duration_ms": null + }, + { + "name": "false", + "value": false, + "whole": null, + "duration_ms": null + }, + { + "name": "null", + "value": null, + "whole": null, + "duration_ms": null + }, + { + "name": "a list", + "value": [ + 5 + ], + "whole": null, + "duration_ms": null + }, + { + "name": "a map", + "value": { + "value": 5 + }, + "whole": null, + "duration_ms": null + }, + { + "name": "minutes", + "value": "30m", + "whole": null, + "duration_ms": 1800000 + }, + { + "name": "hours", + "value": "12h", + "whole": null, + "duration_ms": 43200000 + }, + { + "name": "days", + "value": "2d", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "seconds", + "value": "45s", + "whole": null, + "duration_ms": 45000 + }, + { + "name": "zero days", + "value": "0d", + "whole": null, + "duration_ms": 0 + }, + { + "name": "spaces around a duration", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "a space before the unit", + "value": "2 d", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case unit", + "value": "2D", + "whole": null, + "duration_ms": null + }, + { + "name": "an unknown unit", + "value": "2w", + "whole": null, + "duration_ms": null + }, + { + "name": "two units", + "value": "1d12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fraction of an hour", + "value": "1.5h", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit alone", + "value": "d", + "whole": null, + "duration_ms": null + }, + { + "name": "Arabic-Indic hours", + "value": "٣h", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth hours", + "value": "12h", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth unit", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a byte order mark before a duration", + "value": "2d", + "whole": null, + "duration_ms": null + }, + { + "name": "a next-line character after a duration", + "value": "2d…", + "whole": null, + "duration_ms": null + }, + { + "name": "days past the most milliseconds", + "value": "104249991374d", + "whole": null, + "duration_ms": null + }, + { + "name": "a day more past the most milliseconds", + "value": "104249991375d", + "whole": null, + "duration_ms": null + }, + { + "name": "twenty nines of days", + "value": "99999999999999999999d", + "whole": null, + "duration_ms": null + }, + { + "name": "a range of pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages and ranges", + "value": "1-3,7", + "whole": null, + "duration_ms": null + }, + { + "name": "pages in the order named", + "value": "7,1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with spaces", + "value": " 2 - 3 , 1 ", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with no-break spaces", + "value": "1 - 3", + "whole": null, + "duration_ms": null + }, + { + "name": "two pages without a comma", + "value": "1 3", + "whole": null, + "duration_ms": null + }, + { + "name": "a space inside a page of a range", + "value": "1 0-12", + "whole": null, + "duration_ms": null + }, + { + "name": "line breaks around a hyphen", + "value": "1\n-\n3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a byte order mark", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "pages with a next-line character", + "value": "1…-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an Arabic-Indic page", + "value": "1-٣", + "whole": null, + "duration_ms": null + }, + { + "name": "fullwidth pages", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a fullwidth hyphen", + "value": "1-3", + "whole": null, + "duration_ms": null + }, + { + "name": "an en dash", + "value": "1–3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range from page zero", + "value": "0-3", + "whole": null, + "duration_ms": null + }, + { + "name": "a range to the largest page", + "value": "1-9007199254740991", + "whole": null, + "duration_ms": null + }, + { + "name": "a range beyond the largest page", + "value": "1-9007199254740992", + "whole": null, + "duration_ms": null + }, + { + "name": "milliseconds", + "value": "500ms", + "whole": null, + "duration_ms": 500 + }, + { + "name": "zero milliseconds", + "value": "0ms", + "whole": null, + "duration_ms": 0 + }, + { + "name": "leading zeros and a unit", + "value": "007m", + "whole": null, + "duration_ms": 420000 + }, + { + "name": "spaces around milliseconds", + "value": " 250ms ", + "whole": null, + "duration_ms": 250 + }, + { + "name": "a space before ms", + "value": "500 ms", + "whole": null, + "duration_ms": null + }, + { + "name": "an upper-case ms", + "value": "500MS", + "whole": null, + "duration_ms": null + }, + { + "name": "ms alone", + "value": "ms", + "whole": null, + "duration_ms": null + }, + { + "name": "ms then s", + "value": "5mss", + "whole": null, + "duration_ms": null + }, + { + "name": "a unit before the number", + "value": "s5", + "whole": null, + "duration_ms": null + }, + { + "name": "a minus sign and a unit", + "value": "-5s", + "whole": null, + "duration_ms": null + }, + { + "name": "a float and a unit", + "value": "5.0s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most milliseconds", + "value": "9007199254740991ms", + "whole": null, + "duration_ms": 9007199254740991 + }, + { + "name": "one millisecond more", + "value": "9007199254740992ms", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds", + "value": "9007199254740s", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more", + "value": "9007199254741s", + "whole": null, + "duration_ms": null + }, + { + "name": "the most seconds without a unit", + "value": "9007199254740", + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more without a unit", + "value": "9007199254741", + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a number", + "value": 9007199254740, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "one second more as a number", + "value": 9007199254741, + "whole": 9007199254741, + "duration_ms": null + }, + { + "name": "the most seconds as a float", + "value": 9007199254740.0, + "whole": 9007199254740, + "duration_ms": 9007199254740000 + }, + { + "name": "the most minutes", + "value": "150119987579m", + "whole": null, + "duration_ms": 9007199254740000 + }, + { + "name": "one minute more", + "value": "150119987580m", + "whole": null, + "duration_ms": null + }, + { + "name": "the most hours", + "value": "2501999792h", + "whole": null, + "duration_ms": 9007199251200000 + }, + { + "name": "one hour more", + "value": "2501999793h", + "whole": null, + "duration_ms": null + }, + { + "name": "the most days", + "value": "104249991d", + "whole": null, + "duration_ms": 9007199222400000 + }, + { + "name": "one day more", + "value": "104249992d", + "whole": null, + "duration_ms": null + }, + { + "name": "five thousand nines of seconds", + "value": "99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999s", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0009 around a number, white space in both runtimes", + "value": "\t512\t", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000A around a number, white space in both runtimes", + "value": "\n512\n", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000B around a number, white space in both runtimes", + "value": "\u000b512\u000b", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000C around a number, white space in both runtimes", + "value": "\f512\f", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+000D around a number, white space in both runtimes", + "value": "\r512\r", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0020 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+00A0 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+1680 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2001 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2002 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2003 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2004 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2005 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2006 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2007 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2008 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2009 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+200A around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2028 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+2029 around a number, white space in both runtimes", + "value": "
512
", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+202F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+205F around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+3000 around a number, white space in both runtimes", + "value": " 512 ", + "whole": 512, + "duration_ms": 512000 + }, + { + "name": "U+0009 around a duration, white space in both runtimes", + "value": "\t2d\t", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+00A0 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+2029 around a duration, white space in both runtimes", + "value": "
2d
", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+3000 around a duration, white space in both runtimes", + "value": " 2d ", + "whole": null, + "duration_ms": 172800000 + }, + { + "name": "U+001C around a number, white space in neither or in one runtime", + "value": "\u001c512\u001c", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001D around a number, white space in neither or in one runtime", + "value": "\u001d512\u001d", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001E around a number, white space in neither or in one runtime", + "value": "\u001e512\u001e", + "whole": null, + "duration_ms": null + }, + { + "name": "U+001F around a number, white space in neither or in one runtime", + "value": "\u001f512\u001f", + "whole": null, + "duration_ms": null + }, + { + "name": "U+0085 around a number, white space in neither or in one runtime", + "value": "…512…", + "whole": null, + "duration_ms": null + }, + { + "name": "U+180E around a number, white space in neither or in one runtime", + "value": "᠎512᠎", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200B around a number, white space in neither or in one runtime", + "value": "​512​", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200C around a number, white space in neither or in one runtime", + "value": "‌512‌", + "whole": null, + "duration_ms": null + }, + { + "name": "U+200D around a number, white space in neither or in one runtime", + "value": "‍512‍", + "whole": null, + "duration_ms": null + }, + { + "name": "U+2060 around a number, white space in neither or in one runtime", + "value": "⁠512⁠", + "whole": null, + "duration_ms": null + }, + { + "name": "U+FEFF around a number, white space in neither or in one runtime", + "value": "512", + "whole": null, + "duration_ms": null + } + ], + "switch_cases": [ + { + "name": "the boolean true", + "value": true, + "switch": true + }, + { + "name": "the boolean false", + "value": false, + "switch": false + }, + { + "name": "the text true", + "value": "true", + "switch": true + }, + { + "name": "the text false", + "value": "false", + "switch": false + }, + { + "name": "TRUE in upper case", + "value": "TRUE", + "switch": true + }, + { + "name": "FALSE in upper case", + "value": "FALSE", + "switch": false + }, + { + "name": "True with a capital", + "value": "True", + "switch": true + }, + { + "name": "False with a capital", + "value": "False", + "switch": false + }, + { + "name": "tRuE in mixed case", + "value": "tRuE", + "switch": true + }, + { + "name": "fAlSe in mixed case", + "value": "fAlSe", + "switch": false + }, + { + "name": "no value", + "value": null, + "switch": "default" + }, + { + "name": "an empty value", + "value": "", + "switch": "default" + }, + { + "name": "a blank value", + "value": " ", + "switch": null + }, + { + "name": "a space before true", + "value": " true", + "switch": null + }, + { + "name": "a space after true", + "value": "true ", + "switch": null + }, + { + "name": "a newline after false", + "value": "false\n", + "switch": null + }, + { + "name": "yes", + "value": "yes", + "switch": null + }, + { + "name": "no", + "value": "no", + "switch": null + }, + { + "name": "on", + "value": "on", + "switch": null + }, + { + "name": "off", + "value": "off", + "switch": null + }, + { + "name": "the text 1", + "value": "1", + "switch": null + }, + { + "name": "the text 0", + "value": "0", + "switch": null + }, + { + "name": "the letter t", + "value": "t", + "switch": null + }, + { + "name": "the letter f", + "value": "f", + "switch": null + }, + { + "name": "enabled", + "value": "enabled", + "switch": null + }, + { + "name": "maybe", + "value": "maybe", + "switch": null + }, + { + "name": "truefalse", + "value": "truefalse", + "switch": null + }, + { + "name": "the number 1", + "value": 1, + "switch": null + }, + { + "name": "the number 0", + "value": 0, + "switch": null + }, + { + "name": "the number 1.0", + "value": 1.0, + "switch": null + }, + { + "name": "a list holding true", + "value": [ + true + ], + "switch": null + }, + { + "name": "an empty list", + "value": [], + "switch": null + }, + { + "name": "a map", + "value": { + "value": true + }, + "switch": null + }, + { + "name": "fullwidth true", + "value": "true", + "switch": null + }, + { + "name": "true with a Cyrillic e", + "value": "truе", + "switch": null + }, + { + "name": "true with a dotted capital I after it", + "value": "trueİ", + "switch": null + } + ], + "time_cases": [ + { + "name": "a time in UTC to the second", + "text": "2026-11-20T10:00:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a time in UTC to the millisecond", + "text": "2026-11-20T10:00:00.123Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a time in UTC to the minute", + "text": "2026-11-20T10:00Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "a fraction of one digit", + "text": "2026-11-20T10:00:00.1Z", + "ms": 1795168800100, + "stamp": "2026-11-20T10:00:00.100Z" + }, + { + "name": "a fraction of two digits", + "text": "2026-11-20T10:00:00.12Z", + "ms": 1795168800120, + "stamp": "2026-11-20T10:00:00.120Z" + }, + { + "name": "a fraction of six digits is cut after the third", + "text": "2026-11-20T10:00:00.123456Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction of nine digits is cut after the third", + "text": "2026-11-20T10:00:00.123456789Z", + "ms": 1795168800123, + "stamp": "2026-11-20T10:00:00.123Z" + }, + { + "name": "a fraction that would round up is cut", + "text": "2026-11-20T10:00:00.9996Z", + "ms": 1795168800999, + "stamp": "2026-11-20T10:00:00.999Z" + }, + { + "name": "a fraction of nine nines", + "text": "2026-11-20T23:59:59.999999999Z", + "ms": 1795219199999, + "stamp": "2026-11-20T23:59:59.999Z" + }, + { + "name": "a fraction of zeros", + "text": "2026-11-20T10:00:00.000Z", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset ahead of UTC", + "text": "2026-11-20T10:00:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset behind UTC", + "text": "2026-11-20T10:00:00-08:00", + "ms": 1795197600000, + "stamp": "2026-11-20T18:00:00.000Z" + }, + { + "name": "an offset of half an hour", + "text": "2026-11-20T10:00:00+05:30", + "ms": 1795149000000, + "stamp": "2026-11-20T04:30:00.000Z" + }, + { + "name": "an offset of three quarters of an hour", + "text": "2026-11-20T10:00:00.5+05:45", + "ms": 1795148100500, + "stamp": "2026-11-20T04:15:00.500Z" + }, + { + "name": "the largest offset ahead of UTC", + "text": "2026-11-20T10:00:00+23:59", + "ms": 1795082460000, + "stamp": "2026-11-19T10:01:00.000Z" + }, + { + "name": "the largest offset behind UTC", + "text": "2026-11-20T10:00:00-23:59", + "ms": 1795255140000, + "stamp": "2026-11-21T09:59:00.000Z" + }, + { + "name": "an offset of plus nothing", + "text": "2026-11-20T10:00:00+00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "an offset of minus nothing", + "text": "2026-11-20T10:00:00-00:00", + "ms": 1795168800000, + "stamp": "2026-11-20T10:00:00.000Z" + }, + { + "name": "to the minute at an offset", + "text": "2026-11-20T10:00+01:00", + "ms": 1795165200000, + "stamp": "2026-11-20T09:00:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year before", + "text": "2026-01-01T00:30:00+01:00", + "ms": 1767223800000, + "stamp": "2025-12-31T23:30:00.000Z" + }, + { + "name": "an offset that crosses midnight into the year after", + "text": "2026-12-31T23:30:00-01:00", + "ms": 1798763400000, + "stamp": "2027-01-01T00:30:00.000Z" + }, + { + "name": "an offset that crosses the 29th of February", + "text": "2024-03-01T00:00:00+00:01", + "ms": 1709251140000, + "stamp": "2024-02-29T23:59:00.000Z" + }, + { + "name": "midnight", + "text": "2026-11-20T00:00:00Z", + "ms": 1795132800000, + "stamp": "2026-11-20T00:00:00.000Z" + }, + { + "name": "the last second of a day", + "text": "2026-11-20T23:59:59Z", + "ms": 1795219199000, + "stamp": "2026-11-20T23:59:59.000Z" + }, + { + "name": "the 29th of February of a leap year", + "text": "2024-02-29T12:00:00Z", + "ms": 1709208000000, + "stamp": "2024-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 2000", + "text": "2000-02-29T12:00:00Z", + "ms": 951825600000, + "stamp": "2000-02-29T12:00:00.000Z" + }, + { + "name": "the 29th of February of the year 0004", + "text": "0004-02-29T12:00:00Z", + "ms": -62035848000000, + "stamp": "0004-02-29T12:00:00.000Z" + }, + { + "name": "the 31st of January", + "text": "2026-01-31T12:00:00Z", + "ms": 1769860800000, + "stamp": "2026-01-31T12:00:00.000Z" + }, + { + "name": "the 30th of April", + "text": "2026-04-30T12:00:00Z", + "ms": 1777550400000, + "stamp": "2026-04-30T12:00:00.000Z" + }, + { + "name": "the 31st of December", + "text": "2026-12-31T12:00:00Z", + "ms": 1798718400000, + "stamp": "2026-12-31T12:00:00.000Z" + }, + { + "name": "the first instant of 1970", + "text": "1970-01-01T00:00:00Z", + "ms": 0, + "stamp": "1970-01-01T00:00:00.000Z" + }, + { + "name": "an instant before 1970", + "text": "1969-12-31T23:59:59.250Z", + "ms": -750, + "stamp": "1969-12-31T23:59:59.250Z" + }, + { + "name": "a year before 1000", + "text": "0999-12-31T23:59:59Z", + "ms": -30610224001000, + "stamp": "0999-12-31T23:59:59.000Z" + }, + { + "name": "a year of two significant digits", + "text": "0033-04-03T15:00:00+02:00", + "ms": -61117758000000, + "stamp": "0033-04-03T13:00:00.000Z" + }, + { + "name": "the first instant both packs write", + "text": "0001-01-01T00:00:00Z", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant both packs write", + "text": "9999-12-31T23:59:59.999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the last instant, with a longer fraction", + "text": "9999-12-31T23:59:59.999999999Z", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written at an offset", + "text": "0001-01-01T00:01:00+00:01", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written at an offset", + "text": "9999-12-31T23:58:59.999-00:01", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "the first instant, written a day later at the largest offset", + "text": "0001-01-01T23:59:00+23:59", + "ms": -62135596800000, + "stamp": "0001-01-01T00:00:00.000Z" + }, + { + "name": "the last instant, written a day earlier at the largest offset", + "text": "9999-12-31T00:00:59.999-23:59", + "ms": 253402300799999, + "stamp": "9999-12-31T23:59:59.999Z" + }, + { + "name": "no offset", + "text": "2026-11-20T10:00:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, to the minute", + "text": "2026-11-20T10:00", + "ms": null, + "stamp": null + }, + { + "name": "no offset, with a fraction", + "text": "2026-11-20T10:00:00.123", + "ms": null, + "stamp": null + }, + { + "name": "a date alone", + "text": "2026-11-20", + "ms": null, + "stamp": null + }, + { + "name": "a time alone", + "text": "10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case t", + "text": "2026-11-20t10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a lower-case z", + "text": "2026-11-20T10:00:00z", + "ms": null, + "stamp": null + }, + { + "name": "a space for the T", + "text": "2026-11-20 10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an underscore for the T", + "text": "2026-11-20_10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space before", + "text": " 2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a newline after", + "text": "2026-11-20T10:00:00Z\n", + "ms": null, + "stamp": null + }, + { + "name": "a carriage return and a newline after", + "text": "2026-11-20T10:00:00Z\r\n", + "ms": null, + "stamp": null + }, + { + "name": "a tab before", + "text": "\t2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a no-break space after", + "text": "2026-11-20T10:00:00Z ", + "ms": null, + "stamp": null + }, + { + "name": "a byte order mark before", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a next-line character after", + "text": "2026-11-20T10:00:00Z…", + "ms": null, + "stamp": null + }, + { + "name": "a NUL after", + "text": "2026-11-20T10:00:00Z\u0000", + "ms": null, + "stamp": null + }, + { + "name": "a space before the offset", + "text": "2026-11-20T10:00:00 +01:00", + "ms": null, + "stamp": null + }, + { + "name": "a space before the Z", + "text": "2026-11-20T10:00:00 Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format", + "text": "20261120T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "the basic format of the time alone", + "text": "2026-11-20T100000Z", + "ms": null, + "stamp": null + }, + { + "name": "a week date", + "text": "2026-W47-5", + "ms": null, + "stamp": null + }, + { + "name": "a week date with a time", + "text": "2026-W47-5T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an ordinal date", + "text": "2026-324T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the hour alone", + "text": "2026-11-20T10Z", + "ms": null, + "stamp": null + }, + { + "name": "a comma for the point", + "text": "2026-11-20T10:00:00,5Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of the minute", + "text": "2026-11-20T10:00.5Z", + "ms": null, + "stamp": null + }, + { + "name": "a point without digits", + "text": "2026-11-20T10:00:00.Z", + "ms": null, + "stamp": null + }, + { + "name": "a fraction of ten digits", + "text": "2026-11-20T10:00:00.1234567891Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset in hours alone", + "text": "2026-11-20T10:00:00+01", + "ms": null, + "stamp": null + }, + { + "name": "an offset without its colon", + "text": "2026-11-20T10:00:00+0100", + "ms": null, + "stamp": null + }, + { + "name": "an offset with seconds", + "text": "2026-11-20T10:00:00+01:00:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset of one digit an hour", + "text": "2026-11-20T10:00:00+1:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset without a sign", + "text": "2026-11-20T10:00:0001:00", + "ms": null, + "stamp": null + }, + { + "name": "a zone's name after the offset", + "text": "2026-11-20T10:00:00+01:00[Europe/Paris]", + "ms": null, + "stamp": null + }, + { + "name": "a Z and an offset", + "text": "2026-11-20T10:00:00Z+01:00", + "ms": null, + "stamp": null + }, + { + "name": "two Zs", + "text": "2026-11-20T10:00:00ZZ", + "ms": null, + "stamp": null + }, + { + "name": "UTC for the Z", + "text": "2026-11-20T10:00:00UTC", + "ms": null, + "stamp": null + }, + { + "name": "GMT after a space", + "text": "2026-11-20T10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date of the HTTP kind", + "text": "Fri, 20 Nov 2026 10:00:00 GMT", + "ms": null, + "stamp": null + }, + { + "name": "a date with slashes", + "text": "2026/11/20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a date with points", + "text": "2026.11.20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the day before the month", + "text": "20-11-2026T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a time with points", + "text": "2026-11-20T10.00.00Z", + "ms": null, + "stamp": null + }, + { + "name": "the seconds from 1970 in digits", + "text": "1795168800", + "ms": null, + "stamp": null + }, + { + "name": "the milliseconds from 1970 in digits", + "text": "1795168800000", + "ms": null, + "stamp": null + }, + { + "name": "a word", + "text": "yesterday", + "ms": null, + "stamp": null + }, + { + "name": "the word now", + "text": "now", + "ms": null, + "stamp": null + }, + { + "name": "empty text", + "text": "", + "ms": null, + "stamp": null + }, + { + "name": "a T alone", + "text": "T", + "ms": null, + "stamp": null + }, + { + "name": "two times", + "text": "2026-11-20T10:00:00Z2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a time and a word", + "text": "2026-11-20T10:00:00Z tomorrow", + "ms": null, + "stamp": null + }, + { + "name": "the 30th of February", + "text": "2026-02-30T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of a common year", + "text": "2026-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of the year 1900", + "text": "1900-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 29th of February of the year 2100", + "text": "2100-02-29T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 31st of April", + "text": "2026-04-31T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the 31st of November", + "text": "2026-11-31T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a month of nothing", + "text": "2026-00-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a thirteenth month", + "text": "2026-13-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of nothing", + "text": "2026-11-00T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a 32nd day", + "text": "2026-11-32T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 24, minute nothing", + "text": "2026-11-20T24:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 24", + "text": "2026-11-20T24:30:00Z", + "ms": null, + "stamp": null + }, + { + "name": "hour 25", + "text": "2026-11-20T25:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "minute 60", + "text": "2026-11-20T10:60:00Z", + "ms": null, + "stamp": null + }, + { + "name": "second 60, a leap second", + "text": "2026-12-31T23:59:60Z", + "ms": null, + "stamp": null + }, + { + "name": "second 61", + "text": "2026-11-20T10:00:61Z", + "ms": null, + "stamp": null + }, + { + "name": "an offset of 24 hours", + "text": "2026-11-20T10:00:00+24:00", + "ms": null, + "stamp": null + }, + { + "name": "an offset with 60 minutes", + "text": "2026-11-20T10:00:00+01:60", + "ms": null, + "stamp": null + }, + { + "name": "an offset of 99 hours", + "text": "2026-11-20T10:00:00-99:59", + "ms": null, + "stamp": null + }, + { + "name": "the year nothing", + "text": "0000-01-01T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "the last day of the year nothing", + "text": "0000-12-31T23:59:59Z", + "ms": null, + "stamp": null + }, + { + "name": "the year nothing, at an offset that puts the instant in the year 0001", + "text": "0000-12-31T23:30:00-01:00", + "ms": null, + "stamp": null + }, + { + "name": "a year of five digits", + "text": "10000-01-01T00:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of six digits with a sign", + "text": "+002026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year before nothing", + "text": "-0001-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of two digits", + "text": "26-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a year of three digits", + "text": "999-12-31T23:59:59Z", + "ms": null, + "stamp": null + }, + { + "name": "a month of one digit", + "text": "2026-1-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a day of one digit", + "text": "2026-11-2T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an hour of one digit", + "text": "2026-11-20T9:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minute of one digit", + "text": "2026-11-20T10:0:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a second of one digit", + "text": "2026-11-20T10:00:0Z", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts before the year 0001", + "text": "0001-01-01T00:00:00+00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day before the year 0001", + "text": "0001-01-01T23:58:59.999+23:59", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts past the year 9999", + "text": "9999-12-31T23:59:59-00:01", + "ms": null, + "stamp": null + }, + { + "name": "an instant an offset puts a day past the year 9999", + "text": "9999-12-31T00:01:00-23:59", + "ms": null, + "stamp": null + }, + { + "name": "Arabic-Indic digits in the year", + "text": "٢٠٢٦-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "an Arabic-Indic digit in the second", + "text": "2026-11-20T10:00:0٠Z", + "ms": null, + "stamp": null + }, + { + "name": "fullwidth digits in the day", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the fraction", + "text": "2026-11-20T10:00:00.1Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth digit in the offset", + "text": "2026-11-20T10:00:00+01:00", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth colon", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth T", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a fullwidth Z", + "text": "2026-11-20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a minus sign of the mathematical kind in the offset", + "text": "2026-11-20T10:00:00−01:00", + "ms": null, + "stamp": null + }, + { + "name": "an en dash in the date", + "text": "2026–11–20T10:00:00Z", + "ms": null, + "stamp": null + }, + { + "name": "a superscript digit", + "text": "2026-11-20T10:00:0²Z", + "ms": null, + "stamp": null + }, + { + "name": "a lone surrogate after", + "text": "2026-11-20T10:00:00Z\ud800", + "ms": null, + "stamp": null + } + ], + "text_cases": [ + { + "name": "empty text", + "text": "", + "trimmed": "", + "blank": true + }, + { + "name": "a name", + "text": "order-assistant", + "trimmed": "order-assistant", + "blank": false + }, + { + "name": "a name with a space inside", + "text": "order assistant", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "U+0009 alone, white space in both runtimes", + "text": "\t", + "trimmed": "", + "blank": true + }, + { + "name": "U+0009 around a name, white space in both runtimes", + "text": "\tname\t", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000A alone, white space in both runtimes", + "text": "\n", + "trimmed": "", + "blank": true + }, + { + "name": "U+000A around a name, white space in both runtimes", + "text": "\nname\n", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000B alone, white space in both runtimes", + "text": "\u000b", + "trimmed": "", + "blank": true + }, + { + "name": "U+000B around a name, white space in both runtimes", + "text": "\u000bname\u000b", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000C alone, white space in both runtimes", + "text": "\f", + "trimmed": "", + "blank": true + }, + { + "name": "U+000C around a name, white space in both runtimes", + "text": "\fname\f", + "trimmed": "name", + "blank": false + }, + { + "name": "U+000D alone, white space in both runtimes", + "text": "\r", + "trimmed": "", + "blank": true + }, + { + "name": "U+000D around a name, white space in both runtimes", + "text": "\rname\r", + "trimmed": "name", + "blank": false + }, + { + "name": "U+0020 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+0020 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+00A0 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+00A0 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+1680 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+1680 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2001 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2001 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2002 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2002 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2003 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2003 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2004 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2004 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2005 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2005 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2006 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2006 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2007 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2007 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2008 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2008 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2009 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+2009 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+200A alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+200A around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2028 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true + }, + { + "name": "U+2028 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false + }, + { + "name": "U+2029 alone, white space in both runtimes", + "text": "
", + "trimmed": "", + "blank": true + }, + { + "name": "U+2029 around a name, white space in both runtimes", + "text": "
name
", + "trimmed": "name", + "blank": false + }, + { + "name": "U+202F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+202F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+205F alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+205F around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+3000 alone, white space in both runtimes", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "U+3000 around a name, white space in both runtimes", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "U+001C alone, a character of a name", + "text": "\u001c", + "trimmed": "\u001c", + "blank": false + }, + { + "name": "U+001C around a name, a character of a name", + "text": "\u001cname\u001c", + "trimmed": "\u001cname\u001c", + "blank": false + }, + { + "name": "U+001D alone, a character of a name", + "text": "\u001d", + "trimmed": "\u001d", + "blank": false + }, + { + "name": "U+001D around a name, a character of a name", + "text": "\u001dname\u001d", + "trimmed": "\u001dname\u001d", + "blank": false + }, + { + "name": "U+001E alone, a character of a name", + "text": "\u001e", + "trimmed": "\u001e", + "blank": false + }, + { + "name": "U+001E around a name, a character of a name", + "text": "\u001ename\u001e", + "trimmed": "\u001ename\u001e", + "blank": false + }, + { + "name": "U+001F alone, a character of a name", + "text": "\u001f", + "trimmed": "\u001f", + "blank": false + }, + { + "name": "U+001F around a name, a character of a name", + "text": "\u001fname\u001f", + "trimmed": "\u001fname\u001f", + "blank": false + }, + { + "name": "U+0085 alone, a character of a name", + "text": "…", + "trimmed": "…", + "blank": false + }, + { + "name": "U+0085 around a name, a character of a name", + "text": "…name…", + "trimmed": "…name…", + "blank": false + }, + { + "name": "U+FEFF alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false + }, + { + "name": "U+FEFF around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false + }, + { + "name": "U+180E alone, a character of a name", + "text": "᠎", + "trimmed": "᠎", + "blank": false + }, + { + "name": "U+180E around a name, a character of a name", + "text": "᠎name᠎", + "trimmed": "᠎name᠎", + "blank": false + }, + { + "name": "U+200B alone, a character of a name", + "text": "​", + "trimmed": "​", + "blank": false + }, + { + "name": "U+200B around a name, a character of a name", + "text": "​name​", + "trimmed": "​name​", + "blank": false + }, + { + "name": "U+200C alone, a character of a name", + "text": "‌", + "trimmed": "‌", + "blank": false + }, + { + "name": "U+200C around a name, a character of a name", + "text": "‌name‌", + "trimmed": "‌name‌", + "blank": false + }, + { + "name": "U+200D alone, a character of a name", + "text": "‍", + "trimmed": "‍", + "blank": false }, { - "name": "an older message landing late never overwrites a newer row, and an answer needs a recorded wait", - "steps": [ - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T11:00:00.000Z", - "expires_at": "2026-11-21T11:00:00.000Z", - "ticket": "v1.first.mac", - "link": "https://ask.example.test/ask/v1.first.mac" - }, - "now": "2026-11-19T11:00:00.200Z" - }, - { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T10:59:00.000Z", - "expires_at": "2026-11-21T10:59:00.000Z", - "ticket": "v1.stale.mac", - "link": "https://ask.example.test/ask/v1.stale.mac" + "name": "U+200D around a name, a character of a name", + "text": "‍name‍", + "trimmed": "‍name‍", + "blank": false + }, + { + "name": "U+2060 alone, a character of a name", + "text": "⁠", + "trimmed": "⁠", + "blank": false + }, + { + "name": "U+2060 around a name, a character of a name", + "text": "⁠name⁠", + "trimmed": "⁠name⁠", + "blank": false + }, + { + "name": "U+0000 alone, a character of a name", + "text": "\u0000", + "trimmed": "\u0000", + "blank": false + }, + { + "name": "U+0000 around a name, a character of a name", + "text": "\u0000name\u0000", + "trimmed": "\u0000name\u0000", + "blank": false + }, + { + "name": "U+007F alone, a character of a name", + "text": "", + "trimmed": "", + "blank": false + }, + { + "name": "U+007F around a name, a character of a name", + "text": "name", + "trimmed": "name", + "blank": false + }, + { + "name": "every white-space character and nothing else", + "text": "\t\n\u000b\f\r              

   ", + "trimmed": "", + "blank": true + }, + { + "name": "every white-space character around a name", + "text": "\t\n\u000b\f\r              

   name\t\n\u000b\f\r              

   ", + "trimmed": "name", + "blank": false + }, + { + "name": "white space before a name only", + "text": " \t name", + "trimmed": "name", + "blank": false + }, + { + "name": "white space after a name only", + "text": "name\r\n", + "trimmed": "name", + "blank": false + }, + { + "name": "white space inside a name is kept", + "text": " order assistant ", + "trimmed": "order assistant", + "blank": false + }, + { + "name": "a byte order mark inside white space", + "text": "  ", + "trimmed": "", + "blank": false + }, + { + "name": "white space inside two byte order marks", + "text": " ", + "trimmed": " ", + "blank": false + }, + { + "name": "a next-line character after white space", + "text": "name …", + "trimmed": "name …", + "blank": false + }, + { + "name": "a unit separator before white space", + "text": "\u001f name", + "trimmed": "\u001f name", + "blank": false + }, + { + "name": "fifty spaces", + "text": " ", + "trimmed": "", + "blank": true + }, + { + "name": "a name between fifty spaces", + "text": " name ", + "trimmed": "name", + "blank": false + }, + { + "name": "a lone surrogate between spaces", + "text": " \ud800 ", + "trimmed": "\ud800", + "blank": false + } + ], + "exact_cases": [ + { + "name": "whole numbers past 9007199254740991 in a waiting call's input and in a decision", + "message": { + "kind": "approval", + "graph_id": "ledger-assistant", + "description": "Ledger assistant: a transfer waits for a controller", + "correlation_id": "transfer-88-case", + "turn": 4, + "node": "assist", + "summary": "transfer_units from ACC-7: more units than a double counts exactly", + "calls": [ + { + "id": "toolu_01A", + "name": "transfer_units", + "route": "demo.units.transfer", + "wait": true, + "input": { + "account": "ACC-7", + "units": null, + "limits": [ + null, + null + ], + "counter": null, + "note": "café 
 \"quoted\"" + } }, - "now": "2026-11-19T11:00:00.300Z", - "note": "a message older than the row lands late (two recorder workers, or a redelivery): the row stands and the sequence does not move" - }, + { + "id": "toolu_02B", + "name": "ask_controller", + "ask": true, + "wait": true, + "input": { + "question": "How many units?" + } + } + ], + "ttl": "2d", + "requested_at": "2026-11-19T09:12:04.118Z" + }, + "numbers": [ { - "op": "record", - "event": { - "kind": "approval", - "graph_id": "order-assistant", - "description": "Customer-support assistant: a refund waits for a supervisor", - "correlation_id": "order-1007-case", - "turn": 2, - "node": "assist", - "summary": "A refund waits for the supervisor's decision", - "calls": [ - { - "id": "toolu_01A", - "name": "issue_refund", - "route": "demo.refund.issue", - "wait": true, - "input": { - "order_id": "ORD-1007", - "amount": 60.0, - "reason": "Damaged on arrival" - } - } - ], - "ttl": "2d", - "requested_at": "2026-11-19T11:05:00.000Z", - "expires_at": "2026-11-21T11:05:00.000Z", - "ticket": "v1.newer.mac", - "link": "https://ask.example.test/ask/v1.newer.mac" - }, - "now": "2026-11-19T11:05:00.100Z", - "note": "a newer re-advice updates the row with its ticket" + "place": [ + "calls", + 0, + "input", + "units" + ], + "digits": "1152921504606846977" }, { - "op": "answer", - "key": [ - "order-assistant", - "order-1007-case", - 2 - ], - "decisions": [ - { - "id": "toolu_01A", - "approved": true - } + "place": [ + "calls", + 0, + "input", + "limits", + 0 ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 3 - }, - "now": "2026-11-19T11:06:00.000Z" + "digits": "-9223372036854775808" }, { - "op": "answer", - "key": [ - "order-assistant", - "order-9999-case", - 7 - ], - "decisions": [ - { - "id": "toolu_09Z", - "approved": true - } + "place": [ + "calls", + 0, + "input", + "limits", + 1 ], - "who": "operator-17", - "status": 200, - "body": { - "type": "answer", - "turn": 8 - }, - "now": "2026-11-19T11:06:30.000Z", - "note": "an answer for a wait that was never recorded: nothing to write, the result is null" + "digits": "9223372036854775807" }, { - "op": "since", - "seq": 0, - "limit": 10 + "place": [ + "calls", + 0, + "input", + "counter" + ], + "digits": "18446744073709551615" } ], - "results": [ - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.first.mac" - }, - { - "id": 1, - "seq": 1, - "state": "open", - "ticket": "v1.first.mac" - }, - { - "id": 1, - "seq": 2, - "state": "open", - "ticket": "v1.newer.mac" - }, + "key": "test-key-current", + "reply_url": "https://ask.example.test", + "ticket": "v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q", + "expires_at": "2026-11-21T09:12:04.118Z", + "record": "{\"kind\":\"approval\",\"graph_id\":\"ledger-assistant\",\"description\":\"Ledger assistant: a transfer waits for a controller\",\"correlation_id\":\"transfer-88-case\",\"turn\":4,\"node\":\"assist\",\"summary\":\"transfer_units from ACC-7: more units than a double counts exactly\",\"calls\":[{\"id\":\"toolu_01A\",\"name\":\"transfer_units\",\"route\":\"demo.units.transfer\",\"wait\":true,\"input\":{\"account\":\"ACC-7\",\"units\":1152921504606846977,\"limits\":[-9223372036854775808,9223372036854775807],\"counter\":18446744073709551615,\"note\":\"café 
 \\\"quoted\\\"\"}},{\"id\":\"toolu_02B\",\"name\":\"ask_controller\",\"ask\":true,\"wait\":true,\"input\":{\"question\":\"How many units?\"}}],\"ttl\":\"2d\",\"requested_at\":\"2026-11-19T09:12:04.118Z\",\"expires_at\":\"2026-11-21T09:12:04.118Z\",\"ticket\":\"v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q\",\"link\":\"https://ask.example.test/ask/v1.eyJjIjoidHJhbnNmZXItODgtY2FzZSIsImUiOjE3OTUyNTIzMjQsImciOiJsZWRnZXItYXNzaXN0YW50IiwiayI6ImFwcHJvdmFsIiwidCI6NH0.uPkPasxUhzLey3qmHCPX08Qh_nDHJfxhfM6JFoRmu0Q\"}", + "decisions": [ { - "id": 1, - "seq": 3, - "state": "answered", - "answered_by": "operator-17" + "id": "toolu_01A", + "approved": true, + "note": "counted twice" }, - null, { - "ids": [ - 1 - ], - "seqs": [ - 3 - ] + "id": "toolu_02B", + "answer": null } ], - "final": [ + "decision_numbers": [ { - "id": 1, - "seq": 3, - "kind": "approval", - "state": "answered", - "ticket": "v1.newer.mac", - "turn": 2, - "requested_at": "2026-11-19T11:05:00.000Z", - "expires_at": "2026-11-21T11:05:00.000Z", - "updated_at": "2026-11-19T11:06:00.000Z", - "answered_by": "operator-17", - "outcome": { - "status": 200, - "body": { - "type": "answer", - "turn": 3 - } - } + "place": [ + 1, + "answer" + ], + "digits": "9007199254740993" } - ] + ], + "decisions_record": "[{\"id\":\"toolu_01A\",\"approved\":true,\"note\":\"counted twice\"},{\"id\":\"toolu_02B\",\"answer\":9007199254740993}]" } ] } From 03d35a1fd7c815f3744b5d910389462fe537710e Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:21 -0800 Subject: [PATCH 5/6] docs(changelog): the loose-ends round - the agent tools, the LLM helper, ask-person and agent-question, the YAML 1.2.2 reader, REST automation and the host Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 120 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 113 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72498c8d..64ddb466 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -371,9 +371,8 @@ - A flag of an entry (`tracing`, `stream`, `upload`) was on only for the YAML boolean, so `tracing: "true"` and `tracing: ${TRACING:true}` stayed off without a word. The boolean or the text `true` in any letter case turns it on, as in the Java engine; `false`, no value and an empty one leave it off; any other value, which the - engine reads as off silently, fails the start: `rest[N] 'tracing' must be true or false`. `rest.yaml` is read - with the boolean words of the Python pack's reader and the engine's, so the single letters `y` and `n` are - text. + engine reads as off silently, fails the start: `rest[N] 'tracing' must be true or false`. How the + file's scalars are read is Fixed 10: by YAML 1.2.2, so `yes` and `on` are text. - The upload bound counted a text field by the length of its text; each field counts as the bytes of its part in the body. A body past the bound is let go by unread, so the client takes the 413 instead of a broken connection. @@ -393,6 +392,113 @@ **Upgrade note:** an entry whose flag is written as anything but `true` or `false` stops the start - write `true` or `false`. A request body over 16 MiB is refused; a file upload keeps its own bound, `rest.upload.max.bytes`. +7. **The agent tools: one reader of a URL and of `robots.txt` in both packs, a search by regular expression that + ends at a bound, and settings read by one rule.** The web tools read a URL with each runtime's own reader, and + 103 of 210 probe URLs came out differently in the two packs: `http://0177.0.0.1/` was 127.0.0.1 here and was + kept by the Python twin, and one page was fetched once for each spelling of its link. Both packs now take a URL + apart by one set of rules and write it back in one form - `http` or `https`, no credentials, a host that is a + name, an IPv4 address in dotted decimal or an IPv6 address in brackets, a port in the digits 0 to 9, the path and + the query percent-encoded one way and without `.` and `..` segments, at most 8192 characters - refuse anything + else by name, and ask a site for exactly what was checked. `robots.txt` is read by RFC 9309 with the same reader + in both packs, and a rule is matched part by part between its stars, so its time is bounded by its length plus + the path's: as a regular expression, a rule of four stars against a path of 200 characters took 14.9 seconds on + the event loop. `file.search` with `regex: true` runs the expression in a worker thread that is ended at + `tools.file.search.timeout.ms` (10 s by default) with a 408 - `(a+)+$` against forty letters did not finish, with + the event loop held - and a literal is a substring test in the host, by the tools' own linear search when it is + long. Smaller: `graph.ingest` keeps a property named `__proto__`, which was dropped without a word; a walk looks + at 20,000 entries at most and says `truncated`, and reads a folder only as far as it goes; the port of an + allowlist entry and a page number are the digits 0 to 9; a number argument above 9007199254740991 is a 400; a + `tools.*` setting that is no number or no switch stops the start by name, and a time in milliseconds is at most + 2147483647, where a longer one fired after a millisecond. **Upgrade note:** a host outside letters, digits, + hyphen, dot and underscore is refused, so an internationalized name is written in its `xn--` form; a URL in a + result is in the one form and may be spelled differently than before; a switch written `yes`, `on` or `1`, and a + number written with a point or an exponent, stop the start; a workspace of more than 20,000 entries is listed + and searched up to there; a search by regular expression answers a 408 at its bound. + +8. **The LLM helper reads its settings when it starts, and a switch, a time in milliseconds and a page list by one + rule.** A wrong `llm.provider`, `llm.backend`, `llm.max.tokens`, `llm.timeout.ms`, `llm.max.retries`, + `llm.effort`, `llm.fallbacks`, `llm.transcript.ttl` or `llm.transcript.retention` was refused by the first + request that needed it. A start-up step now reads them, and builds the transcript store when one is named, so a + wrong one stops the application by name (`llm.helper cannot start - llm.max.tokens must be a whole number >= 1`); + the attachment limits and the audit's sweep and switches are read by their own steps. A switch + (`llm.log.batches`, `llm.transcript.audit.single`, the two `ssl` keys) is `true` or `false`: `yes`, `on` and `1` + were read as off without a word - TLS written `yes` was no TLS - and now stop the start. A time in milliseconds + is at most 2147483647: from 2147483648 a timer fired after a millisecond, and 4294967296 was a `RangeError`. The + audit's retention is at most `1000000d`: a longer one wrote an expiry with a five-digit year, or raised. A port + is at most 65535. In a page list white space is ignored around a number and refused inside one: `"1 3"` was + page 13. A path is blank by the same 24 characters in both packs, so one of only U+FEFF is a name. The shared + vectors gain `switches` (22 values) and `start` (47 cases). **Upgrade note:** a deployment with a wrong value it + never exercised no longer starts; `llm.transcript.store: redis` without its client stops the start, where it was + a 503 on the first loop turn; an empty `llm.transcript.audit.postgres.ssl` is its default, TLS on, where it was + off; `"1 3"` as pages is a 400. + +9. **ask-person and agent-question: one reader of a time, a number, a duration and a switch, a signed payload with + one spelling, and a row that keeps every digit.** A time without an offset was local time here and UTC in the + Python twin, and each pack took spellings the other refused - 30 February was 2 March here; a time is now a + date, `T`, a time to the minute or the second, and `Z` or an offset, read to the millisecond by one rule, for + `requested_at`, a wait's `expires_at` at the intake and the transcripts' `before`. A `ttl` whose expiry is past + the year 9999 wrote `+010002-...` or raised `RangeError`; it is a 400, `ttl must end before the year 10000`. + `turn`, `ttl`, `GET /questions`' `since`, `before` and `limit`, and every setting follow the number and duration + rule, where a value above 2^53-1 was rounded; a switch that is neither `true` nor `false` stops the boot, where + `ask.enabled: yes` was on and `ask.audit.postgres.ssl: no` was read as on. The bytes under a ticket's signature + must be the canonical JSON of its five fields: both packs took other spellings, and agree with a reference on + 200,074 generated payloads now. A graph named `constructor`, `toString` or `__proto__` is looked up among the + configured graphs only, where the page answered 200 and the reply a 502. A row id or a sequence above 2^53-1 is + held as a `BigInt` and written with every digit in a page, a stream's event and the record: two such rows + collided after rounding, and a waiting call's input with such a number was not recorded at all. A setting that + sets a timer is at most 2147483647 ms - the sweep ran 178 times in 200 ms with `30d` - a port at most 65535, a + `turn` at most 2147483647, the record's column; a required text is blank by the same 24 characters in both + packs. **Upgrade note:** a time without an offset, with white space around it or with a lower-case `t` or `z` is + a 400; `"2 d"` with a space before its unit is refused; `ask.enabled` and the `ssl` switches take `true` or + `false` only, and an empty `ask.enabled` is its default, on, where it was off; a ticket minted outside the packs + with another JSON spelling is malformed; `turn` as text digits (`"2"`) is taken; a row past 2^53-1 holds a + `BigInt`, which plain `JSON.stringify` refuses. + +10. **Every YAML file is read by YAML 1.2.2 in both packs, and a setting of the host by one rule (the maintainer's + ruling of 2026-11-29).** The configuration file was read by each pack's YAML library - this pack's reads YAML + 1.2, the Python twin's PyYAML YAML 1.1 - and 130 of 239 probe scalars came out differently through the two + packs: `yes` was text here and a boolean there, `010` was 10 and 8, `1e3` a number here only, `16_000` and + `1:30` numbers there only, and `info.app.version: 1.0` read `1`. One reader per pack now resolves a plain + scalar by the core schema of YAML 1.2.2: `true` and `false` are the booleans, `010` is 10, `0o10` is 8, and + `yes`, `on`, `16_000`, `1:30`, `0b101`, a date and the merge key are text or an ordinary key. It reads + `application.yml`, `rest.yaml`, `app-log-context.yaml` and the MCP binding's file; `rest.yaml` no longer takes + `yes` and `on` as booleans, as it did since Fixed 6. A reference written from the specification agrees with + both packs on 239 probes, and on 126,316 generated scalars but for what the two parsers take differently + before a scalar is resolved. An integer is exact at any size, a `BigInt` above 2^53-1, and as text a float + keeps its point. A key with no value takes its default, and so does one whose references leave it empty + (`'${NAME:}'`), as in the Java engine; a `${key}` reference sees a `-D` or `set` override, and resolves only + the environment's own variables, where `${constructor:x}` gave a function; a reference that leads back to + itself is logged and has no value, where it overflowed the stack. A setting of the host that is no number, no + duration or no switch stops the start by name instead of being read as a default or as off: `rest.automation`, + `rest.server.port`, `rest.upload.max.bytes`, `event.stream.keep.alive`, an entry's `timeout`, `otel.forwarding` + and `app.log.context`. The guides say how a file is read and recommend YAML 1.2.2 to whoever writes one - a + developer or an AI assistant - with the spellings the Java engine's YAML 1.1 reader takes another way + (Configuration Reference, the AI agent guide's checklist, `llms.txt`). **Upgrade note:** a switch or a flag + written `yes` or `on` stops the start - write `true` or `false`; `info.app.version: 1.0` reads `1.0`; a number + above 2^53-1 in a file is a `BigInt`; a file with a tag such as `!!binary` or `!!timestamp` does not load. An + entry's `timeout` that is no duration stops the start, where it was the default, and `1h` is an hour held to + the five-minute cap, where it was the default too. + +11. **REST automation and the host: an upload is read by the pack's own reader, the same in both packs; an edge + failure is the failure the caller sees; a name every object carries is a name like any other.** The two packs + read a `multipart/form-data` body with their web framework's reader and differed on a file without a content + type (`text/plain` here), a field that is not UTF-8 (replacement characters here), a declared ISO-8859-1, a part + without a name, an empty filename and a transfer encoding. `parseUpload` now reads the body in both packs, + pinned by 76 shared cases that run over the reader and over HTTP: a file without a content type is + `application/octet-stream`; a text field is UTF-8, or the ISO-8859-1 or US-ASCII its part declares; + `filename*` and `name*` are taken as RFC 5987 writes them, which some HTTP clients send for a name that is + not ASCII; a part whose transfer or content encoding changes its bytes is refused by name. A query + parameter, a form field, a cookie, a header, a path parameter or an upload field named `constructor`, + `toString` or `__proto__` is read as the caller sent it: `?constructor=c` parsed as `[null, "c"]`, and + `__proto__` was dropped. The client's `request()` and `send()` return an edge's JSON error as the failure it + carries, as `stream()` did. A reply the wire codec refuses on `POST /api/event`, and a static-content filter's + reply that cannot be rendered, are the engines' 500 `Reply cannot be rendered`, with the edge recorded at 500, + where the codec's own message was sent and no record was left. A traced request the edge refuses while it + reads the body leaves its record, as the Java engine's edge does. A timer is held to 2147483647 ms, the + longest delay the runtime's timers take: an `x-ttl` above it was a 408 at once. **Upgrade note:** a part with + `Content-Transfer-Encoding: base64` was decoded and is refused; a file's content type is as the part wrote it, + no longer in lower case. + ### Changed 1. **The agent-question app reads the question record and writes nothing: the backend of the React UI (RFC-0014 @@ -439,16 +545,16 @@ (`/`, the hashed script and stylesheet, `/favicon.svg`) and the five actuator endpoints answer beside it. **Upgrade note:** open `http://127.0.0.1:8092/` instead of `/questions/app`. -2. **`web.crawl` accepts a relative `include`**, in lockstep with the Python pack: a prefix that does not start with `/` matches +5. **`web.crawl` accepts a relative `include`**, in lockstep with the Python pack: a prefix that does not start with `/` matches anywhere in a link's path, since a model names a section as `guides/` as often as `/guides/` (the live drive of the Playground's `site-notes` graph showed a crawl returning the start page alone). The README's Event-over-HTTP example lists one route per entry - the engines' map takes no comma-separated list. -2. **CI runs the tests on Node 26, the current LTS, and the package's floor is `node >= 22`, the oldest maintained LTS +6. **CI runs the tests on Node 26, the current LTS, and the package's floor is `node >= 22`, the oldest maintained LTS (Eric, 2026-11-17: Node 20 is end of life).** The agent tools' directory walk is in-house (`compileGlob`): the in-house matcher reads a pattern as the Python pack's `Path.glob` does and never descends into a symbolic link. -2. **A `-D` override value is resolved with the same `${ENV_VAR:default}` substitution as a file value - the engines' +7. **A `-D` override value is resolved with the same `${ENV_VAR:default}` substitution as a file value - the engines' change of the same day.** `AppConfig.get` returned an override as written, so a key moved from `application.yml` to a `-D` flag silently lost its substitution and a credential had to travel on the command line in clear. Now the value of a `-D` override (and of `appConfig().set`) - an environment variable with a default, or a reference to another @@ -457,7 +563,7 @@ **Upgrade note:** a `-D` value that relied on a literal `${...}` is now resolved, as a file value always was; an unresolved reference without a default is no value, as in a file. -2. **The transcript audit store's PostgreSQL pool sets a server-side `statement_timeout` from +8. **The transcript audit store's PostgreSQL pool sets a server-side `statement_timeout` from `llm.transcript.audit.postgres.timeout.ms`, beside the client's `query_timeout`.** The live drive of 2026-11-17 (mercury-composable `docs/test-reports/transcript-audit-live-drive.md`) showed a stopped database failing a write by type within the connection timeout, as designed, but a paused one - a TCP black hole - holding the pooled connection's From a29288aded54737854dfa86e612a7b13686dd87d Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:01:39 -0800 Subject: [PATCH 6/6] test(agent-tools): an expression the engine cannot compile is a count of registers, not a depth of nesting The test of a search by regular expression expected 30,000 nested groups to be refused. That is what the engine's compiler does on a worker's 4 MB stack on macOS arm64: "Stack overflow". On CI's Linux x64 runner the same Node 26.13.1 compiles the expression and runs it in about seven seconds, so the search answered and the test failed with "expected a refusal" (run 46384505235). How deep an expression may nest is the size of a stack, and differs from one platform to the next. Measured on one machine, the same expression is "Regular expression too large" on a stack of 1 MB or 2 MB, "Stack overflow" on 4 MB, and runs on 8 MB and more; with a 16 MB worker stack the test fails here as it did on CI. The case is now 40,000 lookaheads, which need more registers than the engine has. The engine reads that expression and refuses it when it first runs it, at every stack size from 1 MB to 64 MB, in milliseconds. The case also runs on a folder without a file, which pins the worker's first run on an empty text: without that run, the search of an empty folder answers. No change of behaviour. The tools refuse what the engine cannot compile and end what does not finish (tools.file.search.timeout.ms), as before. Co-Authored-By: Claude Fable 5.2 --- test/agent-tools.test.mjs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/agent-tools.test.mjs b/test/agent-tools.test.mjs index e110e970..748d1b38 100644 --- a/test/agent-tools.test.mjs +++ b/test/agent-tools.test.mjs @@ -705,16 +705,21 @@ test('a search by regular expression runs outside the host and leaves nothing ru [[1, [], ['value = 1']], [3, ['value = 1'], ['TODO_COUNT = 2']], [4, ['# todo: later'], []]]); const cut = await files.search({}, { pattern: 't.d.', regex: true, max_results: 2 }); assert.deepEqual([cut.matches.length, cut.truncated], [2, true]); + // An expression the engine reads and then cannot compile when it first runs it: 40,000 lookaheads + // need more registers than the engine has. That is a count, the same on every platform - how deep + // an expression may nest is the size of a stack, and differs from one platform to the next. + const tooLarge = '(?=a)'.repeat(40000); + assert.ok(new RegExp(tooLarge), 'the engine reads the expression: what it cannot do is compile it'); for (const body of [{ pattern: '(', regex: true }, { pattern: '(', regex: true, path: 'empty' }, - { pattern: `${'('.repeat(30000)}a${')'.repeat(30000)}`, regex: true }]) { + { pattern: tooLarge, regex: true }, { pattern: tooLarge, regex: true, path: 'empty' }]) { const got = await refusal(files.search({}, body)); assert.equal(got.status, 400, 'an expression that cannot be compiled is refused, files or none'); assert.ok(got.message.startsWith('pattern is not a valid regular expression ('), got.message.slice(0, 80)); } assert.equal((await files.search({}, { pattern: 'todo' })).files_searched, 5); }); - assert.equal(workers.length, 6, 'a worker for each search by regular expression, none for a literal'); - assert.deepEqual(workers.map((worker) => worker.threadId), Array(6).fill(-1), 'each worker was ended and waited for'); + assert.equal(workers.length, 7, 'a worker for each search by regular expression, none for a literal'); + assert.deepEqual(workers.map((worker) => worker.threadId), Array(7).fill(-1), 'each worker was ended and waited for'); }); test('a literal is searched in the host, in a time bounded by the line', async () => {