@smthrs/flow 1.0.0-rc.8 → 1.0.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cjs/Deadline.d.ts +5 -0
  2. package/dist/cjs/Deadline.d.ts.map +1 -1
  3. package/dist/cjs/Deadline.js +9 -1
  4. package/dist/cjs/Deadline.js.map +2 -2
  5. package/dist/cjs/DurableClock.d.ts +9 -10
  6. package/dist/cjs/DurableClock.d.ts.map +1 -1
  7. package/dist/cjs/DurableClock.js +19 -2
  8. package/dist/cjs/DurableClock.js.map +2 -2
  9. package/dist/cjs/Flow/make.d.ts +2 -1
  10. package/dist/cjs/Flow/make.d.ts.map +1 -1
  11. package/dist/cjs/Flow/make.js +3 -0
  12. package/dist/cjs/Flow/make.js.map +2 -2
  13. package/dist/cjs/HumanTask.d.ts.map +1 -1
  14. package/dist/cjs/HumanTask.js +2 -2
  15. package/dist/cjs/HumanTask.js.map +2 -2
  16. package/dist/esm/Deadline.d.ts +5 -0
  17. package/dist/esm/Deadline.d.ts.map +1 -1
  18. package/dist/esm/Deadline.js +13 -1
  19. package/dist/esm/Deadline.js.map +1 -1
  20. package/dist/esm/DurableClock.d.ts +9 -10
  21. package/dist/esm/DurableClock.d.ts.map +1 -1
  22. package/dist/esm/DurableClock.js +49 -2
  23. package/dist/esm/DurableClock.js.map +1 -1
  24. package/dist/esm/Flow/make.d.ts +2 -1
  25. package/dist/esm/Flow/make.d.ts.map +1 -1
  26. package/dist/esm/Flow/make.js +5 -0
  27. package/dist/esm/Flow/make.js.map +1 -1
  28. package/dist/esm/HumanTask.d.ts.map +1 -1
  29. package/dist/esm/HumanTask.js +5 -3
  30. package/dist/esm/HumanTask.js.map +1 -1
  31. package/docs/api.md +15 -11
  32. package/docs/guides/ask-a-person.md +5 -5
  33. package/docs/guides/inspect-the-plan.md +1 -1
  34. package/docs/reference/flow.md +4 -4
  35. package/package.json +7 -7
  36. package/src/Deadline.ts +17 -1
  37. package/src/DurableClock.ts +45 -2
  38. package/src/Flow/make.ts +7 -1
  39. package/src/HumanTask.ts +5 -3
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/HumanTask.ts"],
4
- "sourcesContent": ["/**\n * Asking a person something, as an ordinary declared action.\n *\n * {@link module:WaitFor.action} is the general rendezvous: it parks until\n * something outside the run resolves it, and settles with whatever arrived.\n * That is the right primitive and the wrong affordance for a human, because a\n * human answers in prose, in a hurry, and sometimes wrongly. Smithers 0.x had\n * the affordance \u2014 a `HumanTask` with a kind, a prompt, an output schema, an\n * attempt budget, and a deadline \u2014 and this module is that affordance rebuilt\n * on the primitives this package already has.\n *\n * Four things are added to a bare wait:\n *\n * - a **kind**, so the four shapes a person is asked for (`ask`, `confirm`,\n * `select`, `json`) are stated rather than reconstructed from a schema;\n * - **validation**, so an answer that does not fit is refused where it arrives\n * instead of failing three steps later as a decode error;\n * - **re-asking**, so a refused answer parks again on a NEW wait point rather\n * than ending the run, until the attempt budget is spent;\n * - a **deadline**, so a question nobody answers settles instead of parking\n * forever.\n *\n * All four are built from what is already durable. Each attempt is its own wait\n * point in {@link module:WaitFor}'s namespace \u2014 `WaitFor/<name>#<attempt>` \u2014 so\n * an answer is recorded exactly as any other durable deferred completion is, a\n * refused answer stays recorded under the attempt that refused it, and a\n * re-driven round replays every answer it already has before parking on the\n * first attempt that has none. The reason an answer was refused is recorded\n * too, as a sealed step named `HumanTask/<name>#<attempt>/rejected`, so the\n * judgment the run made sits in the journal beside the answer it judged rather\n * than in a log stream nobody replays. The park is declared through the ordinary\n * waiting vocabulary under `approval`, carrying the current attempt's token, so\n * whoever collects answers always sees the one wait point that is open. The\n * deadline is a {@link module:DurableClock} armed once per task and raced\n * against every attempt, which makes it a deadline for the QUESTION rather than\n * for one attempt at answering it.\n *\n * @since 0.1.0\n */\n\nimport * as Node from \"@smthrs/plan/Node\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport type * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableClock from \"./DurableClock.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\nimport { annotateWaiting } from \"./FlowRuntime/WaitingAnnotation.ts\"\nimport * as BoundedJson from \"./internal/BoundedJson.ts\"\nimport * as JsonSchemaSubset from \"./internal/JsonSchemaSubset.ts\"\nimport * as WaitFor from \"./WaitFor.ts\"\n\n/**\n * The shape a person is asked for.\n *\n * `ask` wants prose, `confirm` wants yes or no, `select` wants one of the\n * options the task names, and `json` wants a value the task's JSON Schema\n * accepts. The kind is what an interface renders and what {@link validate}\n * checks; it is stated rather than inferred, because a text box and a two-\n * button confirmation are different questions even when both answers happen to\n * be strings.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Kind = \"ask\" | \"confirm\" | \"select\" | \"json\"\n\n/**\n * The schema the `kind` payload field is declared with.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Kind: Schema.Literals<readonly [\"ask\", \"confirm\", \"select\", \"json\"]> = Schema.Literals([\n \"ask\",\n \"confirm\",\n \"select\",\n \"json\"\n])\n\n/**\n * A question that ended without an answer the task could accept.\n *\n * `request_invalid` is the author's mistake \u2014 a `select` with no options, an\n * attempt budget below one, a deadline that is not a length of time, a JSON\n * Schema outside the supported subset \u2014 and is refused before anyone is asked\n * anything. `rejected` means every attempt was\n * spent on answers the task refused, and `timeout` means the deadline passed\n * with the question still open. All three are typed failures rather than\n * defects, so a body recovers from them with `Node.catch` like any other\n * declared failure \u2014 which is the point, because \"the reviewer never answered\"\n * is an ordinary outcome of asking a reviewer.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class HumanTaskFailed extends Schema.TaggedError<HumanTaskFailed>()(\n \"@smthrs/flow/HumanTaskFailed\",\n {\n code: Schema.Literals([\"request_invalid\", \"rejected\", \"timeout\"]),\n task: Schema.String,\n attempts: Schema.Number,\n rejections: Schema.Array(Schema.String),\n message: Schema.String\n }\n) {}\n\n/**\n * An answer refused before it could consume durable storage.\n *\n * @category errors\n * @since 1.0.0\n */\nexport class HumanAnswerInvalid extends Schema.TaggedError<HumanAnswerInvalid>()(\n \"@smthrs/flow/HumanAnswerInvalid\",\n {\n code: Schema.Literals([\"answer_invalid\", \"answer_not_open\"]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"answer_invalid\"))\n ),\n message: Schema.String\n }\n) {}\n\n/**\n * The tag the human-task declaration is catalogued and resolved under.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const tag = \"system/human-task\"\n\n/**\n * The attempt budget a task that names none is asked under.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const defaultMaxAttempts = 10\n\n/**\n * The deepest supported JSON Schema path, counting the root as depth zero.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxSchemaDepth = JsonSchemaSubset.maxSchemaDepth\n\n/**\n * The most schema objects one human-task request may contain.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxSchemaNodes = JsonSchemaSubset.maxSchemaNodes\n\n/**\n * The most JSON values embedded across schema keywords such as `enum`.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaValueNodes = JsonSchemaSubset.maxSchemaValueNodes\n\n/**\n * The deepest JSON value embedded in a schema, including enum members.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaValueDepth = JsonSchemaSubset.maxSchemaValueDepth\n\n/**\n * The most JSON values one answer validation may visit.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxAnswerNodes = JsonSchemaSubset.maxAnswerNodes\n\n/**\n * The largest encoded JSON answer that can enter the durable store.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxAnswerBytes = JsonSchemaSubset.maxAnswerBytes\n\n/**\n * The largest encoded JSON Schema carried by one question.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaBytes = JsonSchemaSubset.maxSchemaBytes\n\n/**\n * The deepest admitted answer tree.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxAnswerDepth = JsonSchemaSubset.maxAnswerDepth\n\n/**\n * The largest encoded string value admitted in a request or answer.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonStringBytes = JsonSchemaSubset.maxJsonStringBytes\n\n/**\n * The largest encoded object key admitted in a request or answer.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonKeyBytes = JsonSchemaSubset.maxJsonKeyBytes\n\n/**\n * The most members admitted in one JSON array or object.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonMembers = JsonSchemaSubset.maxJsonMembers\n\n/**\n * The largest encoded task name.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxTaskNameBytes = 1_024\n\n/**\n * The largest encoded prompt.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxPromptBytes = 64 * 1024\n\n/**\n * The largest option list on one select question.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxOptions = 256\n\n/**\n * The largest encoded select option.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxOptionBytes = 4 * 1024\n\n/**\n * The largest attempt budget one human task may declare.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxAttemptBudget = 1_000\n\n/**\n * The most caller-supplied characters retained in one rendered diagnostic.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxDiagnosticChars = JsonSchemaSubset.maxDiagnosticChars\n\n/**\n * The most characters retained across a terminal failure's rejection list.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxRetainedRejectionChars = 8_192\n\n/**\n * The durable deferred one attempt at answering resolves through.\n *\n * Attempts are separate wait points on purpose. A durable deferred records the\n * FIRST completion and replays it forever, so re-asking on the same wait point\n * would read the refused answer again on every round; a new point per attempt\n * makes \"answer again\" expressible without a second completion mechanism, and\n * leaves the refused answers in place as the record of what was asked and what\n * came back.\n *\n * The name lives in {@link module:WaitFor}'s namespace because an answer is\n * completed through exactly the {@link module:WaitFor} path: a token, and\n * `DurableDeferred.succeed`. {@link answer} is that call with the token parsed\n * for you.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const deferred = (\n name: string,\n attempt: number\n): DurableDeferred.DurableDeferred<typeof Schema.Json> => WaitFor.deferred(`${name}#${attempt}`)\n\n/** The namespace {@link module:WaitFor.deferred} prepends to every wait point. */\nconst waitForNamespace = /^WaitFor\\//\n\n/**\n * The only spelling of an attempt {@link deferred} writes: a canonical decimal\n * with no sign, no leading zero, no exponent, and no fraction.\n *\n * `Number()` alone is not this check. `NaN`, `Infinity`, `-Infinity`, and\n * `1e+21` all survive a `Number()`/`String()` round trip character for\n * character, so a gate that rebuilt the name through `Number()` would accept\n * them as attempts the action never parks on.\n */\nconst attemptSuffix = /^(0|[1-9][0-9]*)$/\n\n/**\n * The deferred a token addresses, when {@link deferred} could have named it.\n *\n * {@link answer} builds its deferred FROM the caller's token, so\n * `DurableDeferred.done`'s own name check compares a name against itself and\n * can never refuse. This is the check that is not vacuous: the name is taken\n * apart at its attempt separator, the suffix is required to be a canonical\n * decimal naming an attempt the action can park on (a safe integer of one or\n * more), the name is rebuilt through {@link deferred}, and it is accepted only\n * when the rebuilt name is character-for-character the one the token carried.\n * A name {@link deferred} cannot produce -- a `DurableQueue` item address, a\n * plain {@link module:WaitFor} gate, another flow's deferred, a suffix spelled\n * any way other than the decimal {@link deferred} writes -- fails, so a\n * foreign token cannot be completed under `Schema.Json` through the\n * human-answer path.\n *\n * This bounds the confusion to human-task wait points. It does NOT distinguish\n * two human tasks from each other, nor a wait point an author deliberately\n * named to collide with one; separating those needs the deferred's schema and\n * purpose carried in the address itself, which is a wire-format change.\n *\n * @private\n */\nconst answerableDeferred = (\n deferredName: string\n): DurableDeferred.DurableDeferred<typeof Schema.Json> | undefined => {\n const separator = deferredName.lastIndexOf(\"#\")\n if (separator === -1) return undefined\n const suffix = deferredName.slice(separator + 1)\n if (!attemptSuffix.test(suffix)) return undefined\n const attempt = Number(suffix)\n if (!Number.isSafeInteger(attempt) || attempt < 1) return undefined\n const rebuilt = deferred(deferredName.slice(0, separator).replace(waitForNamespace, \"\"), attempt)\n return rebuilt.name === deferredName ? rebuilt : undefined\n}\n\n/**\n * The clock a task's deadline is armed on.\n *\n * One clock per task, not one per attempt: the deadline bounds how long the\n * QUESTION stays open, so re-asking does not extend it. The name is the task's,\n * so every attempt's race arms and awaits the same durable timer \u2014 a clock row\n * keeps the deadline it was first armed with, which is what makes the bound\n * survive a restart.\n *\n * The deadline settles on both hosts. `@smthrs/engine`'s in-process engine and\n * the SQLite engine store each re-drive a run parked on\n * {@link module:DurableDeferred.raceAll}, so the durable timer wakes the\n * question wherever it was asked\n * (`packages/smithers/flows/engine-store/test/RacedParkResume.test.ts`).\n *\n * @private\n */\nconst timeoutClockName = (name: string): string => `HumanTask/${name}/timeout`\n\n/**\n * What one attempt settled with: the answer that arrived, or the deadline.\n *\n * @private\n */\nconst Settled = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"answered\"), value: Schema.Json }),\n Schema.Struct({ _tag: Schema.Literal(\"timeout\") })\n])\n\ntype Settled = typeof Settled.Type\n\n/**\n * What {@link validate} checks an answer against.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Request {\n readonly kind: Kind\n /** Ignored for `json`: an option list alone constrains no JSON value. */\n readonly options?: ReadonlyArray<string> | undefined\n readonly schema?: unknown\n}\n\n/**\n * Checks that a JSON Schema stays inside the bounded subset, at every depth.\n *\n * This is a different question from {@link validate}, which asks whether an\n * ANSWER fits a schema. A question is worth refusing before anyone is asked it:\n * a constraint the subset cannot enforce would otherwise be silently dropped,\n * and the person would be told their answer was fine when half of what was\n * asked for went unchecked.\n *\n * The subset is `type` (`object`, `array`, `string`, `number`, `integer`,\n * `boolean`, `null`), `enum`, `properties`, `required`, `items`, and\n * `nullable`; it lives in `internal/JsonSchemaSubset`.\n *\n * Returns the first reason the schema is out of bounds, or `undefined` when the\n * whole tree is inside it.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const validateSchema = (\n schema: unknown,\n path: ReadonlyArray<string> = []\n): string | undefined => JsonSchemaSubset.validateSchema(schema, path)\n\n/**\n * Checks one answer against the question that was asked.\n *\n * Returns the reason the answer was refused, or `undefined` when it fits. It is\n * exported because it is the same check an interface should run BEFORE it\n * records an answer: refusing a typo in the text box the person is looking at\n * is worth more than refusing it one durable round later.\n *\n * ```ts\n * const rejection = HumanTask.validate(value, { kind: \"select\", options })\n * if (rejection !== undefined) return showTheReviewer(rejection)\n * ```\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const validate = (value: unknown, request: Request): string | undefined => {\n switch (request.kind) {\n case \"ask\":\n if (typeof value !== \"string\") return \"The answer must be a string.\"\n return BoundedJson.textFits(value, maxJsonStringBytes)\n ? undefined\n : `The answer must fit within ${maxJsonStringBytes} encoded bytes of well-formed text.`\n case \"confirm\":\n return typeof value === \"boolean\" ? undefined : \"The answer must be a boolean.\"\n case \"select\": {\n if (request.options === undefined || request.options.length === 0) {\n return \"The question declares no options to choose from.\"\n }\n if (\n request.options.length > maxOptions ||\n request.options.some((option) => typeof option !== \"string\" || !BoundedJson.textFits(option, maxOptionBytes))\n ) {\n return `The question's options exceed the ${maxOptions}-member or ${maxOptionBytes}-byte limits.`\n }\n return request.options.some((option) => option === value)\n ? undefined\n : `The answer ${JsonSchemaSubset.renderDiagnostic(value)} is not one of ${\n JsonSchemaSubset.truncateDiagnostic(request.options.join(\", \"))\n }.`\n }\n default: {\n if (request.schema !== undefined) return JsonSchemaSubset.check(value, request.schema)\n const admitted = BoundedJson.admit(value, JsonSchemaSubset.answerLimits)\n return admitted.ok ? undefined : admitted.complaint\n }\n }\n}\n\n/**\n * The fields a question is asked with.\n *\n * @private\n */\nconst boundedText = (label: string, maximumBytes: number) =>\n Schema.String.check(\n Schema.makeFilter(\n (value) =>\n BoundedJson.textFits(value, maximumBytes) ||\n `${label} must be well-formed text within ${maximumBytes} encoded bytes`,\n { title: `bounded${label.replaceAll(\" \", \"\")}` }\n )\n )\n\nconst boundedSchema = Schema.Json.check(\n Schema.makeFilter(\n (value) => {\n const admitted = BoundedJson.admit(value, JsonSchemaSubset.schemaLimits)\n return admitted.ok || admitted.complaint\n },\n { title: \"boundedHumanTaskSchema\" }\n )\n)\n\nconst option = boundedText(\"option\", maxOptionBytes)\n\nconst payloadFields = {\n name: boundedText(\"task name\", maxTaskNameBytes),\n kind: Kind,\n prompt: boundedText(\"prompt\", maxPromptBytes),\n options: Schema.optional(\n Schema.Array(option).check(Schema.isMaxLength(maxOptions))\n ),\n schema: Schema.optional(boundedSchema),\n timeoutMs: Schema.optional(Schema.Number),\n maxAttempts: Schema.optional(Schema.Number)\n}\n\n/**\n * The declared human-task action.\n *\n * **When to use**\n *\n * Use it in a body wherever the next step depends on a person: a release that\n * needs sign-off, a plan that needs a choice, a field the run cannot compute.\n * The node settles with the answer, so downstream steps read it the way they\n * read any other step result, and {@link decode} gives that answer the caller's\n * own type.\n *\n * ```ts\n * HumanTask.action.call({\n * name: \"release\",\n * kind: \"select\",\n * prompt: \"Which build should ship?\",\n * options: [\"canary\", \"stable\"],\n * timeoutMs: 6 * 60 * 60 * 1000\n * })\n * ```\n *\n * `name` addresses the question, so two calls naming one question in one\n * execution await one answer \u2014 the same reading {@link module:WaitFor} takes,\n * for the same reason: a person has to be able to name what they are answering.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const action: Action.Declared<\n typeof tag,\n Schema.Struct<typeof payloadFields>,\n typeof Schema.Json,\n typeof HumanTaskFailed,\n never\n> = Action.makeSystem(tag, {\n payload: payloadFields,\n success: Schema.Json,\n error: HumanTaskFailed,\n tier: \"sealed\"\n})\n\n/** The payload the action is called with, as its implementation reads it. */\ntype Payload = typeof action.payloadSchema.Type\n\n/**\n * The question a park publishes about itself, as the JSON text the durable\n * waiting row stores.\n *\n * It is the payload's own fields, narrowed to what an interface needs to\n * render an answer box and refuse a bad answer before a person sends it: the\n * kind picks the control, the prompt is the question, `options` fills a\n * select, `schema` validates a JSON answer, and the two attempt numbers say\n * how much of the budget is left. The answer VALUE never appears here \u2014 this\n * describes the question, not what anybody said.\n *\n * @private\n */\nconst declaredQuestion = (\n payload: Payload,\n attempt: number,\n maxAttempts: number\n): string =>\n JSON.stringify({\n task: \"human\",\n name: payload.name,\n kind: payload.kind,\n prompt: payload.prompt,\n attempt,\n maxAttempts,\n ...(payload.options === undefined ? {} : { options: [...payload.options] }),\n ...(payload.schema === undefined ? {} : { schema: payload.schema })\n })\n\n/** Builds the failure a task settles with, with the reasons it refused. */\nconst failed = (\n payload: Payload,\n code: typeof HumanTaskFailed.Type[\"code\"],\n attempts: number,\n rejections: ReadonlyArray<string>,\n message: string\n): HumanTaskFailed => new HumanTaskFailed({ code, task: payload.name, attempts, rejections, message })\n\ninterface RetainedRejections {\n readonly entries: Array<string>\n chars: number\n omitted: number\n}\n\n/** Describes the tail of a rejection history that could not be retained. */\nconst omissionMarker = (count: number): string => `${count} further rejections were omitted.`\n\n/** Adds one rejection while keeping the terminal rejection history bounded. */\nconst retainRejection = (state: RetainedRejections, rejection: string): void => {\n const alreadyOmitting = state.omitted > 0\n if (alreadyOmitting) {\n const previousMarker = state.entries.pop()!\n state.chars -= previousMarker.length\n }\n if (!alreadyOmitting && state.chars + rejection.length <= maxRetainedRejectionChars) {\n state.entries.push(rejection)\n state.chars += rejection.length\n return\n }\n state.omitted++\n let marker = omissionMarker(state.omitted)\n while (state.chars + marker.length > maxRetainedRejectionChars) {\n const removed = state.entries.pop()!\n state.chars -= removed.length\n state.omitted++\n marker = omissionMarker(state.omitted)\n }\n state.entries.push(marker)\n state.chars += marker.length\n}\n\n/**\n * The attempt budget a payload asks for, refused when it is not a whole number\n * of attempts.\n *\n * @private\n */\nconst budgetOf = (payload: Payload): Effect.Effect<number, HumanTaskFailed> => {\n const maxAttempts = payload.maxAttempts ?? defaultMaxAttempts\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n return Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with maxAttempts ${maxAttempts}. A question is asked at least once.`\n )\n )\n }\n return maxAttempts <= maxAttemptBudget\n ? Effect.succeed(maxAttempts)\n : Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with maxAttempts ${maxAttempts}. A question asked more than ` +\n `${maxAttemptBudget} times is a stuck question.`\n )\n )\n}\n\n/**\n * The deadline a payload asks for, refused when it is not a length of time.\n *\n * `Duration.millis` takes any number, so an unchecked deadline does not fail \u2014\n * it changes what the question means. `NaN` becomes zero and a negative stays\n * negative, so both are deadlines that have ALREADY passed: the task times out\n * on its first park and nobody is ever really asked. `Infinity` becomes the\n * infinite duration, so the race has a branch that can never win and a question\n * asked with a deadline has none. All three are the same authoring mistake as a\n * `select` with no options, and they are refused in the same place, before the\n * first park, rather than surfacing as a `timeout` nobody waited for.\n *\n * @private\n */\nconst deadlineOf = (payload: Payload): Effect.Effect<Duration.Duration | undefined, HumanTaskFailed> => {\n const timeoutMs = payload.timeoutMs\n if (timeoutMs === undefined) return Effect.succeed(undefined)\n return Number.isFinite(timeoutMs) && timeoutMs >= 0\n ? Effect.succeed(Duration.millis(timeoutMs))\n : Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with timeoutMs ${timeoutMs}. A deadline is a finite number of ` +\n \"milliseconds that is not negative; the question would be over before it was asked, or \" +\n \"never over at all.\"\n )\n )\n}\n\n/**\n * Refuses a question nobody could answer correctly, before anyone is asked.\n *\n * A `select` with no options and a schema outside the supported subset are\n * authoring mistakes whose only symptom at answer time would be a person being\n * refused for something they did not do, so {@link validateSchema} walks the\n * whole schema tree before the first park rather than waiting for an answer to\n * reach the keyword nobody can enforce.\n *\n * An `options` list on a `json` question is ignored because it constrains\n * nothing; JSON constraints come only from `schema`.\n *\n * @private\n */\nconst requestOf = (payload: Payload): Effect.Effect<Request, HumanTaskFailed> => {\n const request: Request = {\n kind: payload.kind,\n options: payload.options,\n ...(payload.schema === undefined ? {} : { schema: payload.schema })\n }\n if (payload.schema !== undefined && payload.kind !== \"json\") {\n return Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `A schema describes a \"json\" answer, and this question is an \"${payload.kind}\".`\n )\n )\n }\n if (payload.kind === \"select\" && (payload.options === undefined || payload.options.length === 0)) {\n return Effect.fail(\n failed(payload, \"request_invalid\", 0, [], `${tag} was called as a select with no options to choose from.`)\n )\n }\n if (payload.kind === \"json\" && payload.schema !== undefined) {\n const complaint = validateSchema(payload.schema)\n if (complaint !== undefined) return Effect.fail(failed(payload, \"request_invalid\", 0, [], complaint))\n }\n return Effect.succeed(request)\n}\n\n/**\n * Awaits one attempt, racing the answer against the task's deadline.\n *\n * The race is named per attempt because a durable race records its winner: one\n * name across attempts would replay the first attempt's answer forever. The\n * clock is NOT named per attempt, for the mirrored reason \u2014 the deadline is one\n * fact about the question.\n *\n * @private\n */\nconst attemptOnce = (\n payload: Payload,\n attempt: number,\n deadline: Duration.Duration | undefined\n): Effect.Effect<Settled, never, Crypto.Crypto | FlowRuntime | FlowInstance> => {\n const answered: Effect.Effect<Settled, never, FlowRuntime | FlowInstance> = Effect.map(\n DurableDeferred.await(deferred(payload.name, attempt)),\n (value): Settled => ({ _tag: \"answered\", value })\n )\n if (deadline === undefined) return answered\n return DurableDeferred.raceAll({\n name: `HumanTask/${payload.name}#${attempt}`,\n success: Settled,\n error: Schema.Never,\n effects: [\n answered,\n Effect.as(\n DurableClock.sleep({\n name: timeoutClockName(payload.name),\n duration: deadline,\n // The wait is the point: the question parks the execution rather than\n // holding a fiber open for however long a person takes.\n inMemoryThreshold: Duration.zero\n }),\n { _tag: \"timeout\" } as const\n )\n ]\n })\n}\n\n/**\n * What a refusal records: which question, which attempt, and why the answer\n * could not be accepted.\n *\n * @private\n */\nconst RejectionRecord = Schema.Struct({\n task: Schema.String,\n attempt: Schema.Number,\n reason: Schema.String\n})\n\n/**\n * Records that an answer was refused, as a step rather than as a log line.\n *\n * A refusal is a decision the run made about something a person did, and it is\n * the only part of the exchange that is not already durable: the answer is\n * recorded under its own wait point and the re-ask is recorded as the next\n * one, but WHY the answer was refused would otherwise live in a log stream\n * nobody replays. `Action.make` is the recorded boundary the rest of this\n * package already writes through \u2014 {@link module:DurableClock.sleep} takes it\n * for an in-memory wait \u2014 so the refusal is dispatched, journaled, and\n * replayed like any other sealed step, under a name that carries the task and\n * the attempt it refused.\n *\n * The payload names no time. A record whose contents depend on the wall clock\n * would differ between the first run and its replay, which is the one thing a\n * journaled decision may never do.\n *\n * @private\n */\nconst recordRejection = (task: string, attempt: number, reason: string) =>\n Action.make({\n name: `HumanTask/${task}#${attempt}/rejected`,\n tier: \"sealed\",\n success: RejectionRecord,\n execute: Effect.succeed({ task, attempt, reason })\n })\n\n/**\n * The human-task implementation: park, validate, re-ask, settle.\n *\n * Provide it beside the other action implementation layers a body calls, over\n * the {@link module:Implementations.layerImplementations} table they file\n * themselves in:\n *\n * ```ts\n * Layer.mergeAll(HumanTask.layer, Interpreter.layer(Release)).pipe(\n * Layer.provideMerge(Action.layerImplementations)\n * )\n * ```\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer: Layer.Layer<never, never, Crypto.Crypto | FlowRuntime> = action.toLayer((payload) =>\n Effect.gen(function*() {\n const instance = yield* FlowInstance\n const maxAttempts = yield* budgetOf(payload)\n const deadline = yield* deadlineOf(payload)\n const request = yield* requestOf(payload)\n const retained: RetainedRejections = { entries: [], chars: 0, omitted: 0 }\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const token = DurableDeferred.tokenFromExecutionId(deferred(payload.name, attempt), {\n flow: instance.flow,\n executionId: instance.executionId\n })\n // Declared rather than left to a driver's derivation, so the run parks\n // under `approval` carrying the ONE wait point that is currently open.\n // The question travels with the park for a different reason than the\n // token does: the token addresses the wait, and the question is what an\n // inbox has to render for a person to answer it at all. Without it a\n // parked run carried nothing but a wait name, so run-3's\n // `coding-clarification` could be listed and never asked.\n yield* annotateWaiting({ reason: \"approval\", token, request: declaredQuestion(payload, attempt, maxAttempts) })\n const settled = yield* attemptOnce(payload, attempt, deadline)\n // The attempt is over either way, so the declared park is over too. A\n // raced attempt awaits on a copied instance, so the branch that resolved\n // could not clear the annotation itself.\n yield* annotateWaiting(undefined)\n if (settled._tag === \"timeout\") {\n return yield* Effect.fail(\n failed(\n payload,\n \"timeout\",\n attempt,\n retained.entries,\n `Nobody answered \"${payload.name}\" within ${payload.timeoutMs} ms.`\n )\n )\n }\n const rejection = validate(settled.value, request)\n if (rejection === undefined) return settled.value\n retainRejection(retained, `attempt ${attempt}: ${rejection}`)\n yield* recordRejection(payload.name, attempt, rejection)\n }\n return yield* Effect.fail(\n failed(\n payload,\n \"rejected\",\n maxAttempts,\n retained.entries,\n `\"${payload.name}\" was asked ${maxAttempts} times without an answer it could accept.`\n )\n )\n })\n)\n\n/**\n * Records one answer to a human task.\n *\n * `token` is the value the run parked with \u2014 the `token` of the waiting\n * annotation, which is the wait point the current attempt is open on. The\n * runtime checks that exact approval wait and records the completion as one\n * mutation, so guessed, unopened, or stale attempt tokens cannot pre-answer a\n * run. An admitted answer then resumes the run through the ordinary durable\n * deferred path.\n *\n * The token is not a credential: anyone who knows or derives the address of\n * the open attempt can answer it. The host decides who may answer, and must\n * authorize the caller before calling `answer`.\n *\n * ```ts\n * yield* HumanTask.answer({ token: waiting.token, value: { decision: \"ship\" } })\n * ```\n *\n * The durable JSON boundary is validated here: the value must be inert,\n * detached, and within the exported depth, node, member, string, key, and byte\n * limits. Whether that JSON fits the question is the task's own judgment, made\n * where its kind and schema are known; a semantically refused answer stays\n * recorded so the record shows what was actually said. Call {@link validate}\n * first when the interface can refuse it while the person is still looking at\n * it.\n *\n * The TOKEN is checked. This entry point completes an arbitrary caller-supplied\n * address under `Schema.Json`, so it accepts only a token whose deferred name\n * {@link deferred} could have written. A token for a `DurableQueue` item, a\n * plain {@link module:WaitFor} gate, or an unrelated flow's deferred fails with\n * `TokenInvalid` carrying `deferred_mismatch` rather than writing a JSON exit\n * into a row another schema will decode.\n *\n * A syntactically valid HumanTask token can still fail with\n * `HumanAnswerInvalid` carrying `answer_not_open` when the addressed run is not\n * currently parked on that exact approval token.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const answer = (options: {\n readonly token: DurableDeferred.Token\n readonly value: typeof Schema.Json.Type\n}): Effect.Effect<void, DurableDeferred.TokenInvalid | HumanAnswerInvalid, FlowRuntime> =>\n Effect.gen(function*() {\n const admitted = BoundedJson.admit(options.value, JsonSchemaSubset.answerLimits)\n if (!admitted.ok) {\n return yield* Effect.fail(\n new HumanAnswerInvalid({\n message: `The human-task answer was not recorded: ${JsonSchemaSubset.truncateDiagnostic(admitted.complaint)}`\n })\n )\n }\n const parsed = yield* DurableDeferred.TokenParsed.parse(options.token)\n const target = answerableDeferred(parsed.deferredName)\n if (target === undefined) {\n return yield* Effect.fail(\n new DurableDeferred.TokenInvalid({\n code: \"deferred_mismatch\",\n message:\n `The token addresses deferred \"${\n JsonSchemaSubset.truncateDiagnostic(parsed.deferredName)\n }\", which is not a ` +\n \"human task wait point. Answer it through the surface that owns it.\"\n })\n )\n }\n const runtime = yield* FlowRuntime\n const outcome = yield* runtime.deferredDoneIfWaiting(target, {\n flowName: parsed.flowName,\n executionId: parsed.executionId,\n deferredName: parsed.deferredName,\n reason: \"approval\",\n token: options.token,\n exit: Exit.succeed(admitted.value)\n })\n if (outcome === \"NotWaiting\") {\n return yield* Effect.fail(\n new HumanAnswerInvalid({\n code: \"answer_not_open\",\n message: \"The human-task answer was not recorded because the run is not parked on this approval token.\"\n })\n )\n }\n })\n\n/**\n * Gives an answer the caller's own type.\n *\n * The action's success schema is `Schema.Json`, because what a person may\n * answer is described by the task's payload rather than by a TypeScript type.\n * `decode` is the other half: the author states the schema they were really\n * asking for, and the node downstream of the question carries that type.\n *\n * ```ts\n * const Decision = Schema.Struct({ decision: Schema.Literals([\"ship\", \"hold\"]) })\n *\n * HumanTask.action.call({ name: \"release\", kind: \"json\", prompt, schema }).pipe(\n * HumanTask.decode(Decision)\n * )\n * ```\n *\n * The two descriptions must agree. The answer already passed the task's own\n * JSON Schema before it reached here, so a value this schema rejects means the\n * payload's schema and the author's schema describe different answers \u2014 an\n * authoring mistake, not a human one \u2014 and it surfaces as a defect naming the\n * offending path rather than as a failure a body could sensibly catch.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const decode =\n <S extends Schema.ConstraintDecoder<unknown>>(schema: S) =>\n <E, R>(self: Node.Node<typeof Schema.Json.Type, E, R>): Node.Node<S[\"Type\"], E, R> =>\n Node.map(self, Schema.decodeUnknownSync(schema))\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCA,WAAsB;AAEtB,eAA0B;AAC1B,aAAwB;AACxB,WAAsB;AAEtB,aAAwB;AACxB,aAAwB;AACxB,mBAA8B;AAC9B,sBAAiC;AACjC,0BAA6B;AAC7B,yBAA4B;AAC5B,+BAAgC;AAChC,kBAA6B;AAC7B,uBAAkC;AAClC,cAAyB;AAuBlB,MAAM,OAAuE,OAAO,SAAS;AAAA,EAClG;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAkBM,MAAM,wBAAwB,OAAO,YAA6B;AAAA,EACvE;AAAA,EACA;AAAA,IACE,MAAM,OAAO,SAAS,CAAC,mBAAmB,YAAY,SAAS,CAAC;AAAA,IAChE,MAAM,OAAO;AAAA,IACb,UAAU,OAAO;AAAA,IACjB,YAAY,OAA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AAS,CAAC;AAAA,MAC7G,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,SAAS,OAAO,gBAAgB,YAAY,MAAM,QAAQ,KAAK;AACrE,QAAM,SAAS,mBAAmB,OAAO,YAAY;AACrD,MAAI,WAAW,QAAW;AACxB,WAAO,OAAO,OAAO;AAAA,MACnB,IAAI,gBAAgB,aAAa;AAAA,QAC/B,MAAM;AAAA,QACN,SACE,iCACE,iBAAiB,mBAAmB,OAAO,YAAY,CACzD;AAAA,MAEJ,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,UAAU,OAAO;AACvB,QAAM,UAAU,OAAO,QAAQ,sBAAsB,QAAQ;AAAA,IAC3D,UAAU,OAAO;AAAA,IACjB,aAAa,OAAO;AAAA,IACpB,cAAc,OAAO;AAAA,IACrB,QAAQ;AAAA,IACR,OAAO,QAAQ;AAAA,IACf,MAAM,KAAK,QAAQ,SAAS,KAAK;AAAA,EACnC,CAAC;AACD,MAAI,YAAY,cAAc;AAC5B,WAAO,OAAO,OAAO;AAAA,MACnB,IAAI,mBAAmB;AAAA,QACrB,MAAM;AAAA,QACN,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;AA2BI,MAAM,SACX,CAA8C,WAC9C,CAAO,SACL,KAAK,IAAI,MAAM,OAAO,kBAAkB,MAAM,CAAC;",
4
+ "sourcesContent": ["/**\n * Asking a person something, as an ordinary declared action.\n *\n * {@link module:WaitFor.action} is the general rendezvous: it parks until\n * something outside the run resolves it, and settles with whatever arrived.\n * That is the right primitive and the wrong affordance for a human, because a\n * human answers in prose, in a hurry, and sometimes wrongly. Smithers 0.x had\n * the affordance \u2014 a `HumanTask` with a kind, a prompt, an output schema, an\n * attempt budget, and a deadline \u2014 and this module is that affordance rebuilt\n * on the primitives this package already has.\n *\n * Four things are added to a bare wait:\n *\n * - a **kind**, so the four shapes a person is asked for (`ask`, `confirm`,\n * `select`, `json`) are stated rather than reconstructed from a schema;\n * - **validation**, so an answer that does not fit is refused where it arrives\n * instead of failing three steps later as a decode error;\n * - **re-asking**, so a refused answer parks again on a NEW wait point rather\n * than ending the run, until the attempt budget is spent;\n * - a **deadline**, so a question nobody answers settles instead of parking\n * forever.\n *\n * All four are built from what is already durable. Each attempt is its own wait\n * point in {@link module:WaitFor}'s namespace \u2014 `WaitFor/<name>#<attempt>` \u2014 so\n * an answer is recorded exactly as any other durable deferred completion is, a\n * refused answer stays recorded under the attempt that refused it, and a\n * re-driven round replays every answer it already has before parking on the\n * first attempt that has none. The reason an answer was refused is recorded\n * too, as a sealed step named `HumanTask/<name>#<attempt>/rejected`, so the\n * judgment the run made sits in the journal beside the answer it judged rather\n * than in a log stream nobody replays. The park is declared through the ordinary\n * waiting vocabulary under `approval`, carrying the current attempt's token, so\n * whoever collects answers always sees the one wait point that is open. The\n * deadline is a {@link module:DurableClock} armed once per task and raced\n * against every attempt, which makes it a deadline for the QUESTION rather than\n * for one attempt at answering it.\n *\n * @since 0.1.0\n */\n\nimport * as Node from \"@smthrs/plan/Node\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport type * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableClock from \"./DurableClock.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\nimport { annotateWaiting } from \"./FlowRuntime/WaitingAnnotation.ts\"\nimport * as BoundedJson from \"./internal/BoundedJson.ts\"\nimport * as JsonSchemaSubset from \"./internal/JsonSchemaSubset.ts\"\nimport * as WaitFor from \"./WaitFor.ts\"\n\n/**\n * The shape a person is asked for.\n *\n * `ask` wants prose, `confirm` wants yes or no, `select` wants one of the\n * options the task names, and `json` wants a value the task's JSON Schema\n * accepts. The kind is what an interface renders and what {@link validate}\n * checks; it is stated rather than inferred, because a text box and a two-\n * button confirmation are different questions even when both answers happen to\n * be strings.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Kind = \"ask\" | \"confirm\" | \"select\" | \"json\"\n\n/**\n * The schema the `kind` payload field is declared with.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Kind: Schema.Literals<readonly [\"ask\", \"confirm\", \"select\", \"json\"]> = Schema.Literals([\n \"ask\",\n \"confirm\",\n \"select\",\n \"json\"\n])\n\n/**\n * A question that ended without an answer the task could accept.\n *\n * `request_invalid` is the author's mistake \u2014 a `select` with no options, an\n * attempt budget below one, a deadline that is not a length of time, a JSON\n * Schema outside the supported subset \u2014 and is refused before anyone is asked\n * anything. `rejected` means every attempt was\n * spent on answers the task refused, and `timeout` means the deadline passed\n * with the question still open. All three are typed failures rather than\n * defects, so a body recovers from them with `Node.catch` like any other\n * declared failure \u2014 which is the point, because \"the reviewer never answered\"\n * is an ordinary outcome of asking a reviewer.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class HumanTaskFailed extends Schema.TaggedError<HumanTaskFailed>()(\n \"@smthrs/flow/HumanTaskFailed\",\n {\n code: Schema.Literals([\"request_invalid\", \"rejected\", \"timeout\"]),\n task: Schema.String,\n attempts: Schema.Number,\n rejections: Schema.Array(Schema.String),\n message: Schema.String\n }\n) {}\n\n/**\n * An answer refused before it could consume durable storage.\n *\n * @category errors\n * @since 1.0.0\n */\nexport class HumanAnswerInvalid extends Schema.TaggedError<HumanAnswerInvalid>()(\n \"@smthrs/flow/HumanAnswerInvalid\",\n {\n code: Schema.Literals([\"answer_invalid\", \"answer_not_open\"]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"answer_invalid\"))\n ),\n message: Schema.String\n }\n) {}\n\n/**\n * The tag the human-task declaration is catalogued and resolved under.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const tag = \"system/human-task\"\n\n/**\n * The attempt budget a task that names none is asked under.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const defaultMaxAttempts = 10\n\n/**\n * The deepest supported JSON Schema path, counting the root as depth zero.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxSchemaDepth = JsonSchemaSubset.maxSchemaDepth\n\n/**\n * The most schema objects one human-task request may contain.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxSchemaNodes = JsonSchemaSubset.maxSchemaNodes\n\n/**\n * The most JSON values embedded across schema keywords such as `enum`.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaValueNodes = JsonSchemaSubset.maxSchemaValueNodes\n\n/**\n * The deepest JSON value embedded in a schema, including enum members.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaValueDepth = JsonSchemaSubset.maxSchemaValueDepth\n\n/**\n * The most JSON values one answer validation may visit.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxAnswerNodes = JsonSchemaSubset.maxAnswerNodes\n\n/**\n * The largest encoded JSON answer that can enter the durable store.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxAnswerBytes = JsonSchemaSubset.maxAnswerBytes\n\n/**\n * The largest encoded JSON Schema carried by one question.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxSchemaBytes = JsonSchemaSubset.maxSchemaBytes\n\n/**\n * The deepest admitted answer tree.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxAnswerDepth = JsonSchemaSubset.maxAnswerDepth\n\n/**\n * The largest encoded string value admitted in a request or answer.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonStringBytes = JsonSchemaSubset.maxJsonStringBytes\n\n/**\n * The largest encoded object key admitted in a request or answer.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonKeyBytes = JsonSchemaSubset.maxJsonKeyBytes\n\n/**\n * The most members admitted in one JSON array or object.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxJsonMembers = JsonSchemaSubset.maxJsonMembers\n\n/**\n * The largest encoded task name.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxTaskNameBytes = 1_024\n\n/**\n * The largest encoded prompt.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxPromptBytes = 64 * 1024\n\n/**\n * The largest option list on one select question.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxOptions = 256\n\n/**\n * The largest encoded select option.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const maxOptionBytes = 4 * 1024\n\n/**\n * The largest attempt budget one human task may declare.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxAttemptBudget = 1_000\n\n/**\n * The most caller-supplied characters retained in one rendered diagnostic.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxDiagnosticChars = JsonSchemaSubset.maxDiagnosticChars\n\n/**\n * The most characters retained across a terminal failure's rejection list.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const maxRetainedRejectionChars = 8_192\n\n/**\n * The durable deferred one attempt at answering resolves through.\n *\n * Attempts are separate wait points on purpose. A durable deferred records the\n * FIRST completion and replays it forever, so re-asking on the same wait point\n * would read the refused answer again on every round; a new point per attempt\n * makes \"answer again\" expressible without a second completion mechanism, and\n * leaves the refused answers in place as the record of what was asked and what\n * came back.\n *\n * The name lives in {@link module:WaitFor}'s namespace because an answer is\n * completed through exactly the {@link module:WaitFor} path: a token, and\n * `DurableDeferred.succeed`. {@link answer} is that call with the token parsed\n * for you.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const deferred = (\n name: string,\n attempt: number\n): DurableDeferred.DurableDeferred<typeof Schema.Json> => WaitFor.deferred(`${name}#${attempt}`)\n\n/** The namespace {@link module:WaitFor.deferred} prepends to every wait point. */\nconst waitForNamespace = /^WaitFor\\//\n\n/**\n * The only spelling of an attempt {@link deferred} writes: a canonical decimal\n * with no sign, no leading zero, no exponent, and no fraction.\n *\n * `Number()` alone is not this check. `NaN`, `Infinity`, `-Infinity`, and\n * `1e+21` all survive a `Number()`/`String()` round trip character for\n * character, so a gate that rebuilt the name through `Number()` would accept\n * them as attempts the action never parks on.\n */\nconst attemptSuffix = /^(0|[1-9][0-9]*)$/\n\n/**\n * The deferred a token addresses, when {@link deferred} could have named it.\n *\n * {@link answer} builds its deferred FROM the caller's token, so\n * `DurableDeferred.done`'s own name check compares a name against itself and\n * can never refuse. This is the check that is not vacuous: the name is taken\n * apart at its attempt separator, the suffix is required to be a canonical\n * decimal naming an attempt the action can park on (a safe integer of one or\n * more), the name is rebuilt through {@link deferred}, and it is accepted only\n * when the rebuilt name is character-for-character the one the token carried.\n * A name {@link deferred} cannot produce -- a `DurableQueue` item address, a\n * plain {@link module:WaitFor} gate, another flow's deferred, a suffix spelled\n * any way other than the decimal {@link deferred} writes -- fails, so a\n * foreign token cannot be completed under `Schema.Json` through the\n * human-answer path.\n *\n * This bounds the confusion to human-task wait points. It does NOT distinguish\n * two human tasks from each other, nor a wait point an author deliberately\n * named to collide with one; separating those needs the deferred's schema and\n * purpose carried in the address itself, which is a wire-format change.\n *\n * @private\n */\nconst answerableDeferred = (\n deferredName: string\n): DurableDeferred.DurableDeferred<typeof Schema.Json> | undefined => {\n const separator = deferredName.lastIndexOf(\"#\")\n if (separator === -1) return undefined\n const suffix = deferredName.slice(separator + 1)\n if (!attemptSuffix.test(suffix)) return undefined\n const attempt = Number(suffix)\n if (!Number.isSafeInteger(attempt) || attempt < 1) return undefined\n const rebuilt = deferred(deferredName.slice(0, separator).replace(waitForNamespace, \"\"), attempt)\n return rebuilt.name === deferredName ? rebuilt : undefined\n}\n\n/**\n * The clock a task's deadline is armed on.\n *\n * One clock per task, not one per attempt: the deadline bounds how long the\n * QUESTION stays open, so re-asking does not extend it. The name is the task's,\n * so every attempt's race arms and awaits the same durable timer \u2014 a clock row\n * keeps the deadline it was first armed with, which is what makes the bound\n * survive a restart.\n *\n * The deadline settles on both hosts. `@smthrs/engine`'s in-process engine and\n * the SQLite engine store each re-drive a run parked on\n * {@link module:DurableDeferred.raceAll}, so the durable timer wakes the\n * question wherever it was asked\n * (`packages/smithers/flows/engine-store/test/RacedParkResume.test.ts`).\n *\n * @private\n */\nconst timeoutClockName = (name: string): string => `HumanTask/${name}/timeout`\n\n/**\n * What one attempt settled with: the answer that arrived, or the deadline.\n *\n * @private\n */\nconst Settled = Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"answered\"), value: Schema.Json }),\n Schema.Struct({ _tag: Schema.Literal(\"timeout\") })\n])\n\ntype Settled = typeof Settled.Type\n\n/**\n * What {@link validate} checks an answer against.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Request {\n readonly kind: Kind\n /** Ignored for `json`: an option list alone constrains no JSON value. */\n readonly options?: ReadonlyArray<string> | undefined\n readonly schema?: unknown\n}\n\n/**\n * Checks that a JSON Schema stays inside the bounded subset, at every depth.\n *\n * This is a different question from {@link validate}, which asks whether an\n * ANSWER fits a schema. A question is worth refusing before anyone is asked it:\n * a constraint the subset cannot enforce would otherwise be silently dropped,\n * and the person would be told their answer was fine when half of what was\n * asked for went unchecked.\n *\n * The subset is `type` (`object`, `array`, `string`, `number`, `integer`,\n * `boolean`, `null`), `enum`, `properties`, `required`, `items`, and\n * `nullable`; it lives in `internal/JsonSchemaSubset`.\n *\n * Returns the first reason the schema is out of bounds, or `undefined` when the\n * whole tree is inside it.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const validateSchema = (\n schema: unknown,\n path: ReadonlyArray<string> = []\n): string | undefined => JsonSchemaSubset.validateSchema(schema, path)\n\n/**\n * Checks one answer against the question that was asked.\n *\n * Returns the reason the answer was refused, or `undefined` when it fits. It is\n * exported because it is the same check an interface should run BEFORE it\n * records an answer: refusing a typo in the text box the person is looking at\n * is worth more than refusing it one durable round later.\n *\n * ```ts\n * const rejection = HumanTask.validate(value, { kind: \"select\", options })\n * if (rejection !== undefined) return showTheReviewer(rejection)\n * ```\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const validate = (value: unknown, request: Request): string | undefined => {\n switch (request.kind) {\n case \"ask\":\n if (typeof value !== \"string\") return \"The answer must be a string.\"\n return BoundedJson.textFits(value, maxJsonStringBytes)\n ? undefined\n : `The answer must fit within ${maxJsonStringBytes} encoded bytes of well-formed text.`\n case \"confirm\":\n return typeof value === \"boolean\" ? undefined : \"The answer must be a boolean.\"\n case \"select\": {\n if (request.options === undefined || request.options.length === 0) {\n return \"The question declares no options to choose from.\"\n }\n if (\n request.options.length > maxOptions ||\n request.options.some((option) => typeof option !== \"string\" || !BoundedJson.textFits(option, maxOptionBytes))\n ) {\n return `The question's options exceed the ${maxOptions}-member or ${maxOptionBytes}-byte limits.`\n }\n return request.options.some((option) => option === value)\n ? undefined\n : `The answer ${JsonSchemaSubset.renderDiagnostic(value)} is not one of ${\n JsonSchemaSubset.truncateDiagnostic(request.options.join(\", \"))\n }.`\n }\n default: {\n if (request.schema !== undefined) return JsonSchemaSubset.check(value, request.schema)\n const admitted = BoundedJson.admit(value, JsonSchemaSubset.answerLimits)\n return admitted.ok ? undefined : admitted.complaint\n }\n }\n}\n\n/**\n * The fields a question is asked with.\n *\n * @private\n */\nconst boundedText = (label: string, maximumBytes: number) =>\n Schema.String.check(\n Schema.makeFilter(\n (value) =>\n BoundedJson.textFits(value, maximumBytes) ||\n `${label} must be well-formed text within ${maximumBytes} encoded bytes`,\n { title: `bounded${label.replaceAll(\" \", \"\")}` }\n )\n )\n\nconst boundedSchema = Schema.Json.check(\n Schema.makeFilter(\n (value) => {\n const admitted = BoundedJson.admit(value, JsonSchemaSubset.schemaLimits)\n return admitted.ok || admitted.complaint\n },\n { title: \"boundedHumanTaskSchema\" }\n )\n)\n\nconst option = boundedText(\"option\", maxOptionBytes)\n\nconst payloadFields = {\n name: boundedText(\"task name\", maxTaskNameBytes),\n kind: Kind,\n prompt: boundedText(\"prompt\", maxPromptBytes),\n options: Schema.optional(\n Schema.Array(option).check(Schema.isMaxLength(maxOptions))\n ),\n schema: Schema.optional(boundedSchema),\n timeoutMs: Schema.optional(Schema.Number),\n maxAttempts: Schema.optional(Schema.Number)\n}\n\n/**\n * The declared human-task action.\n *\n * **When to use**\n *\n * Use it in a body wherever the next step depends on a person: a release that\n * needs sign-off, a plan that needs a choice, a field the run cannot compute.\n * The node settles with the answer, so downstream steps read it the way they\n * read any other step result, and {@link decode} gives that answer the caller's\n * own type.\n *\n * ```ts\n * HumanTask.action.call({\n * name: \"release\",\n * kind: \"select\",\n * prompt: \"Which build should ship?\",\n * options: [\"canary\", \"stable\"],\n * timeoutMs: 6 * 60 * 60 * 1000\n * })\n * ```\n *\n * `name` addresses the question, so two calls naming one question in one\n * execution await one answer \u2014 the same reading {@link module:WaitFor} takes,\n * for the same reason: a person has to be able to name what they are answering.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const action: Action.Declared<\n typeof tag,\n Schema.Struct<typeof payloadFields>,\n typeof Schema.Json,\n typeof HumanTaskFailed,\n never\n> = Action.makeSystem(tag, {\n payload: payloadFields,\n success: Schema.Json,\n error: HumanTaskFailed,\n tier: \"sealed\"\n})\n\n/** The payload the action is called with, as its implementation reads it. */\ntype Payload = typeof action.payloadSchema.Type\n\n/**\n * The question a park publishes about itself, as the JSON text the durable\n * waiting row stores.\n *\n * It is the payload's own fields, narrowed to what an interface needs to\n * render an answer box and refuse a bad answer before a person sends it: the\n * kind picks the control, the prompt is the question, `options` fills a\n * select, `schema` validates a JSON answer, and the two attempt numbers say\n * how much of the budget is left. The answer VALUE never appears here \u2014 this\n * describes the question, not what anybody said.\n *\n * @private\n */\nconst declaredQuestion = (\n payload: Payload,\n attempt: number,\n maxAttempts: number\n): string =>\n JSON.stringify({\n task: \"human\",\n name: payload.name,\n kind: payload.kind,\n prompt: payload.prompt,\n attempt,\n maxAttempts,\n ...(payload.options === undefined ? {} : { options: [...payload.options] }),\n ...(payload.schema === undefined ? {} : { schema: payload.schema })\n })\n\n/** Builds the failure a task settles with, with the reasons it refused. */\nconst failed = (\n payload: Payload,\n code: typeof HumanTaskFailed.Type[\"code\"],\n attempts: number,\n rejections: ReadonlyArray<string>,\n message: string\n): HumanTaskFailed => new HumanTaskFailed({ code, task: payload.name, attempts, rejections, message })\n\ninterface RetainedRejections {\n readonly entries: Array<string>\n chars: number\n omitted: number\n}\n\n/** Describes the tail of a rejection history that could not be retained. */\nconst omissionMarker = (count: number): string => `${count} further rejections were omitted.`\n\n/** Adds one rejection while keeping the terminal rejection history bounded. */\nconst retainRejection = (state: RetainedRejections, rejection: string): void => {\n const alreadyOmitting = state.omitted > 0\n if (alreadyOmitting) {\n const previousMarker = state.entries.pop()!\n state.chars -= previousMarker.length\n }\n if (!alreadyOmitting && state.chars + rejection.length <= maxRetainedRejectionChars) {\n state.entries.push(rejection)\n state.chars += rejection.length\n return\n }\n state.omitted++\n let marker = omissionMarker(state.omitted)\n while (state.chars + marker.length > maxRetainedRejectionChars) {\n const removed = state.entries.pop()!\n state.chars -= removed.length\n state.omitted++\n marker = omissionMarker(state.omitted)\n }\n state.entries.push(marker)\n state.chars += marker.length\n}\n\n/**\n * The attempt budget a payload asks for, refused when it is not a whole number\n * of attempts.\n *\n * @private\n */\nconst budgetOf = (payload: Payload): Effect.Effect<number, HumanTaskFailed> => {\n const maxAttempts = payload.maxAttempts ?? defaultMaxAttempts\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n return Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with maxAttempts ${maxAttempts}. A question is asked at least once.`\n )\n )\n }\n return maxAttempts <= maxAttemptBudget\n ? Effect.succeed(maxAttempts)\n : Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with maxAttempts ${maxAttempts}. A question asked more than ` +\n `${maxAttemptBudget} times is a stuck question.`\n )\n )\n}\n\n/**\n * The deadline a payload asks for, refused when it is not a length of time.\n *\n * `Duration.millis` takes any number, so an unchecked deadline does not fail \u2014\n * it changes what the question means. `NaN` becomes zero and a negative stays\n * negative, so both are deadlines that have ALREADY passed: the task times out\n * on its first park and nobody is ever really asked. `Infinity` becomes the\n * infinite duration, so the race has a branch that can never win and a question\n * asked with a deadline has none. All three are the same authoring mistake as a\n * `select` with no options, and they are refused in the same place, before the\n * first park, rather than surfacing as a `timeout` nobody waited for.\n *\n * @private\n */\nconst deadlineOf = (payload: Payload): Effect.Effect<Duration.Duration | undefined, HumanTaskFailed> => {\n const timeoutMs = payload.timeoutMs\n if (timeoutMs === undefined) return Effect.succeed(undefined)\n // The timeout clock is due at its start plus the deadline, and a durable\n // store records that due time as a safe integer.\n return Number.isFinite(timeoutMs) && timeoutMs >= 0 && timeoutMs <= Number.MAX_SAFE_INTEGER\n ? Effect.succeed(Duration.millis(timeoutMs))\n : Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `${tag} was called with timeoutMs ${timeoutMs}. A deadline is a number of milliseconds ` +\n `from 0 to ${Number.MAX_SAFE_INTEGER}; the question would be over before it was asked, or ` +\n \"never over at all.\"\n )\n )\n}\n\n/**\n * Refuses a question nobody could answer correctly, before anyone is asked.\n *\n * A `select` with no options and a schema outside the supported subset are\n * authoring mistakes whose only symptom at answer time would be a person being\n * refused for something they did not do, so {@link validateSchema} walks the\n * whole schema tree before the first park rather than waiting for an answer to\n * reach the keyword nobody can enforce.\n *\n * An `options` list on a `json` question is ignored because it constrains\n * nothing; JSON constraints come only from `schema`.\n *\n * @private\n */\nconst requestOf = (payload: Payload): Effect.Effect<Request, HumanTaskFailed> => {\n const request: Request = {\n kind: payload.kind,\n options: payload.options,\n ...(payload.schema === undefined ? {} : { schema: payload.schema })\n }\n if (payload.schema !== undefined && payload.kind !== \"json\") {\n return Effect.fail(\n failed(\n payload,\n \"request_invalid\",\n 0,\n [],\n `A schema describes a \"json\" answer, and this question is an \"${payload.kind}\".`\n )\n )\n }\n if (payload.kind === \"select\" && (payload.options === undefined || payload.options.length === 0)) {\n return Effect.fail(\n failed(payload, \"request_invalid\", 0, [], `${tag} was called as a select with no options to choose from.`)\n )\n }\n if (payload.kind === \"json\" && payload.schema !== undefined) {\n const complaint = validateSchema(payload.schema)\n if (complaint !== undefined) return Effect.fail(failed(payload, \"request_invalid\", 0, [], complaint))\n }\n return Effect.succeed(request)\n}\n\n/**\n * Awaits one attempt, racing the answer against the task's deadline.\n *\n * The race is named per attempt because a durable race records its winner: one\n * name across attempts would replay the first attempt's answer forever. The\n * clock is NOT named per attempt, for the mirrored reason \u2014 the deadline is one\n * fact about the question.\n *\n * @private\n */\nconst attemptOnce = (\n payload: Payload,\n attempt: number,\n deadline: Duration.Duration | undefined\n): Effect.Effect<Settled, never, Crypto.Crypto | FlowRuntime | FlowInstance> => {\n const answered: Effect.Effect<Settled, never, FlowRuntime | FlowInstance> = Effect.map(\n DurableDeferred.await(deferred(payload.name, attempt)),\n (value): Settled => ({ _tag: \"answered\", value })\n )\n if (deadline === undefined) return answered\n return DurableDeferred.raceAll({\n name: `HumanTask/${payload.name}#${attempt}`,\n success: Settled,\n error: Schema.Never,\n effects: [\n answered,\n Effect.as(\n DurableClock.sleep({\n name: timeoutClockName(payload.name),\n duration: deadline,\n // The wait is the point: the question parks the execution rather than\n // holding a fiber open for however long a person takes.\n inMemoryThreshold: Duration.zero\n }),\n { _tag: \"timeout\" } as const\n )\n ]\n })\n}\n\n/**\n * What a refusal records: which question, which attempt, and why the answer\n * could not be accepted.\n *\n * @private\n */\nconst RejectionRecord = Schema.Struct({\n task: Schema.String,\n attempt: Schema.Number,\n reason: Schema.String\n})\n\n/**\n * Records that an answer was refused, as a step rather than as a log line.\n *\n * A refusal is a decision the run made about something a person did, and it is\n * the only part of the exchange that is not already durable: the answer is\n * recorded under its own wait point and the re-ask is recorded as the next\n * one, but WHY the answer was refused would otherwise live in a log stream\n * nobody replays. `Action.make` is the recorded boundary the rest of this\n * package already writes through \u2014 {@link module:DurableClock.sleep} takes it\n * for an in-memory wait \u2014 so the refusal is dispatched, journaled, and\n * replayed like any other sealed step, under a name that carries the task and\n * the attempt it refused.\n *\n * The payload names no time. A record whose contents depend on the wall clock\n * would differ between the first run and its replay, which is the one thing a\n * journaled decision may never do.\n *\n * @private\n */\nconst recordRejection = (task: string, attempt: number, reason: string) =>\n Action.make({\n name: `HumanTask/${task}#${attempt}/rejected`,\n tier: \"sealed\",\n success: RejectionRecord,\n execute: Effect.succeed({ task, attempt, reason })\n })\n\n/**\n * The human-task implementation: park, validate, re-ask, settle.\n *\n * Provide it beside the other action implementation layers a body calls, over\n * the {@link module:Implementations.layerImplementations} table they file\n * themselves in:\n *\n * ```ts\n * Layer.mergeAll(HumanTask.layer, Interpreter.layer(Release)).pipe(\n * Layer.provideMerge(Action.layerImplementations)\n * )\n * ```\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer: Layer.Layer<never, never, Crypto.Crypto | FlowRuntime> = action.toLayer((payload) =>\n Effect.gen(function*() {\n const instance = yield* FlowInstance\n const maxAttempts = yield* budgetOf(payload)\n const deadline = yield* deadlineOf(payload)\n const request = yield* requestOf(payload)\n const retained: RetainedRejections = { entries: [], chars: 0, omitted: 0 }\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const token = DurableDeferred.tokenFromExecutionId(deferred(payload.name, attempt), {\n flow: instance.flow,\n executionId: instance.executionId\n })\n // Declared rather than left to a driver's derivation, so the run parks\n // under `approval` carrying the ONE wait point that is currently open.\n // The question travels with the park for a different reason than the\n // token does: the token addresses the wait, and the question is what an\n // inbox has to render for a person to answer it at all. Without it a\n // parked run carried nothing but a wait name, so run-3's\n // `coding-clarification` could be listed and never asked.\n yield* annotateWaiting({ reason: \"approval\", token, request: declaredQuestion(payload, attempt, maxAttempts) })\n const settled = yield* attemptOnce(payload, attempt, deadline)\n // The attempt is over either way, so the declared park is over too. A\n // raced attempt awaits on a copied instance, so the branch that resolved\n // could not clear the annotation itself.\n yield* annotateWaiting(undefined)\n if (settled._tag === \"timeout\") {\n return yield* Effect.fail(\n failed(\n payload,\n \"timeout\",\n attempt,\n retained.entries,\n `Nobody answered \"${payload.name}\" within ${payload.timeoutMs} ms.`\n )\n )\n }\n const rejection = validate(settled.value, request)\n if (rejection === undefined) return settled.value\n retainRejection(retained, `attempt ${attempt}: ${rejection}`)\n yield* recordRejection(payload.name, attempt, rejection)\n }\n return yield* Effect.fail(\n failed(\n payload,\n \"rejected\",\n maxAttempts,\n retained.entries,\n `\"${payload.name}\" was asked ${maxAttempts} times without an answer it could accept.`\n )\n )\n })\n)\n\n/**\n * Records one answer to a human task.\n *\n * `token` is the value the run parked with \u2014 the `token` of the waiting\n * annotation, which is the wait point the current attempt is open on. The\n * runtime checks that exact approval wait and records the completion as one\n * mutation, so guessed, unopened, or stale attempt tokens cannot pre-answer a\n * run. An admitted answer then resumes the run through the ordinary durable\n * deferred path.\n *\n * The token is not a credential: anyone who knows or derives the address of\n * the open attempt can answer it. The host decides who may answer, and must\n * authorize the caller before calling `answer`.\n *\n * ```ts\n * yield* HumanTask.answer({ token: waiting.token, value: { decision: \"ship\" } })\n * ```\n *\n * The durable JSON boundary is validated here: the value must be inert,\n * detached, and within the exported depth, node, member, string, key, and byte\n * limits. Whether that JSON fits the question is the task's own judgment, made\n * where its kind and schema are known; a semantically refused answer stays\n * recorded so the record shows what was actually said. Call {@link validate}\n * first when the interface can refuse it while the person is still looking at\n * it.\n *\n * The TOKEN is checked. This entry point completes an arbitrary caller-supplied\n * address under `Schema.Json`, so it accepts only a token whose deferred name\n * {@link deferred} could have written. A token for a `DurableQueue` item, a\n * plain {@link module:WaitFor} gate, or an unrelated flow's deferred fails with\n * `TokenInvalid` carrying `deferred_mismatch` rather than writing a JSON exit\n * into a row another schema will decode.\n *\n * A syntactically valid HumanTask token can still fail with\n * `HumanAnswerInvalid` carrying `answer_not_open` when the addressed run is not\n * currently parked on that exact approval token.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const answer = (options: {\n readonly token: DurableDeferred.Token\n readonly value: typeof Schema.Json.Type\n}): Effect.Effect<void, DurableDeferred.TokenInvalid | HumanAnswerInvalid, FlowRuntime> =>\n Effect.gen(function*() {\n const admitted = BoundedJson.admit(options.value, JsonSchemaSubset.answerLimits)\n if (!admitted.ok) {\n return yield* Effect.fail(\n new HumanAnswerInvalid({\n message: `The human-task answer was not recorded: ${JsonSchemaSubset.truncateDiagnostic(admitted.complaint)}`\n })\n )\n }\n const parsed = yield* DurableDeferred.TokenParsed.parse(options.token)\n const target = answerableDeferred(parsed.deferredName)\n if (target === undefined) {\n return yield* Effect.fail(\n new DurableDeferred.TokenInvalid({\n code: \"deferred_mismatch\",\n message:\n `The token addresses deferred \"${\n JsonSchemaSubset.truncateDiagnostic(parsed.deferredName)\n }\", which is not a ` +\n \"human task wait point. Answer it through the surface that owns it.\"\n })\n )\n }\n const runtime = yield* FlowRuntime\n const outcome = yield* runtime.deferredDoneIfWaiting(target, {\n flowName: parsed.flowName,\n executionId: parsed.executionId,\n deferredName: parsed.deferredName,\n reason: \"approval\",\n token: options.token,\n exit: Exit.succeed(admitted.value)\n })\n if (outcome === \"NotWaiting\") {\n return yield* Effect.fail(\n new HumanAnswerInvalid({\n code: \"answer_not_open\",\n message: \"The human-task answer was not recorded because the run is not parked on this approval token.\"\n })\n )\n }\n })\n\n/**\n * Gives an answer the caller's own type.\n *\n * The action's success schema is `Schema.Json`, because what a person may\n * answer is described by the task's payload rather than by a TypeScript type.\n * `decode` is the other half: the author states the schema they were really\n * asking for, and the node downstream of the question carries that type.\n *\n * ```ts\n * const Decision = Schema.Struct({ decision: Schema.Literals([\"ship\", \"hold\"]) })\n *\n * HumanTask.action.call({ name: \"release\", kind: \"json\", prompt, schema }).pipe(\n * HumanTask.decode(Decision)\n * )\n * ```\n *\n * The two descriptions must agree. The answer already passed the task's own\n * JSON Schema before it reached here, so a value this schema rejects means the\n * payload's schema and the author's schema describe different answers \u2014 an\n * authoring mistake, not a human one \u2014 and it surfaces as a defect naming the\n * offending path rather than as a failure a body could sensibly catch.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const decode =\n <S extends Schema.ConstraintDecoder<unknown>>(schema: S) =>\n <E, R>(self: Node.Node<typeof Schema.Json.Type, E, R>): Node.Node<S[\"Type\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AAA,IAC3D,UAAU,OAAO;AAAA,IACjB,aAAa,OAAO;AAAA,IACpB,cAAc,OAAO;AAAA,IACrB,QAAQ;AAAA,IACR,OAAO,QAAQ;AAAA,IACf,MAAM,KAAK,QAAQ,SAAS,KAAK;AAAA,EACnC,CAAC;AACD,MAAI,YAAY,cAAc;AAC5B,WAAO,OAAO,OAAO;AAAA,MACnB,IAAI,mBAAmB;AAAA,QACrB,MAAM;AAAA,QACN,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;AA2BI,MAAM,SACX,CAA8C,WAC9C,CAAO,SACL,KAAK,IAAI,MAAM,OAAO,kBAAkB,MAAM,CAAC;",
6
6
  "names": ["option"]
7
7
  }
@@ -44,6 +44,11 @@ import { FlowRuntime } from "./FlowRuntime/FlowRuntime.ts";
44
44
  * replay must line up with: the origin and the clock are addressed by fixed
45
45
  * names within the execution.
46
46
  *
47
+ * A deadline that is not a positive finite duration, a `startedAtMs` that is
48
+ * not finite, or a bound that would expire after epoch millisecond
49
+ * `Number.MAX_SAFE_INTEGER` dies with a `RangeError`: a durable store records
50
+ * the clock's due time as a safe integer.
51
+ *
47
52
  * @category constructors
48
53
  * @since 1.0.0
49
54
  */
@@ -1 +1 @@
1
- {"version":3,"file":"Deadline.d.ts","sourceRoot":"","sources":["../../src/Deadline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,KAAK,MAAM,MAAM,eAAe,CAAA;AAC5C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAMvC,OAAO,EAAW,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAA;AAgB1D;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MA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AC,KAAG,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,YAAY,CAwBzE,CAAA;AAEN;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,KAAK,GAAI,SAAS;IAC7B,kCAAkC;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,qEAAqE;IACrE,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,KAAK,GAAG,SAAS,CAAA;IAC9C,sDAAsD;IACtD,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAC1C,MACA,CAAC,EAAE,CAAC,EAAE,CAAC,EACN,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KAC3B,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,WAAW,GAAG,YAAY,GAAG,MAAM,CAAC,MAAM,CACmB,CAAA"}
@@ -62,6 +62,11 @@ const origin = Action.make({
62
62
  * replay must line up with: the origin and the clock are addressed by fixed
63
63
  * names within the execution.
64
64
  *
65
+ * A deadline that is not a positive finite duration, a `startedAtMs` that is
66
+ * not finite, or a bound that would expire after epoch millisecond
67
+ * `Number.MAX_SAFE_INTEGER` dies with a `RangeError`: a durable store records
68
+ * the clock's due time as a safe integer.
69
+ *
65
70
  * @category constructors
66
71
  * @since 1.0.0
67
72
  */
@@ -78,7 +83,14 @@ export const start = (options) => Effect.gen(function* () {
78
83
  if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {
79
84
  return yield* Effect.die(new RangeError(`Deadline.start: "${options.flowName}" deadline must be a positive finite duration`));
80
85
  }
81
- lineage = { startedAtMs: options.startedAtMs ?? (yield* origin), deadlineMs };
86
+ const startedAtMs = options.startedAtMs ?? (yield* origin);
87
+ // The clock armed below is due at `startedAtMs + deadlineMs`, and a
88
+ // durable store records a due time as a safe integer.
89
+ if (!Number.isFinite(startedAtMs) || startedAtMs + deadlineMs > Number.MAX_SAFE_INTEGER) {
90
+ return yield* Effect.die(new RangeError(`Deadline.start: "${options.flowName}" deadline must expire by epoch millisecond ` +
91
+ `${Number.MAX_SAFE_INTEGER}, and a ${deadlineMs} ms deadline from ${startedAtMs} does not`));
92
+ }
93
+ lineage = { startedAtMs, deadlineMs };
82
94
  }
83
95
  const remaining = yield* remainingMs(lineage);
84
96
  if (remaining > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"Deadline.js","sourceRoot":"","sources":["../../src/Deadline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAA;AAC3C,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAC7D,OAAO,EAAE,OAAO,EAAwB,MAAM,kBAAkB,CAAA;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAA;AAE1D;;;;;;GAMG;AACH,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC;IACzB,IAAI,EAAE,gCAAgC;IACtC,IAAI,EAAE,QAAQ;IACd,OAAO,EAAE,MAAM,CAAC,MAAM;IACtB,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;CAC9D,CAAC,CAAA;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,C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C,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IACzG,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAA;IAChC,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5D,QAAQ,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC;YAC7B,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,CAAC,OAAO,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,EAAE,CAAC;YACvG,QAAQ;SACT,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAC,CAAA;AAEN;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,OAOrB,EAAE,EAAE,CACL,CACE,IAA4B,EACyC,EAAE,CACvE,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA","sourcesContent":["/**\n * The wall-clock bound one run of a flow settles by.\n *\n * A deadline counts from the run's FIRST start, which is journaled, so it\n * survives park, resume and process death: a restarted engine honors the\n * original deadline instead of starting a new one. A trampoline lineage is one\n * run, so its rounds share one deadline: the round that hands off stamps the\n * lineage's start and bound on the {@link module:Result.Handoff}, and the next\n * round runs under that stamp rather than starting a clock of its own. Like\n * `maxRounds`, the bound belongs to the lineage originator; a handoff target\n * cannot reset or replace it.\n *\n * The engine applies {@link bound} to every execution of a flow that declares\n * `Flow.make(tag, { deadline })`. A control plane applies it inside a run body\n * to bound a run by an approved envelope's deadline. Both settle an expired\n * run with the same {@link module:DeadlineExceeded.DeadlineExceeded} defect.\n *\n * @since 1.0.0\n */\n\nimport * as Clock from \"effect/Clock\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableClock from \"./DurableClock.ts\"\nimport { DeadlineExceeded } from \"./Flow/DeadlineExceeded.ts\"\nimport { Handoff, type LineageDeadline } from \"./Flow/Result.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\n/**\n * The execution's first start, journaled once.\n *\n * A sealed action's result is recorded with its attempt and replayed on every\n * later drive, so the origin a deadline counts from is the time the execution\n * first ran, on this engine or on the one that resumes it after a restart.\n */\nconst origin = Action.make({\n name: \"@smthrs/engine/deadline-origin\",\n tier: \"sealed\",\n success: Schema.Number,\n execute: Clock.currentTimeMillis.pipe(Effect.map(Math.floor))\n})\n\n/**\n * Starts the current execution's deadline: the lineage deadline this round\n * inherited from a handoff, or `deadline` counted from the execution's\n * journaled first start, or from `startedAtMs` when the host supplies a\n * durable start of its own. Answers `undefined` when neither applies, which is\n * an unbounded execution.\n *\n * **Details**\n *\n * The first start is a sealed action, so every later drive of the execution,\n * on this engine or one that resumes it after a restart, reads the same\n * origin. A durable clock is armed at the deadline so a parked execution is\n * driven again when it passes; the clock keeps the due time it was first armed\n * with, so arming it on every drive is idempotent.\n *\n * **Gotchas**\n *\n * Start at most one deadline per execution, before any other dispatch that a\n * replay must line up with: the origin and the clock are addressed by fixed\n * names within the execution.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const start = (options: {\n /** The flow the refusal names. */\n readonly flowName: string\n /** The bound; a positive finite duration. Absent means unbounded. */\n readonly deadline?: Duration.Input | undefined\n /**\n * Where the bound counts from, when the host already holds a durable\n * start of its own, such as the time a control plane accepted the run.\n * Absent, the execution's first start is journaled and read back.\n */\n readonly startedAtMs?: number | undefined\n}): Effect.Effect<LineageDeadline | undefined, never, FlowRuntime | FlowInstance | Crypto.Crypto> =>\n Effect.gen(function*() {\n const instance = yield* FlowInstance\n let lineage = instance.lineageDeadline\n if (lineage === undefined) {\n if (options.deadline === undefined) return undefined\n const deadlineMs = Option.match(Duration.fromInput(options.deadline), {\n onNone: () => Number.NaN,\n onSome: Duration.toMillis\n })\n if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {\n return yield* Effect.die(\n new RangeError(`Deadline.start: \"${options.flowName}\" deadline must be a positive finite duration`)\n )\n }\n lineage = { startedAtMs: options.startedAtMs ?? (yield* origin), deadlineMs }\n }\n const remaining = yield* remainingMs(lineage)\n if (remaining > 0) {\n yield* (yield* FlowRuntime).scheduleClock(instance.flow, {\n executionId: instance.executionId,\n clock: DurableClock.make({ name: \"@smthrs/engine/deadline\", duration: remaining })\n })\n }\n return lineage\n })\n\n/**\n * The whole milliseconds left before `deadline` passes, as the durable clock\n * row stores its due time; zero or less once it has passed.\n *\n * @category getters\n * @since 1.0.0\n */\nexport const remainingMs = (deadline: LineageDeadline): Effect.Effect<number> =>\n Effect.map(Clock.currentTimeMillis, (now) => Math.ceil(deadline.startedAtMs + deadline.deadlineMs - now))\n\n/**\n * Runs `body` within a started deadline.\n *\n * A body that starts at or past the deadline settles at once, and one that\n * starts before it races the time remaining in this fiber, so a running\n * execution is stopped too. Both settle with the same `DeadlineExceeded`\n * defect. The race is `raceFirst`: a body that parks exits first, so parking\n * still parks. A round that hands off stamps the deadline on its handoff, so\n * the next round of the lineage runs under it. An `undefined` deadline runs\n * `body` unbounded.\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const within =\n (deadline: LineageDeadline | undefined, flowName: string) =>\n <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | FlowInstance> =>\n deadline === undefined ? body : Effect.gen(function*() {\n const instance = yield* FlowInstance\n const expired = new DeadlineExceeded({\n flowName,\n executionId: instance.executionId,\n deadlineMs: deadline.deadlineMs,\n startedAtMs: deadline.startedAtMs,\n message: `${flowName} execution ${instance.executionId} ran past its ${deadline.deadlineMs} ms deadline, ` +\n `counted from its start at ${new Date(deadline.startedAtMs).toISOString()}`\n })\n const remaining = yield* remainingMs(deadline)\n if (remaining <= 0) return yield* Effect.die(expired)\n const value = yield* Effect.raceFirst(body, Effect.andThen(Effect.sleep(remaining), Effect.die(expired)))\n const handoff = instance.handoff\n if (handoff !== undefined && handoff.deadline === undefined) {\n instance.handoff = new Handoff({\n flow: handoff.flow,\n payload: handoff.payload,\n ...(handoff.capabilityCeilings === undefined ? {} : { capabilityCeilings: handoff.capabilityCeilings }),\n deadline\n })\n }\n return value\n })\n\n/**\n * Bounds the current execution by `deadline`, counted from its journaled first\n * start, or by the lineage deadline this round inherited from a handoff:\n * {@link start}, then {@link within}.\n *\n * A round that inherited a lineage deadline runs under it whatever it\n * declares, so every round of a lineage expires at the originator's time. With\n * no inherited deadline and `deadline` absent, the body runs unbounded.\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const bound = (options: {\n /** The flow the refusal names. */\n readonly flowName: string\n /** The bound; a positive finite duration. Absent means unbounded. */\n readonly deadline?: Duration.Input | undefined\n /** Where the bound counts from; see {@link start}. */\n readonly startedAtMs?: number | undefined\n}) =>\n<A, E, R>(\n body: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R | FlowRuntime | FlowInstance | Crypto.Crypto> =>\n Effect.flatMap(start(options), (deadline) => within(deadline, options.flowName)(body))\n"]}
1
+ {"version":3,"file":"Deadline.js","sourceRoot":"","sources":["../../src/Deadline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,QAAQ,M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,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IACzG,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAA;IAChC,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5D,QAAQ,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC;YAC7B,IAAI,EAAE,OAAO,CAAC,IAAI;YAClB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,GAAG,CAAC,OAAO,CAAC,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,EAAE,CAAC;YACvG,QAAQ;SACT,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAC,CAAA;AAEN;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,OAOrB,EAAE,EAAE,CACL,CACE,IAA4B,EACyC,EAAE,CACvE,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA","sourcesContent":["/**\n * The wall-clock bound one run of a flow settles by.\n *\n * A deadline counts from the run's FIRST start, which is journaled, so it\n * survives park, resume and process death: a restarted engine honors the\n * original deadline instead of starting a new one. A trampoline lineage is one\n * run, so its rounds share one deadline: the round that hands off stamps the\n * lineage's start and bound on the {@link module:Result.Handoff}, and the next\n * round runs under that stamp rather than starting a clock of its own. Like\n * `maxRounds`, the bound belongs to the lineage originator; a handoff target\n * cannot reset or replace it.\n *\n * The engine applies {@link bound} to every execution of a flow that declares\n * `Flow.make(tag, { deadline })`. A control plane applies it inside a run body\n * to bound a run by an approved envelope's deadline. Both settle an expired\n * run with the same {@link module:DeadlineExceeded.DeadlineExceeded} defect.\n *\n * @since 1.0.0\n */\n\nimport * as Clock from \"effect/Clock\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableClock from \"./DurableClock.ts\"\nimport { DeadlineExceeded } from \"./Flow/DeadlineExceeded.ts\"\nimport { Handoff, type LineageDeadline } from \"./Flow/Result.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\n/**\n * The execution's first start, journaled once.\n *\n * A sealed action's result is recorded with its attempt and replayed on every\n * later drive, so the origin a deadline counts from is the time the execution\n * first ran, on this engine or on the one that resumes it after a restart.\n */\nconst origin = Action.make({\n name: \"@smthrs/engine/deadline-origin\",\n tier: \"sealed\",\n success: Schema.Number,\n execute: Clock.currentTimeMillis.pipe(Effect.map(Math.floor))\n})\n\n/**\n * Starts the current execution's deadline: the lineage deadline this round\n * inherited from a handoff, or `deadline` counted from the execution's\n * journaled first start, or from `startedAtMs` when the host supplies a\n * durable start of its own. Answers `undefined` when neither applies, which is\n * an unbounded execution.\n *\n * **Details**\n *\n * The first start is a sealed action, so every later drive of the execution,\n * on this engine or one that resumes it after a restart, reads the same\n * origin. A durable clock is armed at the deadline so a parked execution is\n * driven again when it passes; the clock keeps the due time it was first armed\n * with, so arming it on every drive is idempotent.\n *\n * **Gotchas**\n *\n * Start at most one deadline per execution, before any other dispatch that a\n * replay must line up with: the origin and the clock are addressed by fixed\n * names within the execution.\n *\n * A deadline that is not a positive finite duration, a `startedAtMs` that is\n * not finite, or a bound that would expire after epoch millisecond\n * `Number.MAX_SAFE_INTEGER` dies with a `RangeError`: a durable store records\n * the clock's due time as a safe integer.\n *\n * @category constructors\n * @since 1.0.0\n */\nexport const start = (options: {\n /** The flow the refusal names. */\n readonly flowName: string\n /** The bound; a positive finite duration. Absent means unbounded. */\n readonly deadline?: Duration.Input | undefined\n /**\n * Where the bound counts from, when the host already holds a durable\n * start of its own, such as the time a control plane accepted the run.\n * Absent, the execution's first start is journaled and read back.\n */\n readonly startedAtMs?: number | undefined\n}): Effect.Effect<LineageDeadline | undefined, never, FlowRuntime | FlowInstance | Crypto.Crypto> =>\n Effect.gen(function*() {\n const instance = yield* FlowInstance\n let lineage = instance.lineageDeadline\n if (lineage === undefined) {\n if (options.deadline === undefined) return undefined\n const deadlineMs = Option.match(Duration.fromInput(options.deadline), {\n onNone: () => Number.NaN,\n onSome: Duration.toMillis\n })\n if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {\n return yield* Effect.die(\n new RangeError(`Deadline.start: \"${options.flowName}\" deadline must be a positive finite duration`)\n )\n }\n const startedAtMs = options.startedAtMs ?? (yield* origin)\n // The clock armed below is due at `startedAtMs + deadlineMs`, and a\n // durable store records a due time as a safe integer.\n if (!Number.isFinite(startedAtMs) || startedAtMs + deadlineMs > Number.MAX_SAFE_INTEGER) {\n return yield* Effect.die(\n new RangeError(\n `Deadline.start: \"${options.flowName}\" deadline must expire by epoch millisecond ` +\n `${Number.MAX_SAFE_INTEGER}, and a ${deadlineMs} ms deadline from ${startedAtMs} does not`\n )\n )\n }\n lineage = { startedAtMs, deadlineMs }\n }\n const remaining = yield* remainingMs(lineage)\n if (remaining > 0) {\n yield* (yield* FlowRuntime).scheduleClock(instance.flow, {\n executionId: instance.executionId,\n clock: DurableClock.make({ name: \"@smthrs/engine/deadline\", duration: remaining })\n })\n }\n return lineage\n })\n\n/**\n * The whole milliseconds left before `deadline` passes, as the durable clock\n * row stores its due time; zero or less once it has passed.\n *\n * @category getters\n * @since 1.0.0\n */\nexport const remainingMs = (deadline: LineageDeadline): Effect.Effect<number> =>\n Effect.map(Clock.currentTimeMillis, (now) => Math.ceil(deadline.startedAtMs + deadline.deadlineMs - now))\n\n/**\n * Runs `body` within a started deadline.\n *\n * A body that starts at or past the deadline settles at once, and one that\n * starts before it races the time remaining in this fiber, so a running\n * execution is stopped too. Both settle with the same `DeadlineExceeded`\n * defect. The race is `raceFirst`: a body that parks exits first, so parking\n * still parks. A round that hands off stamps the deadline on its handoff, so\n * the next round of the lineage runs under it. An `undefined` deadline runs\n * `body` unbounded.\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const within =\n (deadline: LineageDeadline | undefined, flowName: string) =>\n <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R | FlowInstance> =>\n deadline === undefined ? body : Effect.gen(function*() {\n const instance = yield* FlowInstance\n const expired = new DeadlineExceeded({\n flowName,\n executionId: instance.executionId,\n deadlineMs: deadline.deadlineMs,\n startedAtMs: deadline.startedAtMs,\n message: `${flowName} execution ${instance.executionId} ran past its ${deadline.deadlineMs} ms deadline, ` +\n `counted from its start at ${new Date(deadline.startedAtMs).toISOString()}`\n })\n const remaining = yield* remainingMs(deadline)\n if (remaining <= 0) return yield* Effect.die(expired)\n const value = yield* Effect.raceFirst(body, Effect.andThen(Effect.sleep(remaining), Effect.die(expired)))\n const handoff = instance.handoff\n if (handoff !== undefined && handoff.deadline === undefined) {\n instance.handoff = new Handoff({\n flow: handoff.flow,\n payload: handoff.payload,\n ...(handoff.capabilityCeilings === undefined ? {} : { capabilityCeilings: handoff.capabilityCeilings }),\n deadline\n })\n }\n return value\n })\n\n/**\n * Bounds the current execution by `deadline`, counted from its journaled first\n * start, or by the lineage deadline this round inherited from a handoff:\n * {@link start}, then {@link within}.\n *\n * A round that inherited a lineage deadline runs under it whatever it\n * declares, so every round of a lineage expires at the originator's time. With\n * no inherited deadline and `deadline` absent, the body runs unbounded.\n *\n * @category combinators\n * @since 1.0.0\n */\nexport const bound = (options: {\n /** The flow the refusal names. */\n readonly flowName: string\n /** The bound; a positive finite duration. Absent means unbounded. */\n readonly deadline?: Duration.Input | undefined\n /** Where the bound counts from; see {@link start}. */\n readonly startedAtMs?: number | undefined\n}) =>\n<A, E, R>(\n body: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R | FlowRuntime | FlowInstance | Crypto.Crypto> =>\n Effect.flatMap(start(options), (deadline) => within(deadline, options.flowName)(body))\n"]}
@@ -1,13 +1,3 @@
1
- /**
2
- * Durable timers for flow sleeps.
3
- *
4
- * `make` creates a `DurableClock` with a name, duration, and deferred wake-up
5
- * signal. `sleep` ignores zero durations, runs short sleeps through an
6
- * in-memory action, and schedules longer sleeps through the `FlowRuntime`
7
- * before awaiting the durable deferred tied to the clock.
8
- *
9
- * @since 0.1.0
10
- */
11
1
  import type * as Crypto from "effect/Crypto";
12
2
  import * as Duration from "effect/Duration";
13
3
  import * as Effect from "effect/Effect";
@@ -32,6 +22,10 @@ export interface DurableClock {
32
22
  /**
33
23
  * Declares one durable clock after validating its finite nonnegative duration.
34
24
  *
25
+ * Throws a `RangeError` for a malformed, infinite or negative duration, or one
26
+ * longer than `Number.MAX_SAFE_INTEGER` milliseconds: a durable store records
27
+ * a clock's due time as a safe integer.
28
+ *
35
29
  * @category constructors
36
30
  * @since 0.1.0
37
31
  */
@@ -43,6 +37,11 @@ export declare const make: (options: {
43
37
  * Waits inside a flow, using an in-memory action for durations at or
44
38
  * below the threshold and scheduling a durable clock for longer durations.
45
39
  *
40
+ * Throws a `RangeError` for the same durations {@link make} refuses, and for
41
+ * a malformed, infinite or negative threshold. A durable sleep that would
42
+ * wake after epoch millisecond `Number.MAX_SAFE_INTEGER` dies with a
43
+ * `RangeError` instead of arming its clock.
44
+ *
46
45
  * @category sleeping
47
46
  * @since 0.1.0
48
47
  */
@@ -1 +1 @@
1
- {"version":3,"file":"DurableClock.d.ts","sourceRoot":"","sources":["../../src/DurableClock.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,OAAO,KAAK,KAAK,MAAM,MAAM,eAAe,CAAA;AAC5C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAA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 2026-08-10.
2
+ /**
3
+ * Durable timers for flow sleeps.
4
+ *
5
+ * `make` creates a `DurableClock` with a name, duration, and deferred wake-up
6
+ * signal. `sleep` ignores zero durations, runs short sleeps through an
7
+ * in-memory action, and schedules longer sleeps through the `FlowRuntime`
8
+ * before awaiting the durable deferred tied to the clock.
9
+ *
10
+ * @since 0.1.0
11
+ */
12
+ import * as Clock from "effect/Clock";
2
13
  import * as Duration from "effect/Duration";
3
14
  import * as Effect from "effect/Effect";
4
15
  import * as Option from "effect/Option";
@@ -25,6 +36,26 @@ const durationFromInput = (input, field) => {
25
36
  }
26
37
  return parsed.value;
27
38
  };
39
+ /**
40
+ * The latest due time a durable timer records, in epoch milliseconds: a store
41
+ * keeps a clock's due time as a safe integer.
42
+ *
43
+ * @private
44
+ */
45
+ const latestDueAtMs = Number.MAX_SAFE_INTEGER;
46
+ /**
47
+ * Parses a clock's own duration, which a store adds to the current time and
48
+ * records, so it is at most {@link latestDueAtMs} milliseconds.
49
+ *
50
+ * @private
51
+ */
52
+ const clockDuration = (input) => {
53
+ const duration = durationFromInput(input, "duration");
54
+ if (Duration.toMillis(duration) > latestDueAtMs) {
55
+ throw new RangeError(`DurableClock: "duration" must be at most ${latestDueAtMs} milliseconds.`);
56
+ }
57
+ return duration;
58
+ };
28
59
  const makeClock = (name, duration) => ({
29
60
  [TypeId]: TypeId,
30
61
  name,
@@ -34,20 +65,29 @@ const makeClock = (name, duration) => ({
34
65
  /**
35
66
  * Declares one durable clock after validating its finite nonnegative duration.
36
67
  *
68
+ * Throws a `RangeError` for a malformed, infinite or negative duration, or one
69
+ * longer than `Number.MAX_SAFE_INTEGER` milliseconds: a durable store records
70
+ * a clock's due time as a safe integer.
71
+ *
37
72
  * @category constructors
38
73
  * @since 0.1.0
39
74
  */
40
- export const make = (options) => makeClock(options.name, durationFromInput(options.duration, "duration"));
75
+ export const make = (options) => makeClock(options.name, clockDuration(options.duration));
41
76
  /**
42
77
  * Waits inside a flow, using an in-memory action for durations at or
43
78
  * below the threshold and scheduling a durable clock for longer durations.
44
79
  *
80
+ * Throws a `RangeError` for the same durations {@link make} refuses, and for
81
+ * a malformed, infinite or negative threshold. A durable sleep that would
82
+ * wake after epoch millisecond `Number.MAX_SAFE_INTEGER` dies with a
83
+ * `RangeError` instead of arming its clock.
84
+ *
45
85
  * @category sleeping
46
86
  * @since 0.1.0
47
87
  */
48
88
  export const sleep = (options) => {
49
89
  const name = options.name;
50
- const duration = durationFromInput(options.duration, "duration");
90
+ const duration = clockDuration(options.duration);
51
91
  const inMemoryThreshold = durationFromInput(options.inMemoryThreshold ?? defaultInMemoryThreshold, "inMemoryThreshold");
52
92
  // Untraced because durable sleeps are recursively resumed by the engine.
53
93
  return Effect.fnUntraced(function* () {
@@ -61,6 +101,13 @@ export const sleep = (options) => {
61
101
  execute: Effect.sleep(duration)
62
102
  });
63
103
  }
104
+ // A due time past the latest one a store records would fail the park
105
+ // write deep in the engine, so the sleep refuses it here by name.
106
+ const now = yield* Clock.currentTimeMillis;
107
+ if (now + Duration.toMillis(duration) > latestDueAtMs) {
108
+ return yield* Effect.die(new RangeError(`DurableClock: "${name}" would wake after epoch millisecond ${latestDueAtMs}, ` +
109
+ `the latest due time a durable timer records.`));
110
+ }
64
111
  const engine = yield* FlowRuntime;
65
112
  const instance = yield* FlowInstance;
66
113
  const clock = makeClock(name, duration);
@@ -1 +1 @@
1
- {"version":3,"file":"DurableClock.js","sourceRoot":"","sources":["../../src/DurableClock.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAcvD,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAA;AAC3C,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE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\n * `make` creates a `DurableClock` with a name, duration, and deferred wake-up\n * signal. `sleep` ignores zero durations, runs short sleeps through an\n * in-memory action, and schedules longer sleeps through the `FlowRuntime`\n * before awaiting the durable deferred tied to the clock.\n *\n * @since 0.1.0\n */\n\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport type * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\nconst TypeId = \"@smthrs/flow/DurableClock\"\n\n/**\n * Represents a durable flow timer with a name, duration, and deferred\n * completed when the timer wakes.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableClock {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly duration: Duration.Duration\n readonly deferred: DurableDeferred.DurableDeferred<typeof Schema.Void>\n}\n\n/**\n * Parses one author-supplied duration and requires it to be finite and\n * nonnegative. Invalid input throws `RangeError` so the authoring mistake is\n * caught at declaration time, matching `Flow.make` and `Poll.make`.\n *\n * @private\n */\nconst durationFromInput = (input: Duration.Input, field: string): Duration.Duration => {\n const parsed = Duration.fromInput(input)\n if (Option.isNone(parsed)) {\n throw new RangeError(`DurableClock: \"${field}\" must be a valid finite duration that is not negative.`)\n }\n const millis = Duration.toMillis(parsed.value)\n if (!Duration.isFinite(parsed.value) || !Number.isFinite(millis) || millis < 0) {\n throw new RangeError(`DurableClock: \"${field}\" must be a valid finite duration that is not negative.`)\n }\n return parsed.value\n}\n\nconst makeClock = (name: string, duration: Duration.Duration): DurableClock => ({\n [TypeId]: TypeId,\n name,\n duration,\n deferred: DurableDeferred.make(`DurableClock/${name}`)\n})\n\n/**\n * Declares one durable clock after validating its finite nonnegative duration.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (options: {\n readonly name: string\n readonly duration: Duration.Input\n}): DurableClock => makeClock(options.name, durationFromInput(options.duration, \"duration\"))\n\n/**\n * Waits inside a flow, using an in-memory action for durations at or\n * below the threshold and scheduling a durable clock for longer durations.\n *\n * @category sleeping\n * @since 0.1.0\n */\nexport const sleep = (\n options: {\n readonly name: string\n readonly duration: Duration.Input\n /**\n * If the duration is less than or equal to this threshold, the clock will\n * be executed in memory.\n *\n * @default 60 seconds\n */\n readonly inMemoryThreshold?: Duration.Input | undefined\n }\n): Effect.Effect<\n void,\n never,\n Crypto.Crypto | FlowRuntime | FlowInstance\n> => {\n const name = options.name\n const duration = durationFromInput(options.duration, \"duration\")\n const inMemoryThreshold = durationFromInput(\n options.inMemoryThreshold ?? defaultInMemoryThreshold,\n \"inMemoryThreshold\"\n )\n\n // Untraced because durable sleeps are recursively resumed by the engine.\n return Effect.fnUntraced(function*() {\n if (Duration.isZero(duration)) {\n return\n }\n\n if (Duration.isLessThanOrEqualTo(duration, inMemoryThreshold)) {\n return yield* Action.make({\n name: `DurableClock/${name}`,\n tier: \"sealed\",\n execute: Effect.sleep(duration)\n })\n }\n\n const engine = yield* FlowRuntime\n const instance = yield* FlowInstance\n const clock = makeClock(name, duration)\n yield* engine.scheduleClock(instance.flow, {\n executionId: instance.executionId,\n clock\n })\n return yield* DurableDeferred.await(clock.deferred)\n })()\n}\n\nconst defaultInMemoryThreshold = Duration.seconds(60)\n"]}
1
+ {"version":3,"file":"DurableClock.js","sourceRoot":"","sources":["../../src/DurableClock.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;GASG;AAEH,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAA;AAC3C,OAAO,KAAK,e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AAG,GAAG,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,aAAa,EAAE,CAAC;YACtD,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CACtB,IAAI,UAAU,CACZ,kBAAkB,IAAI,wCAAwC,aAAa,IAAI;gBAC7E,8CAA8C,CACjD,CACF,CAAA;QACH,CAAC;QACD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,WAAW,CAAA;QACjC,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,YAAY,CAAA;QACpC,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;QACvC,KAAK,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,EAAE;YACzC,WAAW,EAAE,QAAQ,CAAC,WAAW;YACjC,KAAK;SACN,CAAC,CAAA;QACF,OAAO,KAAK,CAAC,CAAC,eAAe,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IACrD,CAAC,CAAC,EAAE,CAAA;AACN,CAAC,CAAA;AAED,MAAM,wBAAwB,GAAG,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Durable timers for flow sleeps.\n *\n * `make` creates a `DurableClock` with a name, duration, and deferred wake-up\n * signal. `sleep` ignores zero durations, runs short sleeps through an\n * in-memory action, and schedules longer sleeps through the `FlowRuntime`\n * before awaiting the durable deferred tied to the clock.\n *\n * @since 0.1.0\n */\n\nimport * as Clock from \"effect/Clock\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport type * as Schema from \"effect/Schema\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\nconst TypeId = \"@smthrs/flow/DurableClock\"\n\n/**\n * Represents a durable flow timer with a name, duration, and deferred\n * completed when the timer wakes.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableClock {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly duration: Duration.Duration\n readonly deferred: DurableDeferred.DurableDeferred<typeof Schema.Void>\n}\n\n/**\n * Parses one author-supplied duration and requires it to be finite and\n * nonnegative. Invalid input throws `RangeError` so the authoring mistake is\n * caught at declaration time, matching `Flow.make` and `Poll.make`.\n *\n * @private\n */\nconst durationFromInput = (input: Duration.Input, field: string): Duration.Duration => {\n const parsed = Duration.fromInput(input)\n if (Option.isNone(parsed)) {\n throw new RangeError(`DurableClock: \"${field}\" must be a valid finite duration that is not negative.`)\n }\n const millis = Duration.toMillis(parsed.value)\n if (!Duration.isFinite(parsed.value) || !Number.isFinite(millis) || millis < 0) {\n throw new RangeError(`DurableClock: \"${field}\" must be a valid finite duration that is not negative.`)\n }\n return parsed.value\n}\n\n/**\n * The latest due time a durable timer records, in epoch milliseconds: a store\n * keeps a clock's due time as a safe integer.\n *\n * @private\n */\nconst latestDueAtMs = Number.MAX_SAFE_INTEGER\n\n/**\n * Parses a clock's own duration, which a store adds to the current time and\n * records, so it is at most {@link latestDueAtMs} milliseconds.\n *\n * @private\n */\nconst clockDuration = (input: Duration.Input): Duration.Duration => {\n const duration = durationFromInput(input, \"duration\")\n if (Duration.toMillis(duration) > latestDueAtMs) {\n throw new RangeError(`DurableClock: \"duration\" must be at most ${latestDueAtMs} milliseconds.`)\n }\n return duration\n}\n\nconst makeClock = (name: string, duration: Duration.Duration): DurableClock => ({\n [TypeId]: TypeId,\n name,\n duration,\n deferred: DurableDeferred.make(`DurableClock/${name}`)\n})\n\n/**\n * Declares one durable clock after validating its finite nonnegative duration.\n *\n * Throws a `RangeError` for a malformed, infinite or negative duration, or one\n * longer than `Number.MAX_SAFE_INTEGER` milliseconds: a durable store records\n * a clock's due time as a safe integer.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = (options: {\n readonly name: string\n readonly duration: Duration.Input\n}): DurableClock => makeClock(options.name, clockDuration(options.duration))\n\n/**\n * Waits inside a flow, using an in-memory action for durations at or\n * below the threshold and scheduling a durable clock for longer durations.\n *\n * Throws a `RangeError` for the same durations {@link make} refuses, and for\n * a malformed, infinite or negative threshold. A durable sleep that would\n * wake after epoch millisecond `Number.MAX_SAFE_INTEGER` dies with a\n * `RangeError` instead of arming its clock.\n *\n * @category sleeping\n * @since 0.1.0\n */\nexport const sleep = (\n options: {\n readonly name: string\n readonly duration: Duration.Input\n /**\n * If the duration is less than or equal to this threshold, the clock will\n * be executed in memory.\n *\n * @default 60 seconds\n */\n readonly inMemoryThreshold?: Duration.Input | undefined\n }\n): Effect.Effect<\n void,\n never,\n Crypto.Crypto | FlowRuntime | FlowInstance\n> => {\n const name = options.name\n const duration = clockDuration(options.duration)\n const inMemoryThreshold = durationFromInput(\n options.inMemoryThreshold ?? defaultInMemoryThreshold,\n \"inMemoryThreshold\"\n )\n\n // Untraced because durable sleeps are recursively resumed by the engine.\n return Effect.fnUntraced(function*() {\n if (Duration.isZero(duration)) {\n return\n }\n\n if (Duration.isLessThanOrEqualTo(duration, inMemoryThreshold)) {\n return yield* Action.make({\n name: `DurableClock/${name}`,\n tier: \"sealed\",\n execute: Effect.sleep(duration)\n })\n }\n\n // A due time past the latest one a store records would fail the park\n // write deep in the engine, so the sleep refuses it here by name.\n const now = yield* Clock.currentTimeMillis\n if (now + Duration.toMillis(duration) > latestDueAtMs) {\n return yield* Effect.die(\n new RangeError(\n `DurableClock: \"${name}\" would wake after epoch millisecond ${latestDueAtMs}, ` +\n `the latest due time a durable timer records.`\n )\n )\n }\n const engine = yield* FlowRuntime\n const instance = yield* FlowInstance\n const clock = makeClock(name, duration)\n yield* engine.scheduleClock(instance.flow, {\n executionId: instance.executionId,\n clock\n })\n return yield* DurableDeferred.await(clock.deferred)\n })()\n}\n\nconst defaultInMemoryThreshold = Duration.seconds(60)\n"]}
@@ -78,7 +78,8 @@ interface MakeOptions<Payload extends Schema.Struct.Fields | AnyStructSchema, Su
78
78
  readonly maxRounds?: number | undefined;
79
79
  /**
80
80
  * How long one execution may take, counted from its journaled first start.
81
- * A positive finite duration; see {@link Flow.deadline}.
81
+ * A positive finite duration of at most `Number.MAX_SAFE_INTEGER`
82
+ * milliseconds; see {@link Flow.deadline}.
82
83
  */
83
84
  readonly deadline?: Duration.Input | undefined;
84
85
  readonly annotations?: Context.Context<never>;
@@ -1 +1 @@
1
- {"version":3,"file":"make.d.ts","sourceRoot":"","sources":["../../../src/Flow/make.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,KAAK,KAAK,OAAO,MAAM,sBAAsB,CAAA;AACpD,OAAO,KAAK,IAAI,MAAM,mBAAmB,CAAA;AACzC,OAAO,KAAK,KAAK,OAAO,MAAM,gBAAgB,CAAA;AAC9C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAG3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAKvC,OAAO,KAAK,KAAK,WAAW,MAAM,mBAAmB,CAAA;AACrD,OAAO,KAAK,EAAE,GAAG,EAAE,eAAe,EAAE,WAAW,EAAE,mBAAmB,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAIzG;;;;GAIG;AACH,UAAU,WAAW,CACnB,OAAO,SAAS,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,eAAe,EACtD,OAAO,SAAS,MAAM,CAAC,GAAG,EAC1B,KAAK,SAAS,MAAM,CAAC,GAAG,CACxB,SAAQ,mBAAmB;IAC3B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;IACzB;;;;OAIG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC1C;;OAEG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA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AE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAA;IAChE,CACE,KAAK,CAAC,GAAG,SAAS,MAAM,EACxB,OAAO,SAAS,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,eAAe,EACtD,OAAO,SAAS,MAAM,CAAC,GAAG,GAAG,MAAM,CAAC,IAAI,EACxC,KAAK,SAAS,MAAM,CAAC,GAAG,GAAG,MAAM,CAAC,KAAK,EAEvC,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,GAAG;QAC9C,QAAQ,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,MAAM,CAAA;QACtE,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,CAAA;QACrB,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KACpD,GACA,UAAU,CAAC,GAAG,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;CAsG7D,CAAA"}
@@ -56,6 +56,11 @@ export const make = (tag, options) => {
56
56
  (deadline === undefined || !Duration.isFinite(deadline) || Duration.toMillis(deadline) <= 0)) {
57
57
  throw new RangeError(`Flow.make: "${tag}" deadline must be a positive finite duration`);
58
58
  }
59
+ // The durable clock that enforces a deadline is due at its start plus the
60
+ // deadline, and a store records that due time as a safe integer.
61
+ if (deadline !== undefined && Duration.toMillis(deadline) > Number.MAX_SAFE_INTEGER) {
62
+ throw new RangeError(`Flow.make: "${tag}" deadline must be at most ${Number.MAX_SAFE_INTEGER} ms`);
63
+ }
59
64
  // Captured here, where the stack still names the author's file, and carried
60
65
  // as a non-enumerable property so no digest can see it
61
66
  // (`internal/DeclarationSite.ts`).