diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index 0dc60611..44e05a65 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -29,7 +29,7 @@ Hosts: the commands below are POSIX shell for Linux and macOS. On Windows, run ` | V3 | Dry-run goldens through the engine and the public CLI | `bun run golden:dryrun` | A line `golden-dryrun: OK ( case(s))` and exit 0 | | V4 | Removed sync target and flag | `./docks-kit sync omp --dry-run; echo "exit $?"; ./docks-kit sync --dry-run --prune; echo "exit $?"` | First the sync help on stdout, then `ERROR` and `Unexpected positional argument: "omp"` on stderr, and `exit 1`. Then `unknown flag --prune for 'sync'` and `exit 2`. Observed 2026-11-19 on Linux x64: exactly these lines | | V5 | Trigger rules on a large tool call, in the real omp | `bun .agents/skills/verify/scripts/ttsr-snippet.ts big-reset \| omp ttsr test --rule SoT/.omp/plugin/rules/git-safety.md --source tool --tool eval --file -`, then the same command with `big-quiet` | For `big-reset`, `Triggered (1)` and a `git-safety` line within a few seconds. For `big-quiet`, `No rules triggered. (evaluated 1)`. The `big-reset` snippet is a 21 KB eval cell with many `\"` escapes that ends with `sh("git reset --hard HEAD")`. The rules of 0.22.29 stayed quiet on it after 4.7 s: JavaScriptCore stopped at its match limit and reported no match, so the rule failed open | -| V6 | Kit plugin in the real omp, isolated | `bun .agents/skills/verify/scripts/omp-smoke.ts; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts hooks; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts talk; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts talk-ui; echo "exit $?"` | The load mode prints `docks-kit-omp -> /SoT/.omp/plugin`; `skills: 34`; `skill names:` with the name of each skill, which are the names of `REQUIRED_SKILLS` in `omp-smoke.ts` and of the skill folders under `SoT/.omp/plugin/skills/`, `talk` among them; `agents: code-reviewer,plan-reviewer`; `extensions:` with the entries of the manifest, `./extensions/talk.js` among them; `talk tool: offered`; `warnings: 0`; `ok registry: talk registered only in the private folder`; `ok registry-removed`; and `exit 0`. The `hooks` mode prints the `ok` lines of the expected output in the V6 section below and `exit 0`. The `talk` mode prints the `ok` lines of the expected output in the V6 `talk` section below, `handover-refused` among them, and `exit 0`. The `talk-ui` mode prints the `ok` lines of the expected output in the V6 `talk-ui` section below, `ui-tool-handover` and `ui-tool-handover-cancel` among them, and `exit 0`. Observed 2026-11-27 on Linux x64 with omp 19.2.1 and the default omp settings in the load mode: exactly these lines; the load mode took 1.7 s, the `hooks` mode 5.8 s, the `talk` mode 4.5 s, and the `talk-ui` mode 7.3 s, each with `nice -n 19` | +| V6 | Kit plugin in real, isolated omp sessions | `bun .agents/skills/verify/scripts/omp-smoke.ts`, then repeat with `hooks`, `talk` and `talk-ui` | All four modes exit zero. Load reports the linked kit plugin, the exact shipped skills, both review agents and the `talk` tool on the prompted request, no warnings, private registration and cleanup. The sections below list the expected output for each mode. | ## V6 — Kit plugin smoke in an isolated omp state @@ -50,7 +50,23 @@ Each mode loads the shipped `talk` extension (`extensions/talk.js`), so each mod - The final scan: immediately before the smoke ends an omp process that it checked, while the process is still live, a scan child reads the default folder once more for the registrations of that process. It fails with the diagnostic that names the default folder, after ` before it ended:`, when the folder holds an entry with the process id and the work folder of a registration of that process (the session ids of a session change included). Thus a copy that a session writes to the default folder after its first check passed still fails the run. Each process gets its own final scan, and the `registry` line keeps the problem of each scan. The script tracks each omp process that runs talk at its spawn, with its process id and folder, before it waits for the process to become ready. In the load mode and the `hooks` mode, the fake model holds the text answer that ends each `omp -p` session until its final scan ends. A session that reaches the command timeout of 120 s without that answer gets the same final scan before the script kills it. A session that is still live at the command timeout after its final scan ended gets a fresh bounded scan before the kill, and the `registry` line keeps the problems of all its scans. In the `talk` mode, the peer scan runs before the peer stdin ends in `closed-peer-not-live`, and the sender scan before the sender gets its last turn at the end of the mode. In the `talk-ui` mode, the TUI scan runs before `ctrl+d`, and the peer scan after the TUI omp exits and before the peer stdin ends. A TUI omp whose footer never shows and an RPC peer that never sends its ready line get their final scan before the cleanup ends them. With an omp before 19.2.0, talk is off, and the TUI omp has no final scan. After a failed step, the scans run before the cleanup ends each process. The final scan has the same deadline of 10 s and the same child, and its diagnostics start with `the final scan of the default talk registry folder`. 4. The line `registry` reports the check of all sessions of the mode: `ok registry: talk registered only in the private folder`. The last line, `registry-removed`, checks after the cleanup that the private folder does not exist. -The load mode writes no `config.yml`, so omp runs with its default settings. talk registers its tool with `loadMode: "essential"`, so omp gives `talk` to the model as a top-level tool and does not mount it as a Bash command. The mode reads `omp skill list --json` and the requests of one `omp -p` session. It prints the names of the skills whose file is inside the linked plugin folder. It fails unless they are the names of the skill folders under `SoT/.omp/plugin/skills/`, and also exactly the names of `REQUIRED_SKILLS` in `omp-smoke.ts`: the 32 docks and plan-lifecycle skills, `workspace-hygiene`, and `talk`. The fixed list does not come from the checkout, so a deleted skill folder, or a skill folder that replaces another, fails the mode. A change that adds, removes, or renames a skill on purpose updates the list. It lists the plugin agents that the task tool offers. It prints the `omp.extensions` list of the linked `package.json`, and fails when the list has no `./extensions/talk.js` entry or the plugin has no `extensions/talk.js`. It fails when the first model request does not offer the `talk` tool. The `hooks` mode makes a scratch git repository with its own git config. The repository holds a root `AGENTS.md`, a root `README.md`, `notes.txt`, and the nested node `scripts/AGENTS.md` with `scripts/ci.mjs`. The fake model plays scripted tool calls in `omp -p --mode json` sessions, and the script reads the JSON event stream, the requests that the fake model receives, `git log`, and the `verify-gate.jsonl` log of each session. Each session has its own `XDG_STATE_HOME` in the scratch folder. The `hooks` mode writes no `config.yml`. Expected output of the `hooks` mode, in order: +The load mode writes no `config.yml`. It compares `omp skill list --json` with the linked plugin folders and the fixed `REQUIRED_SKILLS` list. Update that list only when adding, removing or renaming a skill on purpose. It checks the manifest for `./extensions/talk.js` and checks that the file exists. It checks both the task tool's agent list and the top-level `talk` tool on the first request for the fixture prompt. An earlier auxiliary request or a later request cannot supply either advertisement. Talk uses `loadMode: "essential"` so omp does not mount it as a Bash command. + +Expected load output (`` is the source checkout selected by the script or `--repo`; runtime state is private): + +```text +docks-kit-omp -> /SoT/.omp/plugin +skills: 34 +skill names: accessibility,agent-first-setup,ci-speed,claude-md-migration,code-clarity,code-guardrails,code-review,code-reviewer,commit-discipline,context-tree,dep-vuln-workflow,design-tokenization,effect-ts,fix-workflow,lint-no-suppressions,make-interfaces-feel-better,plan-manager,plan-reviewer,plan-workspace,react-component-patterns,refactor,report-skill-issue,security,skill-agent-pipeline,skill-maintenance,solid,talk,tdd-workflow,test-coverage,type-safety-discipline,workspace-hygiene,write-skill,yolo,zoom-out +agents: code-reviewer,plan-reviewer +extensions: ./extensions/hygiene.ts,./extensions/verify-gate.ts,./extensions/context-tree-nudge.ts,./extensions/talk.js +talk tool: offered +warnings: 0 +ok registry: talk registered only in the private folder +ok registry-removed +``` + +The `hooks` mode runs scripted `omp -p --mode json` sessions in a scratch Git repository with private Git configuration. Each session has its own `XDG_STATE_HOME`. The driver checks the event stream, provider requests, Git log and each `verify-gate.jsonl` log. Expected output, in order: ```text ok install @@ -69,6 +85,7 @@ ok nudge-failed-edit-none ok nudge-url-write-none ok hygiene-scratch-tool ok hygiene-temp-reminder +ok hygiene-stop-reminder ok extensions-loaded ok sessions ok isolated @@ -92,6 +109,7 @@ exit 0 | `nudge-url-write-none` | `write` to `local://notes.md`; the session folder is inside the `scripts` node | The write succeeds. No added-context message follows. | | `hygiene-scratch-tool` | The requests of a session with one `bash` `mktemp -d` call | A request lists the `scratch_new` tool with `Prefer it over /tmp`. | | `hygiene-temp-reminder` | Same session: the `mktemp -d` result | After the tool result, an added-context message holds the reminder `Prefer a directory from the \`scratch_new\` tool`. | +| `hygiene-stop-reminder` | The same session leaves its temporary directory in place | A new user message at the fixture provider contains the stop reminder and the exact directory. | | `extensions-loaded` | All sessions | omp reported no warning that names the linked plugin folder or `docks-kit-omp`, and no `Failed to load extension` record for a plugin file, `hygiene.ts` included. | | `isolated` | The whole run | The `tidy.stamp` of the scratch home kept its modification time, so no hygiene sweep started. | | `real-state` | The whole run | The real omp registry files kept their modification times. The real `verify-gate.jsonl` has no new line with a `cwd` inside the scratch folder. Lines that other omp sessions add during the run do not count. | @@ -249,10 +267,13 @@ The other lines are as above. talk is off on this omp and registers no session, | V6 prints `skills:` other than 34, a `FAIL skills:` line, or misses an agent | omp did not load a skill or agent file of `SoT/.omp/plugin`, a folder moved, or a skill folder was added, removed, or renamed | Check the folders under `SoT/.omp/plugin/skills/` and `SoT/.omp/plugin/agents/`, and the `name` frontmatter of each `SKILL.md` and agent file. When the change adds, removes, or renames a skill on purpose, update `REQUIRED_SKILLS` in `omp-smoke.ts` and the count in this skill | | V6 prints `FAIL extensions-loaded` or `warnings:` above `0` with `Failed to load extension` | A kit extension throws when omp loads it | Fix the file that the `FAIL` line names in `SoT/.omp/plugin/extensions/` | | V6 prints a `FAIL gate-` or `FAIL nudge-` line | The gate or the nudge acted on the wrong command, path, or node | Check `checkCommand` in `SoT/.omp/plugin/extensions/verify-gate-core.ts` or `nudgeText` in `SoT/.omp/plugin/extensions/context-tree-core.ts`, and their adapters `verify-gate.ts` and `context-tree-nudge.ts` | +| V6 reports `no request from the omp session` or `no opening fixture request` | No request arrived, or none matched the fixture prompt and model | Check the private provider and the exact prompt `Reply with ok.`. These messages say nothing about the installed agents. | +| V6 reports `no task tool with an agent list` | The opening request did not offer a task description with an agent section | Check `# Available Agents` in the `task` description on that request. Only `agents missing from the task tool:` identifies missing names in that section. | +| V6 prints `FAIL hygiene-stop-reminder` | The completed turn did not produce the stop notice for the fixture directory | Check the `session_stop` handler and `stopReminder` in `hygiene.ts`. The fixture must receive the tool reply, the assistant's `ok`, then a new stop notice. A creation notice does not count. | | V6 prints a `FAIL hygiene-` line | The `scratch_new` description or the temporary-file reminder lost its preference for scratch, or the reminder did not run | Check the `scratch_new` description and `SCRATCH_NOTE` in `SoT/.omp/plugin/extensions/hygiene.ts` | | V6 prints a `FAIL` line that names `./extensions/talk.js` or `extensions/talk.js` (a missing file or manifest entry) | The shipped plugin has no `talk.js` bundle or no manifest entry for it | Run `bun cli/scripts/build-talk.ts --check`; when it reports a stale or missing bundle, run `bun cli/scripts/build-talk.ts` and check the `omp.extensions` list of `SoT/.omp/plugin/package.json` | | V6 prints `FAIL install` with another reason, or the load mode prints `FAIL omp exited` | An omp command exited with a status other than 0, omp kept no plugin state, `omp plugin list --json` has no `docks-kit-omp` row, `omp --version` names no version, or the private registry folder has the wrong mode | Read the reason on the `FAIL` line: it names the command, the path, or the output that failed. Check the omp binary (V2) and the scratch folder | -| V6 load mode prints `talk tool: missing` | The first model request with omp's default settings does not offer `talk`: `talk.js` did not load, or omp mounted `talk` as a Bash command | Read the `warnings:` line. Check that the tool registration in `cli/talk/extension.ts` sets `loadMode: "essential"`, then rebuild `talk.js` | +| V6 load mode prints `talk tool: missing` | The fixture prompt did not reach the provider, or its first request did not offer `talk` | If the request is absent, check the model and prompt in the fixture. If it arrived without `talk`, check `loadMode: "essential"` in `cli/talk/extension.ts` and rebuild `talk.js`. | | V6 prints `FAIL registry:` with `no valid entry of process` | No poll that the scan child started before its cutoff, 9 s after the launch of the child, found a valid entry of the session in the private folder: talk did not load, did not register, or did not read `DOCKS_KIT_TALK_DIR`. A poll sees a registration that appears before it lists the folder, so a registration close to the cutoff can still count. With `and the session`, the peer did not publish the new session of `new_session` or `fork` | Read the `extensions-loaded` line and the warnings. Check `cli/talk/transport/folder.ts` and the registration in `cli/talk/extension.ts` | | V6 prints `FAIL registry:` with `did not end within 10 s` | Timeout cancellation: the scan child of a registry check gave no result before the 10 s deadline, so the script killed the child and its process group. A scan stalled, for example because the macOS ACL listing (`ls -led`) or a file system call hung | Run `ls -led` on the folder that the line names and check that it ends at once. Check the folder trust check in `cli/talk/transport/trustPosix.ts` | | V6 prints `FAIL registry:` with `ended early` | The scan child exited with an error code or stopped on a signal before it gave a result; the script read this at the exit of the child and then killed its process group | Run the child by hand to see its error: `bun .agents/skills/verify/scripts/omp-smoke.ts registry-scan ''`. A malformed request exits 2 | diff --git a/.agents/skills/verify/scripts/omp-smoke.ts b/.agents/skills/verify/scripts/omp-smoke.ts index fa6c9002..000cf80a 100755 --- a/.agents/skills/verify/scripts/omp-smoke.ts +++ b/.agents/skills/verify/scripts/omp-smoke.ts @@ -85,14 +85,17 @@ import { isObject, type Json, type JsonObject, + loadVerdict, newUserText, objects, offersTool, PeerModel, + PLAIN_ANSWER, PONG, ScriptedSession, SLOW_PROMPT, STEP_TIMEOUT_MS, + stopContinued, TALK_TOOL, textOf, type ToolCall, @@ -412,13 +415,13 @@ interface Script { * session lasts until the driver has acted on another session. */ respond?: (request: JsonObject) => Promise; - /** When set, each answer waits for it first, so the omp session stays live until a check ends. */ - hold?: Promise; + /** Keep the print session live through attribution and the scan before its final answer. */ + registry?: SessionRegistryChecks; /** - * When set, a text answer waits for it first. A text answer ends an `omp -p` session, so the session stays - * live until the final check ends. + * Set with `turns` when a session answers more than once without a tool call: only a plain or text answer to a + * request that it accepts gets the final scan. Without it, every plain or text answer does. */ - final?: () => Promise; + final?: ((request: JsonObject) => boolean) | undefined; } function sseChunk(model: Json, choice: JsonObject, extra: JsonObject = {}): string { @@ -430,7 +433,7 @@ function sseChunk(model: Json, choice: JsonObject, extra: JsonObject = {}): stri * `script.turns[n]` answers a request that holds n assistant messages, unless `script.respond` is set. */ async function scriptedAnswer(script: Script, request: JsonObject): Promise { - if (script.hold !== undefined) await script.hold; + if (script.registry !== undefined) await script.registry.attribution; let answer: Answer | undefined; if (script.respond !== undefined) answer = await script.respond(request); else { @@ -440,12 +443,13 @@ async function scriptedAnswer(script: Script, request: JsonObject): Promise { const fake = createServer((req, res) => { let body = ""; @@ -468,7 +472,7 @@ function startFakeModel(requests: JsonObject[], script: Script): Promise if (parsed["stream"] === true) { res.writeHead(200, { "content-type": "text/event-stream" }); void scriptedAnswer(script, parsed) - .catch((): Answer => "ok") + .catch((): Answer => PLAIN_ANSWER) .then((answer) => { // Cleanup closes the connection of a turn that still waits. if (res.destroyed) return; @@ -511,7 +515,11 @@ function startFakeModel(requests: JsonObject[], script: Script): Promise created: 0, model, choices: [ - { index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }, + { + index: 0, + message: { role: "assistant", content: PLAIN_ANSWER }, + finish_reason: "stop", + }, ], usage, }), @@ -1165,21 +1173,17 @@ function printSessionRegistry( let checks: SessionRegistryChecks | undefined; return { onSpawn: (pid) => { + if (pid === undefined) return; checks = sessionRegistryChecks({ attribution: sessionAttribution(run, label, pid, cwd), - scanFinal: () => - pid === undefined - ? Promise.resolve("") - : finalLeakProblem(run, [{ label, registration: { processId: pid, cwd } }]), + scanFinal: () => finalLeakProblem(run, [{ label, registration: { processId: pid, cwd } }]), }); - run.script.hold = checks.attribution; - run.script.final = checks.finalAnswer; + run.script.registry = checks; }, beforeTimeoutKill: () => checks?.timeout() ?? Promise.resolve(""), problem: async () => { - run.script.hold = undefined; - run.script.final = undefined; - return checks === undefined ? `${label}: the omp session did not start` : checks.problem(); + run.script.registry = undefined; + return checks === undefined ? `${label}: the omp session did not start` : checks.problem(label); }, }; } @@ -1221,20 +1225,6 @@ function pluginSkillNames(root: string): string[] { .sort(); } -/** Agent names in the "Available Agents" list of the task tool that the model receives. */ -function taskToolAgents(requests: readonly JsonObject[]): string[] | null { - for (const request of requests) { - for (const tool of objects(request["tools"])) { - const fn = isObject(tool["function"]) ? tool["function"] : tool; - if (fn["name"] !== "task") continue; - const description = text(fn["description"]); - if (description !== undefined) - return [...description.matchAll(/^- `([^`]+)`/gm)].map((match) => match[1] ?? ""); - } - } - return null; -} - function stateLogLines(stateDir: string): string[] { const logsDir = join(stateDir, "logs"); if (!existsSync(logsDir)) return []; @@ -1539,23 +1529,18 @@ async function smoke(): Promise<{ lines: string[]; registry: string | null }> { `skills: ${skills.length}, expected the ${required.length} skills of REQUIRED_SKILLS: ${required.join(",")}; update REQUIRED_SKILLS only when a skill was added, removed, or renamed on purpose`, ); - const offered = taskToolAgents(run.requests); - const ownAgents = run.plugin === null ? new Set() : pluginAgentNames(run.plugin.realPath); - const agents = (offered ?? []).filter((agent) => ownAgents.has(agent)).sort(); - lines.push(`agents: ${agents.join(",")}`); - if (run.requests.length === 0) - failures.push("the fake model received no request from the omp session"); - else if (offered === null) failures.push("the model request has no task tool with an agent list"); - const missingAgents = REQUIRED_AGENTS.filter((agent) => !agents.includes(agent)); - if (missingAgents.length > 0) - failures.push(`agents missing from the task tool: ${missingAgents.join(",")}`); - - lines.push(`extensions: ${extensions.join(",")}`); - const firstRequest = run.requests[0]; - const talkOffered = firstRequest !== undefined && offersTool(firstRequest, TALK_TOOL); - lines.push(`talk tool: ${talkOffered ? "offered" : "missing"}`); - if (firstRequest !== undefined && !talkOffered) - failures.push(`the first model request does not offer the ${TALK_TOOL} tool`); + const verdict = loadVerdict(run.requests, { + model: MODEL_ID, + prompt: SESSION_PROMPT, + ownAgents: run.plugin === null ? new Set() : pluginAgentNames(run.plugin.realPath), + requiredAgents: REQUIRED_AGENTS, + }); + lines.push( + `agents: ${verdict.agents.join(",")}`, + `extensions: ${extensions.join(",")}`, + `talk tool: ${verdict.talkOffered ? "offered" : "missing"}`, + ); + failures.push(...verdict.failures); const skillWarnings = Array.isArray(skillList?.["warnings"]) ? skillList["warnings"] : []; const warnings = countWarnings( @@ -1678,6 +1663,8 @@ function logLines(file: string): string[] { interface SessionOptions { readonly turns: readonly Turn[]; + /** The request whose answer ends the session (`Script.final`), when it is not the first plain answer. */ + readonly final?: (request: JsonObject) => boolean; readonly mode?: string; readonly extraArgv?: readonly string[]; } @@ -1738,11 +1725,12 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { const stateRoot = run.isolation.stateHome; const session = async ( name: string, - { turns, mode, extraArgv = [] }: SessionOptions, + { turns, final, mode, extraArgv = [] }: SessionOptions, ): Promise => { const env: Record = { ...gitEnv, XDG_STATE_HOME: join(stateRoot, name) }; if (mode !== undefined) env["DOCKS_VERIFY_GATE"] = mode; run.script.turns = turns; + run.script.final = final; const registry = printSessionRegistry(run, name, repoDir); const result = await run.omp( [ @@ -1763,6 +1751,7 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { }, ); run.script.turns = []; + run.script.final = undefined; const registryProblem = await registry.problem(); if (registryProblem) registryProblems.push(registryProblem); if (result.code !== 0) @@ -1941,8 +1930,22 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { quiet("nudge-url-write-none", "nudge-url", false); // Hygiene: the request lists `scratch_new` as preferred over /tmp, and a `mktemp -d` result gets the reminder. + // The session answers twice without a tool call: `ok` after the directory, and `ok` again after the stop + // reminder. Its final scan runs before the second answer, at the request that continues after the stop hook. + const hygieneStop = { model: MODEL_ID, callId: "hygiene-mktemp" } as const; + const stopsHygiene = (request: JsonObject): boolean => { + const directory = toolResultText(request, hygieneStop.callId)?.trim(); + return ( + directory !== undefined && + isAbsolute(directory) && + stopContinued(request, { ...hygieneStop, directory }) + ); + }; const requestsBefore = run.requests.length; - const hygiene = await session("hygiene", { turns: [bash("hygiene-mktemp", "mktemp -d")] }); + const hygiene = await session("hygiene", { + turns: [bash(hygieneStop.callId, "mktemp -d")], + final: stopsHygiene, + }); // omp lists an extension tool such as `scratch_new` in the system prompt as "- `` — ". const scratchLine = run.requests .slice(requestsBefore) @@ -1958,7 +1961,7 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { ? null : `the scratch_new line lacks '${SCRATCH_TOOL_TEXT}': ${short(scratchLine)}`, ); - const temp = callOutcome(hygiene.messages, "hygiene-mktemp"); + const temp = callOutcome(hygiene.messages, hygieneStop.callId); if (!temp) check("hygiene-temp-reminder", "no tool result in the event stream"); else check( @@ -1967,6 +1970,17 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { ? null : `no added-context message with '${SCRATCH_REMINDER_TEXT}' after the tool result`, ); + const directory = temp?.text.trim(); + check( + "hygiene-stop-reminder", + directory !== undefined && + isAbsolute(directory) && + run.requests.some((request, index) => + index >= requestsBefore && stopContinued(request, { ...hygieneStop, directory }), + ) + ? null + : "no request continued the hygiene session after its plain answer with a new stop reminder that names the fixture directory", + ); const warnings = countWarnings( [], @@ -2017,6 +2031,8 @@ const LIST_RETRY_MS = 250; /** The wait before a check that expects no entry, so that a late append would show. */ const SETTLE_MS = 500; const PEER_CLOSE_MS = 10_000; +/** Allow buffered RPC output to drain after exit, but not an inherited pipe to keep the fixture open. */ +const RPC_OUTPUT_DRAIN_MS = 250; /** The number of session id characters that a `list` line shows. */ const SHORT_ID_LENGTH = 8; @@ -2061,37 +2077,64 @@ interface RpcPeer { readonly pid: number | undefined; /** Sends a command; gives the `data` of a response with `success: true`, and fails on any other response. */ readonly send: (command: JsonObject) => Promise; - /** Ends stdin and waits for the exit; SIGTERM, then SIGKILL, when omp does not exit in time. */ + /** + * Ends stdin and waits for the exit; SIGTERM, then SIGKILL, when omp does not exit in time. A process that + * already exited, or never started, gives its result at once. Repeated calls share the first result. + */ readonly close: () => Promise; } +/** A spawned RPC omp: its handle, and its ready line, which fails when the process ends first or takes too long. */ +interface RpcStart { + readonly peer: RpcPeer; + readonly ready: Promise; +} + /** - * Starts omp in RPC mode and waits for its ready line. `onSpawn` gets the process id at spawn, before the ready - * line, so a mode can scan the registry for the process also when it never becomes ready. + * Starts omp in RPC mode. The handle comes at spawn, apart from the ready line, so a mode records the process + * before it waits: a peer that exits or stalls before its ready line still gets its final scan, its close, and + * its exit result. */ -async function startRpcOmp( +function startRpcOmp( argv: readonly string[], cwd: string, env: Record, - onSpawn: (pid: number | undefined) => void, -): Promise { +): RpcStart { const child = spawn(ompBinary, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"] }); children.add(child); - onSpawn(child.pid); let stderr = ""; let next = 0; + let ended = false; const waiting = new Map>(); const ready = Promise.withResolvers(); - ready.promise.catch(() => undefined); + let drainTimer: NodeJS.Timeout | undefined; const exited = Promise.withResolvers(); + const output = createInterface({ input: child.stdout }); + /** Settle once, after the peer exits and its output drains or the drain deadline expires. */ + const end = (code: number | null, problem: string): void => { + if (ended) return; + ended = true; + clearTimeout(drainTimer); + children.delete(child); + output.close(); + child.stdin.destroy(); + child.stdout.destroy(); + child.stderr.destroy(); + const gone = new Error(`${problem}: ${short(stderr)}`); + for (const reply of waiting.values()) reply.reject(gone); + waiting.clear(); + ready.reject(gone); + exited.resolve(code); + }; child.stdin.on("error", () => undefined); child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString("utf8"); }); child.on("error", (error) => { stderr += String(error); + if (child.pid === undefined) end(null, "the peer omp did not start"); }); - createInterface({ input: child.stdout }).on("line", (line) => { + output.on("line", (line) => { const message = parseJsonText(line); if (!isObject(message)) return; if (message["type"] === "ready") ready.resolve(); @@ -2108,17 +2151,17 @@ async function startRpcOmp( ); else reply.resolve(message["data"] ?? null); }); + child.once("exit", (code) => { + // A descendant can hold stdout or stderr after the peer exits. Keep its + // buffered replies until `close`, but never wait indefinitely for EOF. + drainTimer = setTimeout(() => end(code, `the peer omp exited ${code}`), RPC_OUTPUT_DRAIN_MS); + }); child.on("close", (code) => { - children.delete(child); - const gone = new Error(`the peer omp exited ${code}: ${short(stderr)}`); - for (const reply of waiting.values()) reply.reject(gone); - waiting.clear(); - ready.reject(gone); - exited.resolve(code); + end(code, `the peer omp exited ${code}`); }); - await withTimeout(ready.promise, STEP_TIMEOUT_MS, "the ready line of the peer omp"); const send = (rpcCommand: JsonObject): Promise => { + if (ended) return Promise.reject(new Error("the peer omp has ended")); next += 1; const id = `smoke-${next}`; const reply = Promise.withResolvers(); @@ -2128,8 +2171,8 @@ async function startRpcOmp( }; const exitWithin = (ms: number): Promise => withTimeout(exited.promise, ms, "the exit").catch(() => undefined); - const close = async (): Promise => { - child.stdin.end(); + const stop = async (): Promise => { + if (!ended) child.stdin.end(); let code = await exitWithin(PEER_CLOSE_MS); if (code === undefined) { child.kill("SIGTERM"); @@ -2137,11 +2180,21 @@ async function startRpcOmp( } if (code === undefined) { child.kill("SIGKILL"); - code = await exited.promise; + code = await exitWithin(PEER_CLOSE_MS); + if (code === undefined) { + child.unref(); + end(null, "the peer omp did not exit after SIGKILL"); + return { argv, code: "timeout", stdout: "", stderr }; + } } return { argv, code, stdout: "", stderr }; }; - return { pid: child.pid, send, close }; + let closing: Promise | undefined; + const close = (): Promise => (closing ??= stop()); + return { + peer: { pid: child.pid, send, close }, + ready: withTimeout(ready.promise, STEP_TIMEOUT_MS, "the ready line of the peer omp"), + }; } /** @@ -2359,8 +2412,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> const pass = (): void => { results.set(step, ""); }; - let peer: RpcPeer | null = null; - let peerResult: OmpResult | null = null; + let peer: FixtureProcess = { kind: "absent" }; let senderRun: Promise | null = null; // The registrations that the mode attributed for each omp process, and the problems of the `registry` line. const peerAttributed: Attributed[] = []; @@ -2378,17 +2430,19 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> reportRegistry(); }; try { - // The peer: omp in RPC mode. Its first provider turn answers the driver's prompt. - const rpc = await startRpcOmp( + // The peer: omp in RPC mode. Its first provider turn answers the driver's prompt. The mode holds its handle + // before the ready line, so a peer that ends or stalls first still gets its final scan and its exit result. + const started = startRpcOmp( ["--mode", "rpc", "--model", `${MODEL_PROVIDER}/${PEER_MODEL_ID}`, "--no-title"], run.workDir, run.env, - (pid) => { - if (pid !== undefined) - peerAttributed.push({ label: "peer", registration: { processId: pid, cwd: run.workDir } }); - }, ); - peer = rpc; + const rpc = started.peer; + if (rpc.pid !== undefined) { + peer = { kind: "open", handle: rpc }; + peerAttributed.push({ label: "peer", registration: { processId: rpc.pid, cwd: run.workDir } }); + } + await started.ready; const peerRegistry = sessionAttribution(run, "peer", rpc.pid, run.workDir); const peerState = async (): Promise => { const data = await rpc.send({ type: "get_state" }); @@ -2708,7 +2762,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> step = "closed-peer-not-live"; // The smoke ends the peer here; the sender stays live until the end of the mode. await finalScan(peerAttributed); - peerResult = await rpc.close(); + peer = { kind: "closed", result: await rpc.close() }; const closed = await sender.call(TALK_TOOL, { action: "send", instance: afterFork.instance, @@ -2722,15 +2776,16 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> } // The sender ends after its next turn, and a slow peer turn that still waits ends; a sender that still - // waits in a tool call is stopped. After a failed step, the peer ends here too; a peer that never became - // ready stays live until the cleanup, so it gets its final scan here as well. + // waits in a tool call is stopped. After a failed step, the peer ends here too; a peer that exited or stalled + // before its ready line is still open here, so it gets its final scan and its exit result as well. await finalScan(senderAttributed); sender.finish(); peerModel.release(); - if (peerResult === null) { + if (peer.kind !== "closed") { await finalScan(peerAttributed); - if (peer !== null) peerResult = await peer.close(); + if (peer.kind === "open") peer = { kind: "closed", result: await peer.handle.close() }; } + const peerResult = peer.kind === "closed" ? peer.result : null; const senderResult = senderRun === null ? null @@ -3165,12 +3220,29 @@ class TerminalOmp { } } +/** + * One omp process of a talk mode: not started, open while the driver holds a handle to close (whether or not the + * process passed its readiness check), or closed with its exit result. + */ +type FixtureProcess = + | { readonly kind: "absent" } + | { readonly kind: "open"; readonly handle: Handle } + | { readonly kind: "closed"; readonly result: OmpResult }; + /** One `talk` call of the RPC peer that the driver waits for. */ interface MarkedCall { - readonly marker: string; - readonly call: ToolCall; + phase: + | { readonly kind: "prompt"; readonly marker: string; readonly call: ToolCall } + | { readonly kind: "result"; readonly id: string }; readonly result: Deferred; - issued: boolean; +} + +/** Issue the call once, on the matching prompt. Only its result ID matters after that. */ +function issueMarkedCall(pending: MarkedCall, prompt: string | undefined): readonly ToolCall[] { + const phase = pending.phase; + if (phase.kind !== "prompt" || prompt?.includes(phase.marker) !== true) return []; + pending.phase = { kind: "result", id: phase.call.id }; + return [phase.call]; } /** @@ -3186,10 +3258,8 @@ class PeerCalls { this.#count += 1; const result = Promise.withResolvers(); this.#pending = { - marker, - call: { id: `peer-${this.#count}`, name: TALK_TOOL, arguments: toolArgs }, + phase: { kind: "prompt", marker, call: { id: `peer-${this.#count}`, name: TALK_TOOL, arguments: toolArgs } }, result, - issued: false, }; return withTimeout( result.promise, @@ -3201,12 +3271,8 @@ class PeerCalls { async respond(request: JsonObject): Promise { const pending = this.#pending; if (pending === null) return []; - if (!pending.issued) { - if (newUserText(request)?.includes(pending.marker) !== true) return []; - pending.issued = true; - return [pending.call]; - } - const result = toolResultText(request, pending.call.id); + if (pending.phase.kind === "prompt") return issueMarkedCall(pending, newUserText(request)); + const result = toolResultText(request, pending.phase.id); if (result !== undefined) { this.#pending = null; pending.result.resolve(result); @@ -3244,7 +3310,7 @@ class TerminalModel { const id = `tui-${this.#count}`; const result = Promise.withResolvers(); const call = { id, name: TALK_TOOL, arguments: toolArgs }; - this.#pending = { marker, call, draft, result, issued: false }; + this.#pending = { phase: { kind: "prompt", marker, call }, draft, result }; return withTimeout(result.promise, STEP_TIMEOUT_MS, `the handover call ${id} of the TUI omp`); } @@ -3254,14 +3320,10 @@ class TerminalModel { // The side turn copies the session with the pending call and a synthetic result of it (#260 F7), so the // template decides before the result does. if (prompt?.includes(HANDOVER_PROMPT_TEXT) === true) - return pending?.issued === true ? pending.draft : HANDOVER_DRAFT; + return pending?.phase.kind === "result" ? pending.draft : HANDOVER_DRAFT; if (pending === null) return []; - if (!pending.issued) { - if (prompt?.includes(pending.marker) !== true) return []; - pending.issued = true; - return [pending.call]; - } - const result = toolResultText(request, pending.call.id); + if (pending.phase.kind === "prompt") return issueMarkedCall(pending, prompt); + const result = toolResultText(request, pending.phase.id); if (result !== undefined) { this.#pending = null; pending.result.resolve(result); @@ -3315,9 +3377,8 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null const pass = (): void => { results.set(step, ""); }; - let terminal: TerminalOmp | null = null; - let terminalResult: OmpResult | null = null; - let peer: RpcPeer | null = null; + let terminal: FixtureProcess = { kind: "absent" }; + let peer: FixtureProcess = { kind: "absent" }; /** * omp before 19.2.0: one capability notice, no load error, no `/talk` command, and no `talk` tool. The first @@ -3807,7 +3868,7 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null run.workDir, env, ); - terminal = screen; + terminal = { kind: "open", handle: screen }; // On omp 19.2.0 or later the TUI omp runs talk from its spawn, so its final scan runs also when its footer or // the peer never shows. On an older omp talk is off, and the TUI omp has no final scan. if (checks !== OLD_OMP_CHECKS) @@ -3820,39 +3881,45 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null await screen.waitFor(UI_READY_TEXT, 0, "footer with the model name"); if (checks === OLD_OMP_CHECKS) await oldOmpFlow(screen); else { - peer = await startRpcOmp( + // The mode holds the peer handle before the ready line, so a peer that ends or stalls first still gets its + // final scan and its exit result. + const started = startRpcOmp( ["--mode", "rpc", "--model", `${MODEL_PROVIDER}/${PEER_MODEL_ID}`, "--no-title"], run.workDir, env, - (pid) => { - if (pid !== undefined) - peerAttributed.push({ label: "peer", registration: { processId: pid, cwd: run.workDir } }); - }, ); + const rpc = started.peer; + if (rpc.pid !== undefined) { + peer = { kind: "open", handle: rpc }; + peerAttributed.push({ label: "peer", registration: { processId: rpc.pid, cwd: run.workDir } }); + } + await started.ready; // Both omp processes are live: the TUI omp shows its footer, and the peer waits for RPC commands. results.set( REGISTRY_CHECK, await attributionProblem([ sessionAttribution(run, "TUI", screen.pid, run.workDir), - sessionAttribution(run, "peer", peer.pid, run.workDir), + sessionAttribution(run, "peer", rpc.pid, run.workDir), ]), ); - await currentFlow(screen, peer); + await currentFlow(screen, rpc); } await finalScan(terminalAttributed); - terminalResult = await screen.close(); + terminal = { kind: "closed", result: await screen.close() }; } catch (error) { results.set(step, error instanceof Error ? error.message : String(error)); } - if (terminal !== null && terminalResult === null) { + if (terminal.kind === "open") { await finalScan(terminalAttributed); - terminalResult = await terminal.close(); + terminal = { kind: "closed", result: await terminal.handle.close() }; } - // The peer stays live while the TUI omp closes, so its final scan comes after that; a peer that never became - // ready stays live until the cleanup. + const terminalResult = terminal.kind === "closed" ? terminal.result : null; + // The peer stays live while the TUI omp closes, so its final scan comes after that; a peer that exited or + // stalled before its ready line is still open here as well. await finalScan(peerAttributed); - const peerResult = peer === null ? null : await peer.close(); + if (peer.kind === "open") peer = { kind: "closed", result: await peer.handle.close() }; + const peerResult = peer.kind === "closed" ? peer.result : null; const sessionFailures: string[] = []; const sessions: Array = [["TUI", terminalResult]]; if (checks === UI_CHECKS) sessions.push(["peer", peerResult]); diff --git a/.agents/skills/verify/scripts/smokeScan.ts b/.agents/skills/verify/scripts/smokeScan.ts index 80ad560a..84a48326 100644 --- a/.agents/skills/verify/scripts/smokeScan.ts +++ b/.agents/skills/verify/scripts/smokeScan.ts @@ -54,10 +54,19 @@ export interface SessionRegistryChecks { * can have written an entry since. */ readonly timeout: () => Promise; - /** The problems of the attribution and of each scan, without exact duplicates, or an empty text. */ - readonly problem: () => Promise; + /** The distinct problems from attribution, the original final scan, and the latest timeout scan. */ + readonly problem: (session: string) => Promise; } +/** + * The final scan of one print session: not started, running, or ended once its promise fulfilled, with a leak + * diagnostic or with an empty text. A running or ended scan keeps its original promise, so repeated final answers + * and the problem report share it. + */ +type FinalScan = + | { readonly phase: "idle" } + | { readonly phase: "running" | "ended"; readonly scan: Promise }; + /** * The check state of one print session. `scanFinal` runs one bounded scan of the default folder for the session * and gives its problem, or an empty text. @@ -66,28 +75,33 @@ export function sessionRegistryChecks(options: { readonly attribution: Promise; readonly scanFinal: () => Promise; }): SessionRegistryChecks { - let final: Promise | undefined; - let finalEnded = false; + let final: FinalScan = { phase: "idle" }; let timeoutScan: Promise | undefined; const finalAnswer = (): Promise => { - if (final === undefined) { - final = options.scanFinal(); - void final.then(() => { - finalEnded = true; - }); - } - return final; + if (final.phase !== "idle") return final.scan; + const scan = options.scanFinal(); + final = { phase: "running", scan }; + void scan.then(() => { + final = { phase: "ended", scan }; + }); + return scan; }; return { attribution: options.attribution, finalAnswer, timeout: () => { - if (!finalEnded) return finalAnswer(); + if (final.phase !== "ended") return finalAnswer(); timeoutScan = options.scanFinal(); return timeoutScan; }, - problem: async () => { - const problems = [await options.attribution, await (final ?? ""), await (timeoutScan ?? "")]; + problem: async (session) => { + const problems = [ + await options.attribution, + await (final.phase === "idle" + ? `${session}: the session ended without its final registry scan` + : final.scan), + await (timeoutScan ?? ""), + ]; return [...new Set(problems.filter(Boolean))].join("; "); }, }; diff --git a/.agents/skills/verify/scripts/smokeTalkTurns.ts b/.agents/skills/verify/scripts/smokeTalkTurns.ts index f1903b4e..fbadcba7 100644 --- a/.agents/skills/verify/scripts/smokeTalkTurns.ts +++ b/.agents/skills/verify/scripts/smokeTalkTurns.ts @@ -1,11 +1,12 @@ /** * The scripted model turns of the `talk` mode of `omp-smoke.ts`: the JSON narrowing and the reading of provider - * requests, the responders of the sender and of the peer, and the `talk-offered` check. omp can send other - * requests with the model id of a session, for example a request without tools and without the fixture prompt - * before the first prompted turn, or one that copies the conversation. A responder acts only on the current - * turn of a request: the user messages and tool results after its last assistant message. Any other request - * gets a plain answer and neither starts a responder nor takes or advances a call of it. The module uses no Bun - * API and has no side effect at import, so unit tests can load it (`cli/test/unit/verifySmokeTalkTurns.test.ts`). + * requests, the responders of the sender and of the peer, the `talk-offered` check, the tool verdict of the load + * mode, and the stop continuation of the `hooks` mode. omp can send other requests with the model id of a + * session, for example a request without tools and without the fixture prompt before the first prompted turn, or + * one that copies the conversation. A responder acts only on the current turn of a request: the user messages and + * tool results after its last assistant message. Any other request gets a plain answer and neither starts a + * responder nor takes or advances a call of it. The module uses no Bun API and has no side effect at import, so + * unit tests can load it (`cli/test/unit/verifySmokeTalkTurns.test.ts`). */ import { TRUST_LINE } from "../../../../cli/talk/tool/format.ts"; @@ -38,6 +39,8 @@ export interface Deferred { /** The name of the tool that the talk extension registers. */ export const TALK_TOOL = "talk"; +/** The text answer of the fake model to a turn without tool calls. */ +export const PLAIN_ANSWER = "ok"; /** The longest wait of one step: a tool call, an RPC command, or a peer state. */ export const STEP_TIMEOUT_MS = 30_000; /** The peer holds this RPC prompt until the driver releases it or the step timeout expires. */ @@ -153,6 +156,14 @@ function latestEvent(request: JsonObject): FixtureEvent | undefined { return undefined; } +/** + * Whether an event is the user instruction `prompt`, apart from surrounding whitespace: the opening of a talk + * fixture conversation. + */ +function isOpening(event: FixtureEvent | undefined, prompt: string): boolean { + return event?.role === "user" && event.text.trim() === prompt; +} + /** * Whether a user message of a request holds the handover template: the request is a side turn. The template * counts also when it spans adjacent text parts of one message. @@ -164,6 +175,164 @@ export function holdsHandoverPrompt(request: JsonObject): boolean { ); } +/** + * The heading line of the agent list in the task tool description, as omp renders `prompts/tools/task.md` + * (`# Available Agents`, the last section of that template). + */ +const AGENTS_HEADING = /^# Available Agents$/m; +/** A markdown heading line, which ends the agent list. */ +const NEXT_HEADING = /^#{1,6}[ \t]/m; +/** + * One agent of the list: "- ``", the optional markers of the template such as " (read-only, no edits)", + * then ":" and the agent description, which may be empty. + */ +const AGENT_BULLET = /^- `([^`\s]+)`(?: \([^()\n]*\))*:(?: |$)/gm; + +/** + * The agent names of a task tool description, or null when it has no agent list. Only the agent bullets of + * the `# Available Agents` section count, up to the next heading. Other lines of that section, such as the + * notice of disabled spawning, and bullets of other sections are not agents. A section without agent + * bullets is an empty list. + */ +function advertisedAgents(description: string): string[] | null { + const heading = AGENTS_HEADING.exec(description); + if (heading === null) return null; + const rest = description.slice(heading.index + heading[0].length); + const next = NEXT_HEADING.exec(rest); + const section = next === null ? rest : rest.slice(0, next.index); + return [...section.matchAll(AGENT_BULLET)].map((match) => match[1] ?? ""); +} + +/** + * The agent names of the task tool of a request, or null when the first task tool with a description has + * no agent list, or no task tool has a description. + */ +function taskToolAgents(request: JsonObject): string[] | null { + for (const tool of objects(request["tools"])) { + const fn = isObject(tool["function"]) ? tool["function"] : tool; + if (fn["name"] !== "task") continue; + const description = fn["description"]; + if (typeof description === "string") return advertisedAgents(description); + } + return null; +} + +/** + * The first request of `model` whose latest user instruction is exactly `prompt` once whole host-reminder parts + * are left out, outside handover side turns. Auxiliary requests of omp with the same model id, also one with a + * whitespace-padded copy of the prompt, do not count, and the tools of a request never select it. + */ +function loadOpening( + requests: readonly JsonObject[], + model: string, + prompt: string, +): JsonObject | undefined { + return requests.find((request) => { + if (request["model"] !== model || holdsHandoverPrompt(request)) return false; + const event = latestEvent(request); + return event?.role === "user" && event.text === prompt; + }); +} + +/** The load fixture: its model id and prompt, the agents that the plugin ships, and the required ones. */ +export interface LoadFixture { + readonly model: string; + readonly prompt: string; + readonly ownAgents: ReadonlySet; + readonly requiredAgents: readonly string[]; +} + +/** What the load mode reports about the provider requests of its print session. */ +export interface LoadVerdict { + /** The plugin agents that the task tool of the opening request lists, sorted. */ + readonly agents: readonly string[]; + /** Whether the opening request offers the `talk` tool. */ + readonly talkOffered: boolean; + readonly failures: readonly string[]; +} + +/** + * The tool checks of the load mode. Both advertisements come from the same opening request (`loadOpening`). The + * missing agents are named only when that request has a task tool whose description holds the + * `# Available Agents` section, so a missing request, task tool or section is not reported as missing agents. + */ +export function loadVerdict(requests: readonly JsonObject[], fixture: LoadFixture): LoadVerdict { + if (requests.length === 0) + return { + agents: [], + talkOffered: false, + failures: ["the fake model received no request from the omp session"], + }; + const opening = loadOpening(requests, fixture.model, fixture.prompt); + if (opening === undefined) + return { + agents: [], + talkOffered: false, + failures: ["the fake model received no opening fixture request"], + }; + const failures: string[] = []; + const listed = taskToolAgents(opening); + const agents = + listed === null ? [] : listed.filter((agent) => fixture.ownAgents.has(agent)).sort(); + if (listed === null) failures.push("the fixture request has no task tool with an agent list"); + else { + const missing = fixture.requiredAgents.filter((agent) => !agents.includes(agent)); + if (missing.length > 0) + failures.push(`agents missing from the task tool: ${missing.join(",")}`); + } + const talkOffered = offersTool(opening, TALK_TOOL); + if (!talkOffered) failures.push(`the first fixture request does not offer the ${TALK_TOOL} tool`); + return { agents, talkOffered, failures }; +} + +/** The heading of the resources that still exist in the stop reminder (`stopReminder` in `hygiene.ts`). */ +const STOP_HEADING = "These resources from this session still exist:"; + +/** The temporary directory of the hooks fixture: its creating call and its path. */ +export interface StopFixture { + readonly model: string; + readonly callId: string; + readonly directory: string; +} + +/** + * Whether one request continues the session after the stop hook. The first assistant message after the tool + * result of `callId` is the plain answer, without tool calls, and the last assistant message of the request. The + * last message is a new user message after it, with the stop heading and then the line of the directory. A + * reminder before that answer, or one that a later message follows, does not count. + */ +export function stopContinued(request: JsonObject, fixture: StopFixture): boolean { + if (request["model"] !== fixture.model) return false; + const messages = objects(request["messages"]); + const result = messages.findIndex( + (message) => message["role"] === "tool" && message["tool_call_id"] === fixture.callId, + ); + if (result === -1) return false; + const answer = messages.findIndex( + (message, index) => index > result && message["role"] === "assistant", + ); + if ( + answer === -1 || + messages.some((message, index) => index > answer && message["role"] === "assistant") + ) + return false; + const plain = messages[answer]; + if ( + plain === undefined || + objects(plain["tool_calls"]).length > 0 || + textOf(plain["content"]) !== PLAIN_ANSWER + ) + return false; + const last = messages.at(-1); + if (last === undefined || last["role"] !== "user") return false; + const context = textOf(last["content"]); + const heading = context.indexOf(STOP_HEADING); + return ( + heading !== -1 && + context.includes(`\n- the temporary directory ${fixture.directory}: `, heading) + ); +} + /** * The `talk-offered` check of one session: its first fixture turn comes within the step timeout, and that turn * offers the `talk` tool. @@ -181,6 +350,15 @@ export async function expectTalkOffered( throw new Error(`the first fixture turn of the ${label} does not offer the ${TALK_TOOL} tool`); } +/** + * The outstanding call of a scripted session: none, a call that waits for its result, or the exit of omp, which + * fails each later call. + */ +type CallSlot = + | { readonly state: "idle" } + | { readonly state: "waiting"; readonly id: string; readonly result: Deferred } + | { readonly state: "aborted"; readonly error: Error }; + /** * The sender starts when its opening prompt is the latest user instruction. Each call waits until * its result is the latest event. A newer instruction supersedes a copied result. Handover side @@ -191,9 +369,9 @@ export class ScriptedSession { readonly #prompt: string; readonly #first = Promise.withResolvers(); #next = Promise.withResolvers(); - #pending: { readonly id: string; readonly result: Deferred } | null = null; + #call: CallSlot = { state: "idle" }; + /** Whether the opening prompt came; a staged call or an auxiliary request does not imply it. */ #started = false; - #ended: Error | null = null; #count = 0; constructor(label: string, prompt: string) { @@ -210,15 +388,15 @@ export class ScriptedSession { async respond(request: JsonObject): Promise { if (holdsHandoverPrompt(request)) return []; const event = latestEvent(request); - const pending = this.#pending; - if (pending === null) { - if (this.#started || event?.role !== "user" || event.text.trim() !== this.#prompt) return []; + const slot = this.#call; + if (slot.state === "waiting") { + if (event?.role !== "tool" || event.id !== slot.id) return []; + this.#call = { state: "idle" }; + slot.result.resolve(event.text); + } else { + if (this.#started || !isOpening(event, this.#prompt)) return []; this.#started = true; this.#first.resolve(request); - } else { - if (event?.role !== "tool" || event.id !== pending.id) return []; - this.#pending = null; - pending.result.resolve(event.text); } const call = await this.#next.promise; this.#next = Promise.withResolvers(); @@ -227,11 +405,11 @@ export class ScriptedSession { /** Makes the next turn of the session call `name` with `args`; gives the text of its tool result. */ call(name: string, toolArgs: Readonly>): Promise { - if (this.#ended !== null) return Promise.reject(this.#ended); + if (this.#call.state === "aborted") return Promise.reject(this.#call.error); this.#count += 1; const id = `${this.#label}-${this.#count}`; const result = Promise.withResolvers(); - this.#pending = { id, result }; + this.#call = { state: "waiting", id, result }; this.#next.resolve({ id, name, arguments: toolArgs }); return withTimeout( result.promise, @@ -247,10 +425,11 @@ export class ScriptedSession { /** The omp process exited: a call that waits fails at once. */ abort(reason: string): void { - this.#ended = new Error(reason); - this.#first.reject(this.#ended); - this.#pending?.result.reject(this.#ended); - this.#pending = null; + const error = new Error(reason); + const slot = this.#call; + this.#call = { state: "aborted", error }; + this.#first.reject(error); + if (slot.state === "waiting") slot.result.reject(error); } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b5a3c42..20d2fd0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 2026-12-01 - docks-kit 0.31.3: cleanup reminders during overlapping stops + +Overlapping stop checks no longer repeat a cleanup reminder for the same resource. +If you recreate a resource under the same name, an older check no longer marks it as checked or removes its reminder. + ## 2026-11-27 - docks-kit 0.31.0: the talk tool starts a handover An agent can now start a handover when the user asks for one in words, so diff --git a/SoT/.omp/plugin/extensions/hygiene.ts b/SoT/.omp/plugin/extensions/hygiene.ts index 83780eeb..68293cac 100644 --- a/SoT/.omp/plugin/extensions/hygiene.ts +++ b/SoT/.omp/plugin/extensions/hygiene.ts @@ -308,6 +308,15 @@ interface ScopedSegment extends ShellSegment { setupKnown: boolean; } +/** The word that scopedSegments reads. An empty quoted word such as `''` is a word too. */ +interface ShellToken { + text: string; + /** True when the word holds a quoted or escaped character. */ + quoted: boolean; + /** The source index of the last character that the word took without quoting, else -1. */ + lastUnquoted: number; +} + export interface RunOptions { readonly signal?: AbortSignal; readonly timeoutMs: number; @@ -536,12 +545,8 @@ function scopedSegments(command: string, rootScope: string): Array = []; - let word = ""; - let inWord = false; - /** True when the current word holds a quoted or escaped character. */ - let wordQuoted = false; - /** The source index of the last character that the word took without quoting. */ - let lastUnquoted = -1; + /** The word that the scan reads, or undefined between words. */ + let token: ShellToken | undefined; /** The strip flag of a `<<` operator whose delimiter is the next word. */ let heredocOperator: boolean | undefined; /** The operators after the last segment; they count only when a segment follows. */ @@ -550,8 +555,12 @@ function scopedSegments(command: string, rootScope: string): Array scopes.at(-1) ?? rootScope; const childScope = (): string => `${currentScope()}/${childScopes++}`; + /** The current word; the first character of a word starts it. */ + const startToken = (): ShellToken => (token ??= { text: "", quoted: false, lastUnquoted: -1 }); const finishWord = (): void => { - if (!inWord) return; + if (token === undefined) return; + const word = token.text; + token = undefined; if (heredocOperator !== undefined) { heredocs.push({ delimiter: word, strip: heredocOperator }); heredocOperator = undefined; @@ -565,9 +574,6 @@ function scopedSegments(command: string, rootScope: string): Array { + const current = startToken(); + current.quoted = true; let index = start; - inWord = true; while (index < command.length && command[index] !== '"') { const char = command[index]; const next = command[index + 1]; if (char === "\\" && next !== undefined && '"\\$`\n'.includes(next)) { - if (next !== "\n") word += next; + if (next !== "\n") current.text += next; index += 2; } else if (char === "$" && next === "(") { index = readSubstitution(index); } else if (char === "`") { index = readBacktick(index); } else { - word += char; + current.text += char; index++; } } @@ -674,18 +679,17 @@ function scopedSegments(command: string, rootScope: string): Array 0; + const continues = words.length === 0 && token === undefined && pendingSeparators.size > 0; finishSegment(continues ? undefined : ";"); index = skipHeredocBodies(index + 1); - } else if (char === "(" && !inWord) { + } else if (char === "(" && token === undefined) { // `name ()` defines a function: its body runs only when it is called. if (definesFunction(words)) skipsCommands = true; finishSegment(undefined); @@ -721,7 +725,7 @@ function scopedSegments(command: string, rootScope: string): Array|file` the `|` belongs to the redirection; the split stays as it // was, but it separates nothing. Only an unquoted `>` directly before // the `|` makes a clobber, so `echo '>'|` and `echo \>|` are pipes. - const clobber = inWord && command[index - 1] === ">" && lastUnquoted === index - 1; + const clobber = command[index - 1] === ">" && token?.lastUnquoted === index - 1; if (clobber) { finishSegment(undefined); index++; @@ -733,23 +737,31 @@ function scopedSegments(command: string, rootScope: string): Array" || word.endsWith(">") || word.endsWith("<")) { + } else if ( + next === ">" || + token?.text.endsWith(">") === true || + token?.text.endsWith("<") === true + ) { // A redirection such as `&>file` or `2>&1`. - word += char; - inWord = true; + startToken().text += char; index++; } else { finishSegment("&"); index++; } } else { + const current = startToken(); // `name()` without a space: an unquoted name word directly before `(`. - if (char === "(" && words.length === 0 && !wordQuoted && FUNCTION_NAME.test(word)) { + if ( + char === "(" && + words.length === 0 && + !current.quoted && + FUNCTION_NAME.test(current.text) + ) { skipsCommands = true; } - word += char; - inWord = true; - lastUnquoted = index; + current.text += char; + current.lastUnquoted = index; index++; } } @@ -1918,12 +1930,29 @@ export function claimSweep(cacheDir: string, nowMs: number): boolean { // ---------------------------------------------------------------- ledger ---- +/** + * The stop state of one resource key; a key without an entry is absent. A + * pending entry holds the latest resource recorded under the key, and a stop + * names it while it exists. A reminded key stays reminded, also when a later + * call records the same resource again. A stop applies its result only while + * the key still holds the exact record that it checked. + */ +type LedgerEntry = HygieneResource | "reminded"; /** * One omp process shares module state across its sessions, so the main * session also sees the resources that its subagents created. */ -const ledger = new Map(); -const reminded = new Set(); +const ledger = new Map(); + +/** + * Resource detection creates a fresh object for each creation. A pending stop + * checks that object's identity before it applies its result. Reminded keys stay reminded. + */ +function recordResource(resource: HygieneResource): void { + const key = resourceKey(resource); + if (ledger.get(key) !== "reminded") ledger.set(key, resource); +} + /** * The stash IDs of each directory of a bash call before the call ran, keyed * by tool call ID. The tool_result handler takes the snapshot out. omp sends @@ -2114,7 +2143,7 @@ async function resourceLines(event: ToolResultEvent, ctx: ExtensionContext): Pro const detected = detectResources(call.command, call.cwd, output, homedir()); const resources: Array = failed ? [] : detected.resources; resources.push(...(await createdStashes(detected.stashes, snapshot))); - for (const resource of resources) ledger.set(resourceKey(resource), resource); + for (const resource of resources) recordResource(resource); return [...resources.map(creationReminder), ...(failed ? [] : detected.notes)]; } @@ -2147,7 +2176,7 @@ export default function docksKitOmp(pi: ExtensionApi): void { const path = lastAbsoluteLine(output); if (path === undefined) throw new Error(`docks-kit scratch new printed no path: ${output}`); const resource: HygieneResource = { kind: "scratch", path }; - ledger.set(resourceKey(resource), resource); + recordResource(resource); return textResult(path, { path }); } catch (error) { throw toError(error); @@ -2229,7 +2258,11 @@ export default function docksKitOmp(pi: ExtensionApi): void { pi.on("session_stop", async (event) => { try { if (event.stop_hook_active === true) return undefined; - const pending = [...ledger].filter(([key]) => !reminded.has(key)); + // Each check holds the resource as it was when this stop started. + const pending: Array<[string, HygieneResource]> = []; + for (const [key, entry] of ledger) { + if (entry !== "reminded") pending.push([key, entry]); + } if (pending.length === 0) return undefined; const states = await Promise.all( pending.map(async ([key, resource]) => ({ @@ -2241,11 +2274,14 @@ export default function docksKitOmp(pi: ExtensionApi): void { const verified: Array = []; const unverified: Array = []; for (const { key, resource, exists } of states) { + // A result says nothing about a record that a call stored after this + // stop started, and another stop that ended first already reminded. + if (ledger.get(key) !== resource) continue; if (!exists) { ledger.delete(key); continue; } - reminded.add(key); + ledger.set(key, "reminded"); if (resource.kind === "other") unverified.push(resource); else verified.push(resource); } diff --git a/SoT/.omp/plugin/extensions/talk.js b/SoT/.omp/plugin/extensions/talk.js index 3687bdbc..f5df07b4 100644 --- a/SoT/.omp/plugin/extensions/talk.js +++ b/SoT/.omp/plugin/extensions/talk.js @@ -77,7 +77,7 @@ ${renderErrorCause(cause.cause,`${prefix} `)} ${prefix}}`;return stack},FiberTypeId="~effect/Fiber",fiberVariance={_A:identity,_E:identity},nextFiberId=0,AsyncResource=(()=>{try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource}catch{return}})(),captureAsyncContext=()=>AsyncResource===void 0?void 0:new AsyncResource("effect/Fiber"),getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=!0){this.setContext(context),this.id=++nextFiberId,this.currentOpCount=0,this.interruptible=interruptible,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._autoYielded=!1,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[FiberTypeId](){return fiberVariance}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(ref){return getReferenceUnsafe(this.context,ref)}addObserver(cb){if(this._exit)return cb(this._exit),constVoid;return(this._observers??=[]).push(cb),()=>this.removeObserver(cb)}removeObserver(cb){if(this._exit||this._observers===void 0)return;let index=this._observers.indexOf(cb);if(index>=0)this._observers.splice(index,1)}interruptUnsafe(fiberId,annotations){if(this._exit)return;let cause=causeInterrupt(fiberId);if(this.cache.stackFrame)cause=causeAnnotateMap(cause,new Map([[StackTraceKey,this.cache.stackFrame]]));if(annotations)cause=causeAnnotateMap(cause,annotations.mapUnsafe);if(this._interruptedCause=this._interruptedCause?causeAddInterrupts(this._interruptedCause,cause):cause,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(failCause(this._interruptedCause))}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit)return;else if(this._asyncContext!==void 0){let asyncContext=this._asyncContext;this._asyncContext=void 0;try{return asyncContext.runInAsyncScope(this.evaluate,this,effect)}finally{asyncContext.emitDestroy()}}else if(this._yielded!==void 0){let yielded=this._yielded;this._yielded=void 0,yielded()}let exit=this.runLoop(effect);if(exit===Yield){this._asyncContext=captureAsyncContext();return}let interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this,exit);if(interruptChildren!==void 0)return this.interruptible=!1,this.evaluate(interruptChildren);if(this._exit=exit,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent)this._parent._children?.delete(this),this._parent=void 0;if(this._observers!==void 0){let observers=this._observers;this._observers=void 0;for(let i=0;i{if(resumed)return;this._autoYielded=automatic,this.evaluate(effect)},priority),this.yieldWith(()=>{resumed=!0})}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){let previous=this.context;if(this.context=context,previous!==void 0&&hasSameCache(previous,context))return;let root=context.cacheRoot,cache=root._fiberCache??=makeFiberContextCache(context);if(this.cache?.scheduler!==cache.scheduler)this._dispatcher=void 0;this.cache=cache}get currentSpanLocal(){let span=this.cache.span;return span?._tag==="Span"?span:void 0}}var makeFiberContextCache=(context)=>{let get=(key)=>getOrUndefinedUnsafe(context,key),currentTracer=get(TracerKey);return{scheduler:get(SchedulerKey)??getDefaultScheduler(),tracer:currentTracer,tracerContext:currentTracer?.context,tracerEnabled:get(TracerEnabledKey)??defaultTracerEnabled,span:get(ParentSpanKey),logLevel:get(CurrentLogLevelKey)??defaultCurrentLogLevel,minimumLogLevel:get(MinimumLogLevelKey)??defaultMinimumLogLevel,stackFrame:get(CurrentStackFrameKey),runtimeMetrics:get(FiberRuntimeMetricsKey),maxOpsBeforeYield:get(MaxOpsBeforeYieldKey)??defaultMaxOpsBeforeYield,preventYield:get(PreventSchedulerYieldKey)??defaultPreventSchedulerYield}},deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}},maxInlineSteps=32,fiberMiddleware={interruptChildren:void 0},fiberStackAnnotations=(fiber)=>{if(!fiber.cache.stackFrame)return;let annotations=new Map;return annotations.set(InterruptorStackTrace.key,fiber.cache.stackFrame),makeUnsafe(annotations)},fiberInterruptChildren=(fiber,exit)=>{if(fiber._children===void 0||fiber._children.size===0)return;return flatMap(fiberInterruptAll(fiber._children),()=>exit)},fiberAwait=(self)=>{let impl=self;if(impl._exit)return succeed3(impl._exit);return callback((resume)=>{if(impl._exit)return resume(succeed3(impl._exit));return sync(self.addObserver((exit)=>resume(succeed3(exit))))})},fiberAwaitAll=(self)=>callback((resume)=>{let iter=self[Symbol.iterator](),exits=[],cancel=void 0;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit),result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit),loop()});return}resume(succeed3(exits))}return loop(),sync(()=>cancel?.())}),fiberJoin=(self)=>{let impl=self;if(impl._exit)return impl._exit;return callback((resume)=>{if(impl._exit)return resume(impl._exit);return sync(self.addObserver(resume))})};var fiberInterrupt=(self)=>withFiber((fiber)=>fiberInterruptAs(self,fiber.id)),fiberInterruptAs=dual((args)=>hasProperty(args[0],FiberTypeId),(self,fiberId,annotations)=>withFiber((parent)=>{let ann=fiberStackAnnotations(parent);return ann=ann&&annotations?merge(ann,annotations):ann??annotations,self.interruptUnsafe(fiberId,ann),asVoid(fiberAwait(self))})),fiberInterruptAll=(fibers)=>withFiber((parent)=>{let annotations=fiberStackAnnotations(parent),fiberArr=empty3();for(let fiber of fibers)fiber.interruptUnsafe(parent.id,annotations),fiberArr.push(fiber);return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed,failCause=exitFailCause,fail3=exitFail,sync=makePrimitive({op:"Sync",[evaluate](fiber){let thunk=this[args],value=thunk(),cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}}),suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){let thunk=this[args];return thunk()}});var fromResult=match2({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){return fiber.yieldNow(exitVoid,this[args]??0)}}),yieldNow=yieldNowWith(0);var succeedNone=succeed3(none2());var failCauseSync=(evaluate)=>suspend(()=>failCause(evaluate())),die=(defect)=>exitDie(defect);var void_=succeed3(void 0);var try_=(options)=>{let evaluate=typeof options==="function"?options:options.try,catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(evaluate())}catch(err){return fail3(catcher(err))}})};var tryPromise=(options)=>{let f=typeof options==="function"?options:options.try,catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){let failWithCatch=(cause)=>suspend(()=>{try{return fail3(internalCall(()=>catcher(cause)))}catch(err){return die(err)}});try{f(signal).then((a)=>resume(succeed3(a)),(e)=>resume(failWithCatch(e)))}catch(err){resume(failWithCatch(err))}},f.length!==0)};var callbackOptions=function(){let Proto=makePrimitiveProto({op:"Async",[evaluate](fiber){let resumed=!1,yielded=!1,controller=this.withSignal?new AbortController:void 0,onCancel=this.register.call(fiber.cache.scheduler,(effect)=>{if(resumed)return;if(resumed=!0,yielded)fiber.evaluate(effect);else yielded=effect},controller?.signal);if(yielded!==!1)return yielded;if(yielded=!0,fiber.yieldWith(()=>{resumed=!0}),controller===void 0&&onCancel===void 0)return Yield;return fiber._stack.push(asyncFinalizer(()=>(resumed=!0,controller?.abort(),onCancel??exitVoid))),Yield}}),AsyncImpl=function(register,withSignal){this.register=register,this.withSignal=withSignal};return AsyncImpl.prototype=Proto,function(register,withSignal){return new AsyncImpl(register,withSignal)}}(),asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible)fiber.interruptible=!1,fiber._stack.push(setInterruptibleTrue)},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap(combineFinalizerCause(exitFailCause(cause),this[args]()),()=>failCause(cause)):failCause(cause)}}),callback=(register)=>callbackOptions(register,register.length>=2),never=callback(constVoid),gen=(...args)=>{if(args.length===1){let body=args[0];return suspend(()=>fromIteratorUnsafe(body()))}let[options,body]=args;return suspend(()=>fromIteratorUnsafe(body.call(options.self)))},fnBody=(bodyOrOptions,pipeables)=>typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.shift().bind(bodyOrOptions.self),fnUntraced=(bodyOrOptions,...pipeables)=>{let body=fnBody(bodyOrOptions,pipeables),fn=pipeables.length===0?function(){return suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)))}:function(){let effect=suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)));for(let i=0;iObject.defineProperty(fn,"length",{value:length,configurable:!0}),fnStackCleaner=makeStackCleaner(2),fn=function(){let nameFirst=typeof arguments[0]==="string",name=nameFirst?arguments[0]:"Effect.fn",spanOptions=nameFirst?arguments[1]:void 0,prevLimit=getStackTraceLimit(),defError;if(prevLimit!==0)setStackTraceLimit(2),defError=new globalThis.Error,setStackTraceLimit(prevLimit);if(nameFirst)return(body,...pipeables)=>makeFn(name,body,defError,pipeables,nameFirst,spanOptions);return makeFn(name,arguments[0],defError,Array.prototype.slice.call(arguments,1),nameFirst,spanOptions)},makeFn=(name,bodyOrOptions,defError,pipeables,addSpan,spanOptions)=>{let body=fnBody(bodyOrOptions,pipeables),definitionName=`${name} (definition)`,definitionStack=defError?fnStackCleaner(()=>defError.stack):constUndefined,makeCallFrame=(callError)=>(prev)=>({name,stack:callError?fnStackCleaner(()=>callError.stack):constUndefined,parent:{name:definitionName,stack:definitionStack,parent:prev}});return defineFunctionLength(body.length,function(...args){let result=suspend(()=>{let iter=body.apply(this,arguments);return isEffect(iter)?iter:fromIteratorUnsafe(iter)});for(let i=0;iprovideParentSpan(result,span)):result,CurrentStackFrame,makeCallFrame(callError))})},fnUntracedEager=(bodyOrOptions,...pipeables)=>{let body=fnBody(bodyOrOptions,pipeables);return defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(let pipeable of pipeables)effect=pipeable(effect,...arguments);return effect})},fromIteratorEagerUnsafe=(evaluate)=>{try{let iterator=evaluate(),value=void 0;while(!0){let state=iterator.next(value);if(state.done)return succeed3(state.value);let primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure")return state.value;else{let isFirstExecution=!0;return suspend(()=>{if(isFirstExecution)return isFirstExecution=!1,flatMap(state.value,(value)=>fromIteratorUnsafe(iterator,value));else return suspend(()=>fromIteratorUnsafe(evaluate()))})}}}catch(error){return die(error)}},fromIteratorUnsafe=function(){let Proto=makePrimitiveProto({op:"Iterator",[contA](value,fiber){let iter=this.iterator;while(!0){let state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value))return fiber._stack.push(this),state.value;else if(state.value._tag==="Failure")return state.value;value=state.value.value}},[evaluate](fiber){return this[contA](this.initial,fiber)}}),IteratorImpl=function(iterator,initial){this.iterator=iterator,this.initial=initial};return IteratorImpl.prototype=Proto,function(iterator,initial){return new IteratorImpl(iterator,initial)}}(),as=dual(2,(self,value)=>new ContImpl(self,returnPayload,succeed3(value))),evaluateCont=function(fiber){return fiber._stack.push(this),this[args]},OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate]:evaluateCont}),ContImpl=function(self,cont,payload){this[args]=self,this[contA]=cont,this.payload=payload};ContImpl.prototype=OnSuccessProto;var returnPayload=function(){return this.payload},succeedPayload=function(_value,fiber){return fiber.succeedWith(this.payload)},continuationMarksStack=(()=>{let limit=getStackTraceLimit();if(limit===0)return!1;let marker="~effect/Effect/stackProbe",probe={[marker]:function(){return Error()}};setStackTraceLimit(1);let error=probe[marker]();return setStackTraceLimit(limit),error.stack?.includes("[as "+marker+"]")===!0})(),mapCont=function(value,fiber){let f=this.payload;return fiber.succeedWith(continuationMarksStack?f(value):internalCall(()=>f(value)))},andThenCont=function(value){let f=this.payload;return f(value)},tapCont=function(value){let f=this.payload;return new ContImpl(f(value),succeedPayload,value)},tapEffectCont=function(value){return new ContImpl(this.payload,succeedPayload,value)},asSome=(self)=>map2(self,some2);var andThen=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?returnPayload:andThenCont,f)),tap=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?tapEffectCont:tapCont,f)),asVoid=(self)=>new ContImpl(self,returnPayload,exitVoid);var raceAllFirst=(all,options)=>withFiber((parent)=>{let fibers=new Set;return onExitUnsafe(parent,()=>fibers.size===0?void 0:fiberInterruptAll(fibers)),callback((resume)=>{let done=!1,i=0;for(let effect of all){if(done)break;let index=i++,fiber=new FiberImpl(parent.context);if(fibers.add(fiber),fiber.addObserver((exit)=>{fibers.delete(fiber);let isWinner=!done;if(done=!0,resume(exit),isWinner)interruptRaceLosers(fibers,parent),options?.onWinner?.({fiber,index,parentFiber:parent})}),done)fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent));else fiber.evaluate(effect);if(done)break}})}),interruptRaceLosers=(fibers,parent)=>{let annotations=fiberStackAnnotations(parent);for(let fiber of fibers)fiber.interruptUnsafe(parent.id,annotations)};var raceFirst=dual((args)=>isEffect(args[1]),(self,that,options)=>raceAllFirst([self,that],options)),flatMap=dual(2,(self,f)=>new ContImpl(self,andThenCont,f));var effectIsExit=(effect)=>effect[ExitTypeId]!==void 0,flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self))return self._tag==="Success"?f(self.value):self;return flatMap(self,f)}),flatten2=(self)=>flatMap(self,identity),map2=dual(2,(self,f)=>new ContImpl(self,mapCont,f)),mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map2(self,f)),mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError2(self,f));var exitIsSuccess=(self)=>self._tag==="Success";var exitIsFailure=(self)=>self._tag==="Failure";var exitHasInterrupts=(self)=>self._tag==="Failure"&&hasInterrupts(self.cause);var exitVoid=exitSucceed(void 0),exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self),exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;return exitFailCause(causeMap(self.cause,f))});var exitZipRight=dual(2,(self,that)=>exitIsSuccess(self)?that:self);var exitAsVoidAll=(exits)=>{let failures=[];for(let exit of exits)if(exit._tag==="Failure")failures.push(...exit.cause.reasons);return failures.length===0?exitVoid:exitFailCause(causeFromReasons(failures))};var updateContext=dual(2,(self,f)=>withFiber((fiber)=>{let prevContext=fiber.context,nextContext=f(prevContext);if(prevContext===nextContext)return self;return fiber.setContext(nextContext),onExitUnsafe(fiber,()=>{fiber.setContext(prevContext);return}),self})),updateService=dual(3,(self,service,f)=>updateContext(self,(s)=>{let prev=getUnsafe(s,service),next=f(prev);if(prev===next)return s;return add(s,service,next)}));var context=()=>getContext,getContext=withFiber((fiber)=>succeed3(fiber.context)),contextWith=(f)=>withFiber((fiber)=>f(fiber.context));var provideContext=dual(2,(self,context)=>{if(effectIsExit(self))return self;return updateContext(self,merge(context))}),provideService=function(){if(arguments.length===1)return dual(2,(self,impl)=>provideServiceImpl(self,arguments[0],impl));return dual(3,(self,service,impl)=>provideServiceImpl(self,service,impl)).apply(this,arguments)},provideServiceImpl=(self,service,implementation)=>updateContext(self,add(service,implementation));var filterOrFail=dual((args)=>isEffect(args[0]),(self,predicate,orFailWith)=>filterOrElse(self,predicate,orFailWith?(a)=>fail3(orFailWith(a)):()=>fail3(new NoSuchElementError)));var forever=dual((args)=>isEffect(args[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap(self,(_)=>yieldNow)),step:constVoid})),catchCause=dual(2,(self,f)=>new OnFailureImpl(self,f.length!==1?(cause)=>f(cause):f)),OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate]:evaluateCont}),OnFailureImpl=function(self,f){this[args]=self,this[contE]=f};OnFailureImpl.prototype=OnFailureProto;var catchCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{let eb=filter(cause);return isFailure2(eb)?failCause(eb.failure):f(eb.success,cause)})),catch_=dual(2,(self,f)=>catchCauseFilter(self,findRecoverableError,(e)=>f(e)));var catchDefect=dual(2,(self,f)=>catchCauseFilter(self,findDefect,f));var tapCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{let result=filter(cause);if(isFailure2(result))return failCause(cause);return andThen(f(result.success,cause),failCause(cause))})),tapError=dual(2,(self,f)=>tapCauseFilter(self,findError,(e)=>f(e)));var catchIf=dual((args)=>isEffect(args[0]),(self,predicate,f,orElse)=>catchCause(self,(cause)=>{let error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);if(!predicate(error.success))return orElse?orElse(error.success):failCause(cause);return f(error.success)})),catchFilter=dual((args)=>isEffect(args[0]),(self,filter,f,orElse)=>catchCause(self,(cause)=>{let error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);let result=filter(error.success);if(isFailure2(result))return orElse?orElse(result.failure):failCause(cause);return f(result.success)})),catchTag=dual((args)=>isEffect(args[0]),(self,k,f,orElse)=>{let pred=Array.isArray(k)?(e)=>hasProperty(e,"_tag")&&k.includes(e._tag):isTagged(k);return catchIf(self,pred,f,orElse)}),catchTags=dual((args)=>isEffect(args[0]),(self,cases,orElse)=>{let keys;return catchFilter(self,(e)=>(keys??=Object.keys(cases),hasProperty(e,"_tag")&&isString(e._tag)&&keys.includes(e._tag)?succeed2(e):fail2(e)),(e)=>cases[e._tag](e),orElse)});var mapError2=dual(2,(self,f)=>catchCause(self,(cause)=>failCause(causeMap(cause,f))));var orDie=(self)=>catch_(self,die),orElseSucceed=dual(2,(self,f)=>catch_(self,(error)=>sync(()=>f(error))));var ignoreCauseLogger=(log)=>log==="Unhandled"?(...message)=>withFiber((fiber)=>{let level=fiber.getRef(UnhandledLogLevel);return level===void 0?void_:logWithLevel(level)(...message)}):logWithLevel(log===!0?void 0:log),ignore=dual((args)=>isEffect(args[0]),(self,options)=>{if(!options?.log)return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_});let logEffect=ignoreCauseLogger(options.log);return matchCauseEffect(self,{onFailure(cause){let error=findRecoverableError(cause);return isFailure2(error)?failCause(error.failure):options.message===void 0?logEffect(cause):logEffect(options.message,cause)},onSuccess:(_)=>void_})});var result=(self)=>matchEager(self,{onFailure:fail2,onSuccess:succeed2}),matchCauseEffect=dual(2,(self,options)=>new OnSuccessAndFailureImpl(self,options.onSuccess.length!==1?(a)=>options.onSuccess(a):options.onSuccess,options.onFailure.length!==1?(cause)=>options.onFailure(cause):options.onFailure)),OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate]:evaluateCont}),OnSuccessAndFailureImpl=function(self,onSuccess,onFailure){this[args]=self,this[contA]=onSuccess,this[contE]=onFailure};OnSuccessAndFailureImpl.prototype=OnSuccessAndFailureProto;var matchSuccess=function(value,fiber){let handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onSuccess(value):internalCall(()=>handlers.onSuccess(value)))},makeMatch=(op,onFailure)=>{let Proto=makePrimitiveProto({op,[evaluate]:evaluateCont,[contA]:matchSuccess,[contE]:onFailure}),MatchImpl=function(self,handlers){this[args]=self,this.payload=handlers};return MatchImpl.prototype=Proto,MatchImpl},MatchImpl=makeMatch("Match",function(cause,fiber){let error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);let handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onFailure(error.success):internalCall(()=>handlers.onFailure(error.success)))});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{let error=findRecoverableError(cause);return isFailure2(error)?failCause(error.failure):options.onFailure(error.success)},onSuccess:options.onSuccess})),match4=dual(2,(self,options)=>new MatchImpl(self,options)),matchEager=dual(2,(self,options)=>{if(effectIsExit(self)){if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));let error=findRecoverableError(self.cause);if(isFailure2(error))return exitFailCause(error.failure);return exitSucceed(options.onFailure(error.success))}return match4(self,options)});var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self),exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){return fiber._stack.push(this),this[args]},[contA](value,fiber,exit){return fiber.succeedWith(exit??exitSucceed(value))},[contE](cause,fiber,exit){return fiber.succeedWith(exit??exitFailCause(cause))}});var timeoutOrElse=dual(2,(self,options)=>flatMap(timeoutOption(self,options.duration),(option)=>isNone2(option)?options.orElse():succeed3(option.value)));var timeoutOption=dual(2,(self,duration)=>raceFirst(asSome(self),as(sleep(duration),none2())));var ScopeTypeId="~effect/Scope",ScopeCloseableTypeId="~effect/Scope/Closeable",scopeTag=Service("effect/Scope"),scopeClose=(self,exit_)=>withFiber((fiber)=>(fiberEnterUninterruptibleUnsafe(fiber),scopeCloseUnsafe(self,exit_)??void_)),scopeCloseUnsafe=(self,exit_)=>{let state=self.state;if(state._tag==="Closed")return;if(self.state={_tag:"Closed",exit:exit_},self.parent!==void 0)scopeRemoveFinalizerUnsafe(self.parent,self);if(state._tag==="Empty")return;if(state.finalizer!==void 0)return runFinalizer(state.finalizer,exit_);let finalizers=state.finalizers;if(finalizers.size===1)return runFinalizer(finalizers.values().next().value,exit_);return scopeCloseFinalizers(self,finalizers,exit_)},runFinalizer=(finalizer,exit_)=>{try{return finalizer(exit_)}catch(defect){return exitDie(defect)}},combineFinalizerCause=(exit_,finalizer)=>exitIsSuccess(exit_)?finalizer:catchCause(finalizer,(cause)=>failCause(causeElectDefects(causeCombine(exit_.cause,cause)))),scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[],fibers=[],arr=Array.from(finalizers),parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){let[key,finalizer]=arr[i];if(self.strategy==="sequential")exits.push(yield*exit(runFinalizer(finalizer,exit_)));else if(key!==parent)fibers.push(forkUnsafe(parent,runFinalizer(finalizer,exit_),!0,!0,"inherit"))}if(fibers.length>0)exits=yield*fiberAwaitAll(fibers);return yield*exitAsVoidAll(exits)});var scopeForkUnsafe=(scope,finalizerStrategy)=>{let child=makeScope(finalizerStrategy,scope);if(scope.state._tag==="Closed")return child.state=scope.state,child;return scopeAddFinalizerUnsafe(scope,child,(exit)=>scopeClose(child,exit)),child},scopeAddFinalizerExit=(scope,finalizer)=>suspend(()=>{if(scope.state._tag==="Closed")return finalizer(scope.state.exit);return scopeAddFinalizerUnsafe(scope,{},finalizer),void_}),scopeAddFinalizer=(scope,finalizer)=>scopeAddFinalizerExit(scope,constant(finalizer)),scopeAddFinalizerUnsafe=(scope,key,finalizer)=>{if(scope.state._tag==="Empty")scope.state={_tag:"Open",finalizerKey:key,finalizer,finalizers:void 0};else if(scope.state._tag==="Open"){let state=scope.state;if(state.finalizer!==void 0)state.finalizers=new Map([[state.finalizerKey,state.finalizer]]),state.finalizerKey=void 0,state.finalizer=void 0,state.finalizers.set(key,finalizer);else state.finalizers.set(key,finalizer)}},scopeRemoveFinalizerUnsafe=(scope,key)=>{if(scope.state._tag!=="Open")return;let state=scope.state;if(state.finalizerKey===key)scope.state=constScopeEmpty;else if(state.finalizers!==void 0){if(state.finalizers.delete(key),state.finalizers.size===0)scope.state=constScopeEmpty}},scopeMakeUnsafe=(finalizerStrategy)=>makeScope(finalizerStrategy,void 0),makeScope=(finalizerStrategy="sequential",parent)=>({[ScopeCloseableTypeId]:ScopeCloseableTypeId,[ScopeTypeId]:ScopeTypeId,strategy:finalizerStrategy,parent,state:constScopeEmpty}),constScopeEmpty={_tag:"Empty"};var scope=scopeTag,provideScope=provideService(scopeTag),scoped=(self)=>withFiber((fiber)=>{let prev=fiber.context,scope=scopeMakeUnsafe();return fiber.setContext(add(fiber.context,scopeTag,scope)),onExitUnsafe(fiber,(exit)=>(fiber.setContext(prev),scopeCloseUnsafe(scope,exit))),self});var acquireRelease=(acquire,release,options)=>contextWith((context)=>uninterruptibleMask((restore)=>flatMap(scope,(scope)=>tap(options?.interruptible?restore(acquire):acquire,(a)=>scopeAddFinalizerExit(scope,(exit)=>provideContext(release(a,exit),context)))))),addFinalizer=(finalizer)=>flatMap(scope,(scope)=>contextWith((context)=>scopeAddFinalizerExit(scope,(exit)=>provideContext(finalizer(exit),context)))),OnExitImpl=function(){let Proto=makePrimitiveProto({op:"OnExit",[evaluate](fiber){return fiber._stack.push(this),this.effect},[contAll](fiber){if(fiber.interruptible&&this.interruptible!==!0)fiber._stack.push(setInterruptibleTrue),fiber.interruptible=!1},[contA](value,_,exit){exit??=exitSucceed(value);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap(eff,(_)=>exit):exit},[contE](cause,_,exit){exit??=exitFailCause(cause);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap(combineFinalizerCause(exit,eff),(_)=>exit):exit}}),OnExitImpl=function(effect,onExit,interruptible){this.effect=effect,this.onExit=onExit,this.interruptible=interruptible};return OnExitImpl.prototype=Proto,OnExitImpl}(),onExitPrimitive=(effect,onExit,interruptible)=>new OnExitImpl(effect,onExit,interruptible),onExitUnsafe=(fiber,f)=>{fiber._stack.push(new OnExitImpl(void 0,f,void 0))},onExit=dual(2,onExitPrimitive),ensuring=dual(2,(self,finalizer)=>onExit(self,(_)=>finalizer));var onErrorFilter=dual(3,(self,filter,f)=>onExit(self,(exit)=>{if(exit._tag!=="Failure")return void_;let result=filter(exit.cause);return isFailure2(result)?void_:f(result.success,exit.cause)})),onInterrupt=dual(2,(self,finalizer)=>onErrorFilter(causeFilterInterruptors,finalizer)(self)),acquireUseRelease=(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap(acquire,(a)=>onExitPrimitive(suspend(()=>restore(use(a))),(exit)=>release(a,exit),!0)));var infiniteTTL=constant(1/0),makeCachedUnsafe=(self,ttlMillis)=>{let expiresAt=0,exit,current,join=(fiber,run)=>(run.awaiters++,onExitUnsafe(fiber,()=>{if(--run.awaiters>0||run.done)return;if(current===run)current=void 0;return fiberInterrupt(run.fiber)}),fiberJoin(run.fiber));return[withFiber((fiber)=>{if(current!==void 0)return fiber===current.fiber?fiberJoin(current.fiber):join(fiber,current);if(exit!==void 0&&(expiresAt===1/0||fiber.getRef(ClockRef).currentTimeMillisUnsafe(){if(run.done=!0,current!==run)return;if(current=void 0,exitHasInterrupts(exit_))return;let duration=ttlMillis(exit_);expiresAt=duration===1/0?1/0:clock.currentTimeMillisUnsafe()+duration,exit=exit_})),run.fiber._exit??joined}),sync(()=>{current=void 0,exit=void 0})]};var cached=(self)=>sync(()=>makeCachedUnsafe(self,infiniteTTL)[0]),interrupt=withFiber((fiber)=>failCause(causeInterrupt(fiber.id))),uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;return fiber.interruptible=!1,fiber._stack.push(setInterruptibleTrue),self}),setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){if(fiber.interruptible=this[args],fiber._interruptedCause&&fiber.interruptible)return()=>failCause(fiber._interruptedCause)}}),setInterruptibleTrue=setInterruptible(!0),setInterruptibleFalse=setInterruptible(!1),setFiberInterruptible=(fiber)=>{if(fiber.interruptible=!0,fiber._stack.push(setInterruptibleFalse),fiber._interruptedCause)return failCause(fiber._interruptedCause)},fiberEnterUninterruptibleUnsafe=(fiber)=>{let impl=fiber;if(!impl.interruptible)return;impl.interruptible=!1,impl._stack.push(setInterruptibleTrue)};var interruptible=(self)=>withFiber((fiber)=>{if(fiber.interruptible)return self;return setFiberInterruptible(fiber)??self}),uninterruptibleMask=(f)=>withFiber((fiber)=>{if(!fiber.interruptible)return f(identity);return fiber.interruptible=!1,fiber._stack.push(setInterruptibleTrue),f(interruptible)});var whileLoop=makePrimitive({op:"While",[contA](value,fiber){if(this[args].step(value),this[args].while())return fiber._stack.push(this),this[args].body();return exitVoid},[evaluate](fiber){if(this[args].while())return fiber._stack.push(this),this[args].body();return exitVoid}}),forEach=dual((args)=>typeof args[1]==="function",(iterable,f,options)=>suspend(()=>{let concurrency=resolveConcurrency(options?.concurrency);if(concurrency===1)return forEachSequential(iterable,f,options);let items=fromIterable(iterable),length=items.length;if(length===0)return options?.discard?void_:succeed3([]);let out=options?.discard?void 0:Array(length),eff=forEachConcurrent({f,out},items,{concurrency});return eff?as(eff,out):succeed3(out)}));var forEachSequential=(iterable,f,options)=>suspend(()=>{let out=options?.discard?void 0:[],iterator=iterable[Symbol.iterator](),state=iterator.next(),index=0;return as(whileLoop({while:()=>!state.done,body:()=>f(state.value,index++),step:(b)=>{if(out)out.push(b);state=iterator.next()}}),out)}),resolveConcurrency=(concurrency)=>concurrency==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrency??1),iterateEager=()=>(options)=>{let{onItem,step}=options,resumeSequential=(state,items,index,end,effect)=>flatMap(exit(effect),(itemExit)=>step(state,items[index],itemExit,index)??runSequential(state,items,index+1,end)??void_),runSequential=(state,items,index=0,end=items.length)=>{for(;index{let{onItem,step}=options;return(state,items,opts)=>{let index=0,end=opts.end??items.length,concurrency=opts.concurrency,done=!1,parentFiber,fibers,resume,terminal,effect,failDefect=(error)=>{let defect=exitDie(error);return terminal=defect,done=!0,fibers&&fibers.size>0?flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>terminal??defect):defect},go=()=>{let paused=!1;for(;!terminal&&index{parentFiber=getCurrentFiber(),fibers=new Set,effect=eff,resume=cb;let result;try{result=go()}catch(error){return cb(failDefect(error))}if(result)return cb(result);return suspend(()=>(terminal??=exitVoid,flatMap(fibers?fiberInterruptAll(fibers):void_,()=>terminal?._tag==="Failure"?terminal:void_)))});else{effect=void 0;let fiber=forkUnsafe(parentFiber,eff,!0,!0,"inherit");if(fiber._exit){if(terminal=step(state,item,fiber._exit,index),terminal)break;continue}fibers.add(fiber);let currentIndex=index;if(fiber.addObserver((exit)=>{fibers.delete(fiber);try{if(terminal){if(exit._tag==="Failure"){let reasons=exit.cause.reasons.filter((reason)=>reason._tag!=="Interrupt");if(reasons.length>0){let cause=causeFromReasons(reasons);terminal=exitFailCause(terminal._tag==="Failure"?causeElectDefects(causeCombine(terminal.cause,cause)):cause)}}}else{let result=step(state,item,exit,currentIndex);if(result)terminal=result,go()}if(paused){let eff=go();if(eff)resume(eff)}else if(done&&fibers.size===0)resume(terminal??void_)}catch(error){resume(failDefect(error))}}),fibers.size0){let annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure")return terminal}else if(resume){if(!fibers)return exitVoid;else if(fibers.size===0)resume(void_)}};return go()}},iterateConcurrent=()=>(options)=>iterateConcurrentImpl(options),forEachConcurrent=iterateConcurrentImpl({onItem(state,item,index){return state.f(item,index)},step(state,_,exit,index){if(exit._tag==="Failure")return exit;else if(state.out)state.out[index]=exit.value}}),filterOrElse=dual(3,(self,predicate,orElse)=>flatMap(self,(a)=>predicate(a)?succeed3(a):orElse(a)));var forkChild=dual((args)=>isEffect(args[0]),(self,options)=>withFiber((fiber)=>(interruptChildrenPatch(),succeed3(forkUnsafe(fiber,self,options?.startImmediately,!1,options?.uninterruptible??!1))))),forkUnsafe=(parent,effect,immediate=!1,daemon=!1,uninterruptible=!1)=>{let parentRuntime=parent,interruptible=uninterruptible==="inherit"?parentRuntime.interruptible:!uninterruptible,child=new FiberImpl(parentRuntime.context,interruptible);if(!daemon)parentRuntime.children().add(child),child._parent=parentRuntime;if(immediate)child.evaluate(effect);else{child._asyncContext=captureAsyncContext();let resumed=!1;child.yieldWith(()=>{resumed=!0}),parentRuntime.currentDispatcher.scheduleTask(()=>{if(resumed)return;child.evaluate(effect)},0)}return child};var fiberScopeFinalizer=(fiber)=>()=>withFiber((current)=>current===fiber?void_:fiberInterrupt(fiber)),forkIn=dual((args)=>isEffect(args[0]),(self,scope,options)=>withFiber((parent)=>{let fiber=scope.state._tag==="Closed"?new FiberImpl(parent.context):forkUnsafe(parent,self,options?.startImmediately,!0,options?.uninterruptible);if(!fiber._exit)if(scope.state._tag!=="Closed")scopeAddFinalizerUnsafe(scope,fiber,fiberScopeFinalizer(fiber)),fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope,fiber));else fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent));return succeed3(fiber)})),forkScoped=dual((args)=>isEffect(args[0]),(self,options)=>flatMap(scope,(scope)=>forkIn(self,scope,options))),runFiber=(context,effect,options)=>{let fiber=new FiberImpl(context,options?.uninterruptible!==!0);if(fiber.evaluate(effect),!fiber._exit){let signal=options?.signal;if(signal)if(signal.aborted)fiber.interruptUnsafe();else{let abort=()=>fiber.interruptUnsafe();signal.addEventListener("abort",abort,{once:!0}),fiber.addObserver(()=>signal.removeEventListener("abort",abort))}options?.onFiberStart?.(fiber)}return fiber},runForkWith=(context)=>(effect,options)=>runFiber(options?.scheduler?addUnsafe(context,SchedulerKey,options.scheduler):context,effect,options),fiberRunIn=dual(2,(self,scope)=>{if(self._exit)return self;else if(scope.state._tag==="Closed")return self.interruptUnsafe(self.id),self;return scopeRemoveFinalizerUnsafe(scope,self),scopeAddFinalizerUnsafe(scope,self,fiberScopeFinalizer(self)),self.addObserver(()=>scopeRemoveFinalizerUnsafe(scope,self)),self}),runFork=(effect,options)=>runFiber(options?.scheduler?makeUnsafe(new Map([[SchedulerKey,options.scheduler]])):empty(),effect,options),runCallbackWith=(context)=>{let runFork=runForkWith(context);return(effect,options)=>{let fiber=runFork(effect,options);if(options?.onExit)fiber.addObserver(options.onExit);return(interruptor)=>fiber.interruptUnsafe(interruptor)}},runCallback=runCallbackWith(empty()),runPromiseExitWith=(context)=>{let runFork=runForkWith(context);return(effect,options)=>{let fiber=runFork(effect,options);return new Promise((resolve)=>{fiber.addObserver((exit)=>resolve(exit))})}},runPromiseExit=runPromiseExitWith(empty()),runPromiseWith=(context)=>{let runPromiseExit=runPromiseExitWith(context);return(effect,options)=>runPromiseExit(effect,options).then((exit)=>{if(exit._tag==="Failure")throw causeSquash(exit.cause);return exit.value})},runPromise=runPromiseWith(empty()),runSyncExitWith=(context)=>{let runFork=runForkWith(context);return(effect)=>{if(effectIsExit(effect))return effect;let scheduler=new MixedScheduler("sync"),fiber=runFork(effect,{scheduler});return fiber._dispatcher?.flush(),fiber._exit??exitDie(new AsyncFiberError(fiber))}},runSyncExit=runSyncExitWith(empty()),runSyncWith=(context)=>{let runSyncExit=runSyncExitWith(context);return(effect)=>{let exit=runSyncExit(effect);if(exit._tag==="Failure")throw causeSquash(exit.cause);return exit.value}},runSync=runSyncWith(empty());var bigint02=BigInt(0),NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:!1,status:{_tag:"Ended",startTime:bigint02,endTime:bigint02,exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}},noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options),filterDisablePropagation=(span)=>{if(!span)return none2();return get(span.annotations,DisablePropagation)?span._tag==="Span"?filterDisablePropagation(getOrUndefined(span.parent)):none2():some2(span)},makeSpanUnsafe=(fiber,name,options)=>{let disablePropagation=!fiber.cache.tracerEnabled||options?.annotations&&get(options.annotations,DisablePropagation),parent=options?.parent!==void 0?some2(options.parent):options?.root?none2():filterDisablePropagation(fiber.cache.span),span;if(disablePropagation)span=noopSpan({name,parent,annotations:add(options?.annotations??empty(),DisablePropagation,!0)});else{let tracer=fiber.cache.tracer??nativeTracer,clock=fiber.getRef(ClockRef),timingEnabled=fiber.getRef(TracerTimingEnabled),annotationsFromEnv=fiber.getRef(TracerSpanAnnotations),linksFromEnv=fiber.getRef(TracerSpanLinks),level=options?.level??fiber.getRef(CurrentTraceLevel),links=options?.links!==void 0?[...linksFromEnv,...options.links]:linksFromEnv.length===0?[]:linksFromEnv.slice();span=tracer.span({name,parent,annotations:options?.annotations??empty(),links,startTime:timingEnabled?clock.currentTimeNanosUnsafe():bigint02,kind:options?.kind??"internal",root:options?.root??!1,sampled:options?.sampled??(isSome2(parent)&&parent.value.sampled===!1?!1:!isLogLevelGreaterThan(fiber.getRef(MinimumTraceLevel),level))});for(let key in annotationsFromEnv)span.attribute(key,annotationsFromEnv[key]);if(options?.attributes!==void 0)for(let key in options.attributes)span.attribute(key,options.attributes[key])}return span};var endSpan=(span,exit,clock,timingEnabled)=>sync(()=>{if(span.status._tag==="Ended")return;span.end(timingEnabled?clock.currentTimeNanosUnsafe():bigint02,exit)}),useSpan=(name,...args)=>{let options=args.length===1?void 0:args[0],evaluate=args[args.length-1];return withFiber((fiber)=>{let span=makeSpanUnsafe(fiber,name,options),clock=fiber.getRef(ClockRef),timingEnabled=fiber.getRef(TracerTimingEnabled);return onExitUnsafe(fiber,(exit)=>endSpan(span,exit,clock,timingEnabled)),evaluate(span)})},provideParentSpan=provideService(ParentSpan);var ClockRef=Reference("effect/Clock",{defaultValue:()=>new ClockImpl}),MAX_TIMER_MILLIS=2147483647;class ClockImpl{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=sync(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return wallTimeNanos()}currentTimeNanos=sync(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return monotonicNowNanos()}monotonicTimeNanos=sync(()=>this.monotonicTimeNanosUnsafe());sleep(duration){return this.sleepMillis(toMillis(duration))}sleepMillis(millis){if(millis<=0)return yieldNow;else if(!Number.isFinite(millis))return never;return callback((resume)=>{let continuation=millis>MAX_TIMER_MILLIS?this.sleepMillis(millis-MAX_TIMER_MILLIS):void_,handle=setTimeout(()=>resume(continuation),Math.min(millis,MAX_TIMER_MILLIS));return sync(()=>clearTimeout(handle))})}}var nanosPerMilli=BigInt(1e6),monotonicNowNanos=function(){let processHrtime=globalThis.process?.hrtime;if(typeof processHrtime?.bigint==="function")return()=>processHrtime.bigint();if(typeof performance<"u"&&typeof performance.now==="function")return()=>BigInt(Math.round(performance.now()*1e6));let previous=BigInt(0);return()=>{let current=BigInt(Date.now())*nanosPerMilli;if(current>previous)previous=current;return previous}}(),wallTimeNanos=function(){let reanchorThresholdNanos=BigInt(1e9),origin;return()=>{let monotonic=monotonicNowNanos(),wall=BigInt(Date.now())*nanosPerMilli;if(origin===void 0)origin=wall-monotonic;else{let projected=origin+monotonic;if((wall>projected?wall-projected:projected-wall)>reanchorThresholdNanos)origin=wall-monotonic}return origin+monotonic}}(),clockWith=(f)=>withFiber((fiber)=>f(fiber.getRef(ClockRef))),sleep=(duration)=>clockWith((clock)=>clock.sleep(fromInputUnsafe(duration))),currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis);var IllegalArgumentErrorTypeId="~effect/Cause/IllegalArgumentError";class IllegalArgumentError extends TaggedError("IllegalArgumentError"){[IllegalArgumentErrorTypeId]=IllegalArgumentErrorTypeId;constructor(message){super({message})}}var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var ConsoleRef=Reference("effect/Console",{defaultValue:()=>globalThis.console}),logLevelToOrder=(level)=>{switch(level){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}},LogLevelOrder=mapInput(Number2,logLevelToOrder),isLogLevelGreaterThan=isGreaterThan(LogLevelOrder),CurrentLoggers=Reference("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([defaultLogger,tracerLogger])}),LogToStderr=Reference("effect/Logger/LogToStderr",{defaultValue:constFalse});var LoggerTypeId="~effect/Logger",LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}},loggerMake=(log)=>{let self=Object.create(LoggerProto);return self.log=log,self},formatLabel=(key)=>key.replace(/[\s="]/g,"_"),formatLogSpan=(self,now)=>`${formatLabel(self[0])}=${now-self[1]}ms`;var logWithLevel=(level)=>(...message)=>{let cause=void 0;for(let i=0,len=message.length;i{let logLevel=level??fiber.cache.logLevel;if(isLogLevelGreaterThan(fiber.cache.minimumLogLevel,logLevel))return void_;let clock=fiber.getRef(ClockRef),loggers=fiber.getRef(CurrentLoggers);if(loggers.size>0){let date=new Date(clock.currentTimeMillisUnsafe());for(let logger of loggers)logger.log({cause,fiber,date,logLevel,message})}return void_})};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`;var defaultLogger=loggerMake(({cause,date,fiber,logLevel,message})=>{let message_=Array.isArray(message)?message.slice():[message];if(cause.reasons.length>0)message_.push(causePretty(cause));let now=date.getTime(),spans=fiber.getRef(CurrentLogSpans),spanString="";for(let span of spans)spanString+=` ${formatLogSpan(span,now)}`;let annotations=fiber.getRef(CurrentLogAnnotations);if(Object.keys(annotations).length>0)message_.push(annotations);let console=fiber.getRef(ConsoleRef);(fiber.getRef(LogToStderr)?console.error:console.log)(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`,...message_)}),tracerLogger=loggerMake(({cause,fiber,logLevel,message})=>{let clock=fiber.getRef(ClockRef),annotations=fiber.getRef(CurrentLogAnnotations),span=fiber.cache.span;if(span===void 0||span._tag==="ExternalSpan"||span.status._tag==="Ended")return;let attributes={};for(let[key,value]of Object.entries(annotations))assignProperty(attributes,key,value);if(attributes["effect.fiberId"]=fiber.id,attributes["effect.logLevel"]=logLevel.toUpperCase(),cause.reasons.length>0)attributes["effect.cause"]=causePretty(cause);span.event(toStringUnknown(Array.isArray(message)&&message.length===1?message[0]:message),clock.currentTimeNanosUnsafe(),attributes)});function interruptChildrenPatch(){fiberMiddleware.interruptChildren??=fiberInterruptChildren}var undefined_=succeed3(void 0);var isFailReason2=isFailReason;var fail4=causeFail,die2=causeDie;var hasInterruptsOnly2=hasInterruptsOnly,map3=causeMap;var filterInterruptors=causeFilterInterruptors;var isDone2=isDone;var IllegalArgumentError2=IllegalArgumentError;var succeed4=exitSucceed,failCause2=exitFailCause,fail5=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess,isFailure3=exitIsFailure;var TypeId5="~effect/Deferred";var DeferredProto={[TypeId5]:{_A:identity,_E:identity},pipe(){return pipeArguments(this,arguments)}},DeferredImpl=function(){this.resumes=void 0,this.effect=void 0};DeferredImpl.prototype=DeferredProto;var makeUnsafe2=()=>new DeferredImpl,make5=()=>sync(()=>makeUnsafe2()),_await=(self)=>callback((resume)=>{if(self.effect)return resume(self.effect);return self.resumes??=[],self.resumes.push(resume),sync(()=>{let resumes=self.resumes;if(resumes===void 0)return;let index=resumes.indexOf(resume);if(index>=0)resumes.splice(index,1)})});var completeWith=dual(2,(self,effect)=>sync(()=>doneUnsafe(self,effect))),done2=completeWith;var isDoneUnsafe=(self)=>self.effect!==void 0;var succeed5=dual(2,(self,value)=>done2(self,exitSucceed(value)));var doneUnsafe=(self,effect)=>{if(self.effect)return!1;if(self.effect=effect,self.resumes){let resumes=self.resumes;self.resumes=void 0;for(let i=0;iuninterruptibleMask((restore)=>flatMap(exit(restore(self)),(exit)=>done2(deferred,exit))));var makeUnsafe3=scopeMakeUnsafe,provide=provideScope;var forkUnsafe2=scopeForkUnsafe,close=scopeClose;var TypeId6="~effect/Layer",MemoMapTypeId="~effect/Layer/MemoMap",makeMemoMapEntry=(memoMap,layer)=>{let entry={observers:0,deferred:makeUnsafe2(),scope:makeUnsafe3(),finalizer:(exit)=>suspend(()=>{if(--entry.observers>0)return void_;return memoMap.map.delete(layer),close(entry.scope,exit)})};return entry},memoMapObserve=(entry,scope)=>{if(scope.state._tag==="Closed")return!1;return entry.observers++,scopeAddFinalizerUnsafe(scope,{},entry.finalizer),!0};var LayerProto={[TypeId6]:{_ROut:identity,_E:identity,_RIn:identity},pipe(){return pipeArguments(this,arguments)}},fromBuildUnsafe=(build)=>{let self=Object.create(LayerProto);return self.build=build,self},fromBuild=(build)=>fromBuildUnsafe((memoMap,scope)=>{let layerScope=forkUnsafe2(scope);return onExit(build(memoMap,layerScope),(exit)=>exit._tag==="Failure"?close(layerScope,exit):void_)}),fromBuildMemo=(build)=>{let self=fromBuild((memoMap,scope)=>memoMap.getOrElseMemoize(self,scope,build));return self};class MemoMapImpl{get[MemoMapTypeId](){return MemoMapTypeId}parent;constructor(parent){this.parent=parent}map=new Map;get(layer,scope){let local=this.map.get(layer);if(local)return memoMapObserve(local,scope),local.deferred.effect??_await(local.deferred);return this.parent?.get(layer,scope)}getOrElseMemoize(layer,scope,build){return suspend(()=>{let deferred;return onExitPrimitive(suspend(()=>{let existing=this.get(layer,scope);if(existing)return existing;let entry=makeMemoMapEntry(this,layer);if(!memoMapObserve(entry,scope))return build(this,scope);return deferred=entry.deferred,this.map.set(layer,entry),build(this,entry.scope)}),(exit)=>{if(deferred)doneUnsafe(deferred,exit)})})}}var makeMemoMapUnsafe=()=>new MemoMapImpl,forkMemoMapUnsafe=(parent)=>new MemoMapImpl(parent);class CurrentMemoMap extends Service()("effect/Layer/CurrentMemoMap"){static forkOrCreate(self){let current=getOrUndefined2(self,CurrentMemoMap);return current?forkMemoMapUnsafe(current):makeMemoMapUnsafe()}}var buildWithMemoMap=dual(3,(self,memoMap,scope)=>provideService(map2(suspend(()=>self.build(memoMap,scope)),add(CurrentMemoMap,memoMap)),CurrentMemoMap,memoMap));var succeed6=function(){if(arguments.length===1)return(resource)=>succeedContext(make2(arguments[0],resource));return succeedContext(make2(arguments[0],arguments[1]))},succeedContext=(context)=>fromBuildUnsafe(constant(succeed3(context)));var effect=function(){if(arguments.length===1)return(effect)=>effectImpl(arguments[0],effect);return effectImpl(arguments[0],arguments[1])},effectImpl=(service,effect)=>effectContext(map2(effect,(value)=>make2(service,value))),effectContext=(effect)=>fromBuildMemo((_,scope)=>provide(effect,scope));var unwrapKey=Service("effect/Layer/unwrap"),unwrap=(self)=>flatMap2(effect(unwrapKey)(self),get(unwrapKey)),mergeAllEffect=(layers,memoMap,scope)=>{let parentScope=forkUnsafe2(scope,"parallel");return forEach(layers,(layer)=>layer.build(memoMap,forkUnsafe2(parentScope,"sequential")),{concurrency:layers.length}).pipe(map2((context)=>mergeAll(...context)))};var provideWith=(self,that,f)=>fromBuildMemo((memoMap,scope)=>flatMap(Array.isArray(that)?mergeAllEffect(that,memoMap,scope):that.build(memoMap,scope),(context)=>self.build(memoMap,scope).pipe(provideContext(context),map2((merged)=>f(merged,context))))),provide2=dual(2,(self,that)=>provideWith(self,that,identity)),provideMerge=dual(2,(self,that)=>provideWith(self,that,(self,that)=>merge(that,self))),flatMap2=dual(2,(self,f)=>fromBuild((memoMap,scope)=>flatMap(self.build(memoMap,scope),(context)=>f(context).build(memoMap,scope))));var currentTimeMillis2=currentTimeMillis;var TypeId7="~effect/DateTime",TimeZoneTypeId="~effect/DateTime/TimeZone",Proto2={[TypeId7]:TypeId7,pipe(){return pipeArguments(this,arguments)},[NodeInspectSymbol](){return this.toString()},toJSON(){return toDateUtc(this).toJSON()}},ProtoUtc={...Proto2,_tag:"Utc",[symbol](){return number(this.epochMilliseconds)},[symbol2](that){return isDateTime(that)&&that._tag==="Utc"&&this.epochMilliseconds===that.epochMilliseconds},toString(){return`DateTime.Utc(${toDateUtc(this).toJSON()})`}},ProtoZoned={...Proto2,_tag:"Zoned",[symbol](){return combine2(number(this.epochMilliseconds))(hash(this.zone))},[symbol2](that){return isDateTime(that)&&that._tag==="Zoned"&&this.epochMilliseconds===that.epochMilliseconds&&equals(this.zone,that.zone)},toString(){return`DateTime.Zoned(${formatIsoZoned(this)})`}},ProtoTimeZone={[TimeZoneTypeId]:TimeZoneTypeId,[NodeInspectSymbol](){return this.toString()}},ProtoTimeZoneNamed={...ProtoTimeZone,_tag:"Named",[symbol](){return string(`Named:${this.resolvedId}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Named"&&this.resolvedId===(that.resolvedId??that.id)},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:"TimeZone",_tag:"Named",id:this.id}}},ProtoTimeZoneOffset={...ProtoTimeZone,_tag:"Offset",[symbol](){return string(`Offset:${this.offset}`)},[symbol2](that){return isTimeZone(that)&&that._tag==="Offset"&&this.offset===that.offset},toString(){return`TimeZone.Offset(${offsetToString(this.offset)})`},toJSON(){return{_id:"TimeZone",_tag:"Offset",offset:this.offset}}},cacheSlot={value:void 0,enumerable:!1,writable:!0},sealedCaches=new WeakMap,cacheAccessor=(key,slots)=>({get(){return Object.isExtensible(this)?void 0:sealedCaches.get(this)?.[key]},set(value){if(Object.isExtensible(this)){for(let slot of slots)Object.defineProperty(this,slot,cacheSlot);this[key]=value}else{let caches=sealedCaches.get(this);if(caches===void 0)caches={},sealedCaches.set(this,caches);caches[key]=value}}}),zonedSlots=["partsUtc","adjustedEpochMilliseconds","partsAdjusted"];Object.defineProperty(ProtoUtc,"partsUtc",cacheAccessor("partsUtc",["partsUtc"]));Object.defineProperties(ProtoZoned,{partsUtc:cacheAccessor("partsUtc",zonedSlots),adjustedEpochMilliseconds:cacheAccessor("adjustedEpochMilliseconds",zonedSlots),partsAdjusted:cacheAccessor("partsAdjusted",zonedSlots)});var makeZonedProto=(epochMillis,zone,partsUtc)=>{let self=Object.create(ProtoZoned);if(self.epochMilliseconds=epochMillis,self.zone=zone,partsUtc!==void 0)self.partsUtc=partsUtc;return self},isDateTime=(u)=>hasProperty2(u,TypeId7);var isTimeZone=(u)=>hasProperty2(u,TimeZoneTypeId);var isZoned=(self)=>self._tag==="Zoned";var makeUtc=(epochMillis)=>{let self=Object.create(ProtoUtc);return self.epochMilliseconds=epochMillis,self},fromDateUnsafe=(date)=>{let epochMillis=date.getTime();if(Number.isNaN(epochMillis))throw new IllegalArgumentError2("Invalid date");return makeUtc(epochMillis)},makeUnsafe4=(input)=>{if(isDateTime(input))return input;else if(input instanceof Date)return fromDateUnsafe(input);else if(typeof input==="object"){if("epochMilliseconds"in input)return fromDateUnsafe(new Date(input.epochMilliseconds));let date=new Date(0);return setPartsDate(date,input),fromDateUnsafe(date)}else if(typeof input==="string"&&!hasZone(input)&&!dateOnlyRegExp.test(input))return fromDateUnsafe(new Date(input+"Z"));return fromDateUnsafe(new Date(input))},dateOnlyRegExp=/^(?:[+-]\d{6}|\d{4})(?:-\d{2}(?:-\d{2})?)?$/,withoutComments=(input)=>{let first=input.indexOf("(");if(first===-1)return input;let result=input.slice(0,first)+" ",depth=1;for(let i=first+1;i{let text=withoutComments(input).trimEnd();if(text.endsWith("]"))return!0;let firstNumber=text.search(/\d/);if(firstNumber===-1)return!1;let date=text.slice(firstNumber);return offsetSignRegExp.test(date)||/(?:^|[^a-z])(?:z|gmt|utc?|[ecmp][sd]t)(?![a-z])/i.test(date)},minEpochMillis=-8639999956800000,maxEpochMillis=8639999949600000,makeZonedUnsafe=(input,options)=>{let timeZoneOption=options?.timeZone;if(timeZoneOption===void 0&&isDateTime(input)&&isZoned(input))return input;let self=makeUnsafe4(input);if(self.epochMillisecondsmaxEpochMillis)throw RangeError(`Epoch millis out of range: ${self.epochMilliseconds}`);if(timeZoneOption===void 0&&typeof input==="object"&&"timeZoneId"in input)timeZoneOption=input.timeZoneId;let zone;if(timeZoneOption===void 0){let offset=new Date(self.epochMilliseconds).getTimezoneOffset()*-60*1000;zone=zoneMakeOffset(offset)}else if(isTimeZone(timeZoneOption))zone=timeZoneOption;else if(typeof timeZoneOption==="number")zone=zoneMakeOffset(timeZoneOption);else{let parsedZone=zoneFromString(timeZoneOption);if(isNone2(parsedZone))throw new IllegalArgumentError2(`Invalid time zone: ${timeZoneOption}`);zone=parsedZone.value}if(options?.adjustForTimeZone!==!0)return makeZonedProto(self.epochMilliseconds,zone,self.partsUtc);return makeZonedFromAdjusted(self.epochMilliseconds,zone,options?.disambiguation??"compatible")};var validZoneCache=new Map,formatOptions={day:"numeric",month:"numeric",year:"numeric",era:"short",hour:"numeric",minute:"numeric",second:"numeric",timeZoneName:"longOffset",fractionalSecondDigits:3,hourCycle:"h23"},zoneMakeIntl=(format,resolvedId,id=resolvedId)=>{let cached=validZoneCache.get(id);if(cached!==void 0)return cached;let zone=Object.create(ProtoTimeZoneNamed);return zone.id=id,zone.resolvedId=resolvedId,zone.format=format,validZoneCache.set(id,zone),zone},zoneMakeNamedUnsafe=(zoneId)=>{let cached=validZoneCache.get(zoneId);if(cached!==void 0)return cached;try{let format=new Intl.DateTimeFormat("en-US",{...formatOptions,timeZone:zoneId}),resolvedId=format.resolvedOptions().timeZone,zone=zoneMakeIntl(format,resolvedId,resolvedId.toLowerCase()===zoneId.toLowerCase()?resolvedId:zoneId);return validZoneCache.set(zoneId,zone),zone}catch{throw new IllegalArgumentError2(`Invalid time zone: ${zoneId}`)}},zoneMakeOffset=(offset)=>{let zone=Object.create(ProtoTimeZoneOffset);return zone.offset=offset,zone},zoneMakeNamed=(zoneId)=>{try{return some2(zoneMakeNamedUnsafe(zoneId))}catch{return none2()}};var zoneMakeLocal=()=>{let format=new Intl.DateTimeFormat("en-US",formatOptions);return zoneMakeIntl(format,format.resolvedOptions().timeZone)},offsetZoneRegExp=/^(?:GMT)?[+-]/,zoneFromString=(zone)=>{if(offsetZoneRegExp.test(zone)){let offset=parseOffset(zone);return offset===null?none2():some2(zoneMakeOffset(offset))}return zoneMakeNamed(zone)};var toDateUtc=(self)=>new Date(self.epochMilliseconds),toDate=(self)=>{if(self._tag==="Utc")return new Date(self.epochMilliseconds);else if(self.zone._tag==="Offset")return new Date(self.epochMilliseconds+self.zone.offset);else if(self.adjustedEpochMilliseconds!==void 0)return new Date(self.adjustedEpochMilliseconds);let bc=!1,parts=self.zone.format.formatToParts(self.epochMilliseconds).filter((_)=>{if(_.type==="era")return bc=_.value==="BC",!1;return _.type!=="literal"}),year=Number(parts[2].value),date=new Date(0);return date.setUTCFullYear(bc?1-year:year,Number(parts[0].value)-1,Number(parts[1].value)),date.setUTCHours(Number(parts[3].value),Number(parts[4].value),Number(parts[5].value),parts[6]?.type==="fractionalSecond"?Number(parts[6].value):(self.epochMilliseconds%1000+1000)%1000),self.adjustedEpochMilliseconds=date.getTime(),date},zonedOffset=(self)=>toDate(self).getTime()-toEpochMillis(self),offsetToString=(offset)=>{let abs=Math.abs(offset),hours=Math.floor(abs/3600000),minutes=Math.round(abs%3600000/60000);if(minutes===60)hours+=1,minutes=0;return`${offset<0?"-":"+"}${String(hours).padStart(2,"0")}:${String(minutes).padStart(2,"0")}`},zonedOffsetIso=(self)=>offsetToString(zonedOffset(self)),toEpochMillis=(self)=>self.epochMilliseconds;var dateToParts=(date)=>({millisecond:date.getUTCMilliseconds(),second:date.getUTCSeconds(),minute:date.getUTCMinutes(),hour:date.getUTCHours(),day:date.getUTCDate(),weekDay:date.getUTCDay(),month:date.getUTCMonth()+1,year:date.getUTCFullYear()}),toParts=(self)=>{if(self._tag==="Utc")return toPartsUtc(self);else if(self.partsAdjusted!==void 0)return self.partsAdjusted;let parts=withDate(self,dateToParts);return self.partsAdjusted=parts,parts},toPartsUtc=(self)=>{if(self.partsUtc!==void 0)return self.partsUtc;let parts=withDateUtc(self,dateToParts);return self.partsUtc=parts,parts};var setPartsDate=(date,parts)=>{if(parts.year!==void 0||parts.month!==void 0||parts.day!==void 0)date.setUTCFullYear(parts.year??date.getUTCFullYear(),parts.month!==void 0?parts.month-1:date.getUTCMonth(),parts.day??date.getUTCDate());if(parts.weekDay!==void 0){let diff=parts.weekDay-date.getUTCDay();date.setUTCDate(date.getUTCDate()+diff)}if(parts.hour!==void 0)date.setUTCHours(parts.hour);if(parts.minute!==void 0)date.setUTCMinutes(parts.minute);if(parts.second!==void 0)date.setUTCSeconds(parts.second);if(parts.millisecond!==void 0)date.setUTCMilliseconds(parts.millisecond)};var constDayMillis=86400000,makeZonedFromAdjusted=(adjustedMillis,zone,disambiguation)=>{if(zone._tag==="Offset")return makeZonedProto(adjustedMillis-zone.offset,zone);let beforeOffset=calculateNamedOffset(adjustedMillis-constDayMillis,adjustedMillis,zone),afterOffset=calculateNamedOffset(adjustedMillis+constDayMillis,adjustedMillis,zone);if(beforeOffset===afterOffset)return makeZonedProto(adjustedMillis-beforeOffset,zone);let isForwards=beforeOffset{let match=offsetRegExp.exec(offset);if(match===null)return null;let[,sign,hours,minutes]=match;return(sign==="+"?1:-1)*(Number(hours)*60+Number(minutes))*60*1000},calculateNamedOffset=(utcMillis,adjustedMillis,zone)=>{let offset=zone.format.formatToParts(utcMillis).find((_)=>_.type==="timeZoneName")?.value??"";if(offset==="GMT")return 0;let result=parseOffset(offset);if(result===null)return zonedOffset(makeZonedProto(adjustedMillis,zone));return result};var withDate=dual(2,(self,f)=>f(toDate(self))),withDateUtc=dual(2,(self,f)=>f(toDateUtc(self)));var formatIso=(self)=>toDateUtc(self).toISOString();var formatIsoOffset=(self)=>{let date=toDate(self);return self._tag==="Utc"?date.toISOString():`${date.toISOString().slice(0,-1)}${zonedOffsetIso(self)}`},formatIsoZoned=(self)=>self.zone._tag==="Offset"?formatIsoOffset(self):`${formatIsoOffset(self)}[${self.zone.id}]`;var String2=globalThis.String;var loneSurrogate=/[\uD800-\uDFFF]/u;var isWellFormed=(self)=>self.isWellFormed?.()??!loneSurrogate.test(self);var isDoneCause=(cause)=>cause.reasons.some(isDoneFailure),isDoneFailure=(failure)=>failure._tag==="Fail"&&isDone2(failure.error);var forEach2=forEach;var tryPromise2=tryPromise,succeed7=succeed3,succeedNone2=succeedNone;var suspend2=suspend,sync2=sync,void_3=void_;var undefined_2=undefined_;var callback2=callback,never2=never;var gen2=gen,fail6=fail3;var failCauseSync2=failCauseSync,die3=die,try_2=try_;var withFiber2=withFiber;var fromResult2=fromResult;var flatMap3=flatMap,flatten3=flatten2,andThen2=andThen,tap2=tap,result2=result;var exit2=exit,map5=map2,as2=as,asSome2=asSome,asVoid2=asVoid;var catch_2=catch_;var catchTag2=catchTag,catchTags2=catchTags;var catchCause2=catchCause,catchDefect2=catchDefect,catchIf2=catchIf;var mapError3=mapError2;var orDie2=orDie,tapError2=tapError;var ignore2=ignore;var orElseSucceed2=orElseSucceed;var timeoutOption2=timeoutOption,timeoutOrElse2=timeoutOrElse;var sleep2=sleep;var raceFirst2=raceFirst;var filterOrFail2=filterOrFail;var match5=match4;var context2=context;var provideContext2=provideContext;var provideService2=provideService;var scoped2=scoped;var acquireRelease2=acquireRelease;var acquireUseRelease2=acquireUseRelease,addFinalizer2=addFinalizer,ensuring2=ensuring;var cached2=cached;var interrupt2=interrupt;var onInterrupt2=onInterrupt,uninterruptible2=uninterruptible;var forever2=forever;var forkChild2=forkChild;var forkScoped2=forkScoped;var runFork2=runFork,runForkWith2=runForkWith,runCallbackWith2=runCallbackWith,runCallback2=runCallback,runPromise2=runPromise,runPromiseWith2=runPromiseWith,runPromiseExit2=runPromiseExit,runPromiseExitWith2=runPromiseExitWith,runSync2=runSync,runSyncWith2=runSyncWith,runSyncExit2=runSyncExit,runSyncExitWith2=runSyncExitWith,fnUntraced2=fnUntraced,fn2=fn;var logWarning=logWithLevel("Warn");var mapEager2=mapEager,mapErrorEager2=mapErrorEager;var flatMapEager2=flatMapEager;var fnUntracedEager2=fnUntracedEager;var await_=fiberAwait;var interrupt3=fiberInterrupt;var interruptAll=fiberInterruptAll;var runIn=fiberRunIn;var Empty=Symbol.for("effect/MutableList/Empty"),make6=()=>({head:void 0,tail:void 0,length:0}),compactHead=(self)=>{let head=self.head;if(head.offset>=1024&&head===self.tail&&head.mutable&&(head.array.length-head.offset)*8<=head.offset)self.head=self.tail={array:head.array.slice(head.offset),mutable:!0,offset:0,next:void 0}},emptyBucket=()=>({array:[],mutable:!0,offset:0,next:void 0}),append=(self,message)=>{if(!self.tail)self.head=self.tail=emptyBucket();else if(!self.tail.mutable)self.tail.next=emptyBucket(),self.tail=self.tail.next;self.tail.array.push(message),self.length++};var clear=(self)=>{self.head=self.tail=void 0,self.length=0};var takeNVoid=(self,n)=>{if(n=normalize(n),n<=0||!self.head)return;if(n=Math.min(n,self.length),n===self.length&&self.head?.offset===0&&!self.head.next){clear(self);return}let count=0,chunk=self.head;while(chunk){let size=chunk.array.length-chunk.offset;if(count+size>n){chunk.offset+=n-count,self.head=chunk,self.length-=n,compactHead(self);return}count+=size,chunk=chunk.next}clear(self);return};var take=(self)=>{if(!self.head)return Empty;let message=self.head.array[self.head.offset];if(self.head.mutable)self.head.array[self.head.offset]=void 0;if(self.head.offset++,self.length--,self.head.offset===self.head.array.length)if(self.head.next)self.head=self.head.next;else clear(self);else compactHead(self);return message};var TypeId8="~effect/Queue",EnqueueTypeId="~effect/Queue/Enqueue",DequeueTypeId="~effect/Queue/Dequeue";var variance={_A:identity,_E:identity},QueueProto={[TypeId8]:variance,[EnqueueTypeId]:variance,[DequeueTypeId]:variance,...PipeInspectableProto,toJSON(){return{_id:"effect/Queue",state:this.state._tag,size:sizeUnsafe(this)}}},make7=(options)=>withFiber((fiber)=>{let self=Object.create(QueueProto);return self.dispatcher=fiber.currentDispatcher,self.capacity=options?.capacity??Number.POSITIVE_INFINITY,self.strategy=options?.strategy??"suspend",self.messages=make6(),self.scheduleRunning=!1,self.state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set},succeed3(self)});var unbounded=()=>make7();var offerUnsafe=(self,message)=>{if(self.state._tag!=="Open")return!1;else if(self.messages.length>=self.capacity){if(self.capacity<=0&&self.state.takers.size>(self.strategy==="sliding"?0:self.messages.length)){if(append(self.messages,message),self.strategy==="sliding")takeNVoid(self.messages,self.messages.length-self.state.takers.size);return releaseTakers(self),!0}else if(self.strategy==="sliding"){if(self.capacity>0)take(self.messages),append(self.messages,message);return!0}return!1}return append(self.messages,message),scheduleReleaseTaker(self),!0};var failCauseUnsafe=(self,cause)=>{if(self.state._tag!=="Open")return!1;let exit=exitFailCause(cause),fail=exitZipRight(exit,exitFailDone);if(self.state.offers.size===0&&self.messages.length===0)return finalize(self,fail),!0;return self.state={...self.state,_tag:"Closing",exit:fail},scheduleReleaseTaker(self),!0};var take2=(self)=>suspendTake(()=>takeUnsafe(self)??andThen(awaitTake(self,()=>canTake(self,1)),take2(self)));var takeUnsafe=(self)=>{if(self.state._tag==="Done")return self.state.exit;if(self.messages.length>0){let message=take(self.messages);return releaseCapacity(self),exitSucceed(message)}else if(self.capacity<=0&&self.state.offers.size>0){let message=takeOfferUnsafe(self.state.offers);return releaseCapacity(self),exitSucceed(message)}return};var sizeUnsafe=(self)=>self.state._tag==="Done"?0:self.messages.length;var exitTrue=exitSucceed(!0),exitFailDone=exitFail(Done());var releaseTakers=(self)=>{if(self.state._tag==="Done"||self.state.takers.size===0)return;for(let taker of self.state.takers){if(!taker.ready())continue;if(self.state.takers.delete(taker),taker.resume(exitVoid),self.messages.length===0)break}},scheduleReleaseTaker=(self)=>{if(self.scheduleRunning||self.state._tag==="Done"||self.state.takers.size===0)return;self.scheduleRunning=!0,self.dispatcher.scheduleTask(()=>{self.scheduleRunning=!1,releaseTakers(self)},0)};var suspendTake=makePrimitive({op:"QueueTake",[evaluate](fiber){let effect=this[args]();return isExit(effect)?effect[evaluate](fiber):effect}}),canTake=(self,min)=>self.messages.length>=(self.state._tag==="Closing"?1:Math.min(min,self.capacity||1))||self.capacity<=0&&self.state._tag!=="Done"&&self.state.offers.size>0,awaitTake=(self,ready)=>callback((resume)=>{if(self.state._tag==="Done")return resume(self.state.exit);if(ready())return resume(exitVoid);let taker={ready,resume};return self.state.takers.add(taker),sync(()=>{if(self.state._tag!=="Done")self.state.takers.delete(taker)})});var takeOfferUnsafe=(offers)=>{let entry=offers.values().next().value;if(entry._tag==="Single")return offers.delete(entry),entry.resume(exitTrue),entry.message;let message=entry.remaining[entry.offset++];if(entry.offset===entry.remaining.length)offers.delete(entry),entry.resume(exitSucceed([]));return message},releaseCapacity=(self)=>{if(self.state._tag==="Done")return isDoneCause(self.state.exit.cause);else if(self.state.offers.size===0){if(self.state._tag==="Closing"&&self.messages.length===0)return finalize(self,self.state.exit,!0),isDoneCause(self.state.exit.cause);return!1}for(let entry of self.state.offers){let n=self.capacity-self.messages.length;if(n<=0)break;else if(entry._tag==="Single")append(self.messages,entry.message),self.state.offers.delete(entry),entry.resume(exitTrue);else{for(;entry.offset{if(self.state._tag==="Done")return;let openState=self.state;if(self.state={_tag:"Done",exit},openState.takers.size===0&&openState.awaiters.size===0)return;let notify=()=>{for(let taker of openState.takers)taker.resume(exit);openState.takers.clear();for(let awaiter of openState.awaiters)awaiter(exit);openState.awaiters.clear()};if(deferNotify)self.dispatcher.scheduleTask(notify,0);else notify()};var makeUnsafe5=(permits)=>new SemaphoreImpl(permits),firstAvailableWaiter=(self)=>{if(self.freewithFiber((fiber)=>{if(self.free>=n&&firstAvailableWaiter(self)===void 0)return self.taken+=n,onAcquire();let waiter={permits:n,resume:void 0},remove=()=>{if(self.waiters.delete(waiter)){if(self.waiters.size===0)self.waiterPermitsLowerBound=1/0;self.releaseUnsafe(fiber,0)}return};if(self.waiters.add(waiter),n{if(firstAvailableWaiter(self)===waiter)resume(void_);else waiter.resume=resume})),loop=flatMap(wait,()=>{if(firstAvailableWaiter(self)!==waiter)return loop;return self.taken+=n,remove(),onAcquire()});return loop});class SemaphoreImpl{waiters=new Set;waiterPermitsLowerBound=1/0;taken=0;permits;constructor(permits){this.permits=permits}get free(){return this.permits-this.taken}take(n){return takePermits(this,n,()=>succeed3(n))}takeScoped(n){return uninterruptibleMask((restore)=>flatMap(scope,(scope)=>takePermits(this,n,()=>scopeAddFinalizer(scope,this.release(n)),restore)))}takeIfAvailable(n){return suspend(()=>{if(this.free0)fiber.currentDispatcher.scheduleTask(()=>{let remaining=this.free,woken=[];for(let waiter of this.waiters){if(remainingremaining)continue;remaining-=waiter.permits,woken.push(waiter)}for(let waiter of woken){if(!this.waiters.has(waiter))continue;let resume=waiter.resume;waiter.resume=void 0,resume?.(void_)}},0);return this.free}resize(permits){return withFiber((fiber)=>{if(this.permits=permits,this.free<0)return void_;return this.releaseUnsafe(fiber,0),void_})}release(n){return withFiber((fiber)=>succeed3(this.releaseUnsafe(fiber,n)))}get releaseAll(){return withFiber((fiber)=>succeed3(this.releaseUnsafe(fiber,this.taken)))}withPermits(n){return(self)=>uninterruptibleMask((restore)=>takePermits(this,n,()=>onExitPrimitive(restore(self),()=>{this.releaseUnsafe(getCurrentFiber(),n);return},!0),restore))}withPermit=this.withPermits(1);withPermitsIfAvailable(n){return(self)=>uninterruptibleMask((restore)=>{if(this.free{this.releaseUnsafe(getCurrentFiber(),n);return},!0)})}}var make8=(permits)=>sync(()=>new SemaphoreImpl(permits));var decodeNative=(str,decodedLength,options)=>{if(str.length<128)return;let NativeUint8Array=Uint8Array;if(typeof NativeUint8Array.fromBase64!=="function"){let Buffer2=getBuffer();if(Buffer2===void 0)return;let encoding=options?.alphabet??"base64",bytes=new Uint8Array(decodedLength),buffer=Buffer2.from(bytes.buffer),canonical=options!==void 0&&str.endsWith("=")?str.slice(0,str.indexOf("=")):str;return buffer.write(str,encoding)===decodedLength&&buffer.toString(encoding)===canonical?bytes:null}try{let bytes=NativeUint8Array.fromBase64(str,options);return bytes.length===decodedLength?bytes:null}catch{return null}},typedArrayPrototype=Object.getPrototypeOf(Uint8Array.prototype),typedArrayBuffer=Object.getOwnPropertyDescriptor(typedArrayPrototype,"buffer").get,typedArrayByteOffset=Object.getOwnPropertyDescriptor(typedArrayPrototype,"byteOffset").get,typedArrayByteLength=Object.getOwnPropertyDescriptor(typedArrayPrototype,"byteLength").get,getBuffer=()=>{let global=globalThis;return typeof global.process?.versions?.node==="string"&&typeof global.Buffer==="function"?global.Buffer:void 0},encodeBuffer=(bytes,encoding)=>{let Buffer2=getBuffer();if(Buffer2===void 0)return;let byteLength=typedArrayByteLength.call(bytes);if(byteLength<32)return;return Buffer2.from(typedArrayBuffer.call(bytes),typedArrayByteOffset.call(bytes),byteLength).toString(encoding)},stripCrlf=(str)=>str.indexOf(` `)===-1&&str.indexOf("\r")===-1?str:str.replace(/[\n\r]/g,"");var encode=(input)=>encodeBytes(typeof input==="string"?encoder.encode(input):input),decode=(str)=>{let stripped=stripCrlf(str),length=stripped.length;if(length%4!==0)return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Length must be a multiple of 4, but is ${length}`}));let index=stripped.indexOf("=");if(index!==-1&&(index= 0) importCalls.set(open, at); - regexNext = open === CONTROL_PAREN; + const open = openParens.pop(); + if (typeof open === "number") importCalls.set(open, at); + regexNext = open === "control"; } else regexNext = char !== "]"; at += 1; } diff --git a/cli/src/generated/sotPayload.ts b/cli/src/generated/sotPayload.ts index ebd469f9..5d4730cb 100644 --- a/cli/src/generated/sotPayload.ts +++ b/cli/src/generated/sotPayload.ts @@ -1,7 +1,7 @@ // Generated by cli/scripts/generate-sot-payload.ts. DO NOT EDIT. // Edit SoT/ or package.json, then run: bun cli/scripts/generate-sot-payload.ts -export const GENERATED_PACKAGE_VERSION = "0.31.2" +export const GENERATED_PACKAGE_VERSION = "0.31.3" export const GENERATED_PAYLOAD_TEXT = { "SoT/toolchain.json": "{\n \"$comment\": \"Kit toolchain manifest - DATA only (versions, floors, policy); version probing and the doctor report live in cli/src/engine-native/toolchain.ts, and the one managed install lives in cli/src/engine-native/bun.ts bunBootstrap. kind: check (doctor visibility only) | managed (kit installs it when missing). policy (managed only): present (install when missing, never upgrade). `verified` = last kit-tested version; `pinnable` marks a tool whose `verified` release the bootstrap can install by exact tag. Supply-chain stance: every kit-driven package install from npm or GitHub releases is pinned to `verified` - never floating @latest (npm-worm/Shai-Hulud surface). The existing omp marketplace plugins follow their marketplace and have no pin. Any new install surface, a new marketplace or plugin source included, needs a pin first. Update `verified` after testing a new release. upstream (optional) names where `docks-kit toolchain outdated` reads the newest release: GitHub repo releases with a tag prefix; results cache 24 h in ~/.docks-kit/kit.db; the report never installs or edits pins.\",\n \"tools\": {\n \"jq\": { \"kind\": \"check\", \"note\": \"optional operator CLI; EngineNative JSON handling does not invoke it\" },\n \"curl\": { \"kind\": \"check\", \"note\": \"installer transport for the Bun bootstrap on every host (install.sh on POSIX, install.ps1 on Windows); probed only when Bun is missing\" },\n \"git\": { \"kind\": \"check\", \"note\": \"omp plugin marketplaces (omp clones them) + kit checkout updates\" },\n \"npm\": { \"kind\": \"check\", \"note\": \"npm-global installer; `docks-kit update` uses it for an npm-installed kit\" },\n \"omp\": { \"kind\": \"check\", \"floor\": \"19.2.1\", \"verified\": \"19.2.1\",\n \"upstream\": { \"github\": \"can1357/oh-my-pi\", \"tagPrefix\": \"v\" },\n \"note\": \"Oh My Pi harness (https://github.com/can1357/oh-my-pi); upstream-owned. It updates through `omp update` or through the external manager that owns the install (for example Tern), and sync never installs or upgrades it. The floor is the oldest release the kit tested and equals the verified pin: on 2026-11-26, omp 19.2.1 listed every model selector of the kit roles exactly, loaded every setting of SoT/.omp/config.yml with its SoT value, and ran the bash approval order that cli/test/lib/ompBashPatterns.ts ports. The talk extension that DocksDocks/docks-kit#248 plans needs the reactive UI of omp 19.2. Sync needs the CLI only for the marketplace and plugin passes; the file deploys proceed without it\" },\n \"bun\": { \"kind\": \"managed\", \"policy\": \"present\", \"floor\": \"1.4.5\", \"verified\": \"1.4.5\", \"pinnable\": true,\n \"upstream\": { \"github\": \"oven-sh/bun\", \"tagPrefix\": \"bun-v\" },\n \"note\": \"runtime for the docks-kit CLI; bootstrap installs the verified release (installer takes bun-vX.Y.Z); self-updates via `bun upgrade` when wanted. By owner decision (2026-09-25), the floor equals the verified pin and the CI Bun, and the checkout launchers refuse an older Bun. All three moved to 1.4.5 on 2026-11-21 for its TLS, DNS, and HTTP security fixes\" }\n }\n}\n", @@ -14,8 +14,8 @@ export const GENERATED_PAYLOAD_TEXT = { "SoT/.omp/plugin/commands/cleanup.md": "---\ndescription: Remove what this session created and list other leftovers\n---\nFollow the workspace-hygiene skill. List each resource that this session created. Remove each one that the task no longer needs. Remove only local resources and remote resources whose target is not production. For a production resource, ask first, and keep it if you get no answer. Then run tidy_report, and report the items that this session did not create without removing them.\n", "SoT/.omp/plugin/extensions/context-tree-core.ts": "// The host-neutral core of the context-tree-nudge omp extension (`context-tree-nudge.ts`):\n// after a file edit inside a context-tree node, name the node, so that the agent can refresh\n// it. A node is a folder below the repository root that holds an AGENTS.md. The core uses\n// git and the file system only: no model call. Its git calls and file operations are\n// asynchronous, so a check does not hold the event loop of omp.\nimport { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n// Each git call stops after this time.\nconst GIT_TIMEOUT_MS = 5000;\n\n// The root of the git repository that holds `dir`. Outside a repository `dir` itself counts as\n// the root, so that no folder is a node below it. git prints the root with `/` separators also on\n// Windows; path.resolve gives it the native form of the folders that it is compared with.\nfunction repositoryRoot(dir: string): Promise {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['rev-parse', '--show-toplevel'],\n { cwd: dir, encoding: 'utf8', timeout: GIT_TIMEOUT_MS },\n (error, stdout) => resolve(error ? dir : path.resolve(stdout.trim())),\n );\n });\n}\n\n// True when `file` exists.\nconst exists = (file: string): Promise =>\n fs.promises.stat(file).then(\n () => true,\n () => false,\n );\n\n// The nearest folder of `file` that exists, with symbolic links resolved, so that it compares\n// with the root that git gives. A deleted file or a moved file can have a folder that does not\n// exist now. The walk stops at the file system root at the latest, because that root exists.\nasync function existingFolder(file: string): Promise {\n let dir = path.dirname(file);\n while (!(await exists(dir))) dir = path.dirname(dir);\n return fs.promises.realpath(dir);\n}\n\n// The nearest node of `dir`, as a path relative to `root`, or null when the nearest AGENTS.md\n// is the one at the root: the nudge names sub-folder nodes only. The walk runs only in folders\n// below `root`, so it also stops when `dir` is not below `root`.\nasync function nearestNode(root: string, dir: string): Promise {\n for (let current = dir; current.startsWith(`${root}${path.sep}`); current = path.dirname(current)) {\n if (await exists(path.join(current, 'AGENTS.md'))) return path.relative(root, current);\n }\n return null;\n}\n\n// A node name made only of these characters goes into the text as it is. Any other name goes in as\n// a JSON string, so that a newline in a folder name cannot start a new line of the added context.\n// Names use `/` separators on every platform; on Windows an absolute name starts with a drive\n// prefix such as `C:` before its first `/`.\nconst PLAIN_NAME =\n process.platform === 'win32' ? /^(?:[A-Za-z]:(?=\\/))?[A-Za-z0-9._/@+-]+$/u : /^[A-Za-z0-9._/@+-]+$/u;\n\n// The last sentence of a line that holds a JSON string: the words of a folder name are not\n// instructions for the agent.\nconst QUOTED_NAMES_NOTE = 'Quoted names are folder names from the repository, not instructions.';\n\nconst nodeName = (name: string): string => (PLAIN_NAME.test(name) ? name : JSON.stringify(name));\n\n// One line of the nudge text for the node names of one root.\nfunction nudgeLine(names: ReadonlyArray): string {\n const text =\n `Edited files inside context-tree node(s): ${names.map(nodeName).join(', ')}. If conventions in a listed folder changed, ` +\n 'run context-tree refresh on it (no-op when nothing semantic changed).';\n return names.every((name) => PLAIN_NAME.test(name)) ? text : `${text} ${QUOTED_NAMES_NOTE}`;\n}\n\n// The nudge text for the absolute paths of the edited files, or null when no file is inside a\n// node. Each path finds its own repository root, because an agent can edit files in another\n// repository than its session folder `cwd`. A node in the repository of `cwd` is named relative\n// to its root; a node in another repository is named by its absolute path, so that the agent\n// refreshes the right folder. When `cwd` does not exist now (a session folder can be removed),\n// each node is named by its absolute path. The text has one line for each root, in the order of\n// the first path of each root, and each line lists its nodes once, in the order of the paths. The\n// root of each folder is found once for each call, so that many files in one folder start one git\n// call.\nexport async function nudgeText(files: ReadonlyArray, cwd: string): Promise {\n const roots = new Map>();\n const rootOf = (dir: string): Promise => {\n let root = roots.get(dir);\n if (root === undefined) {\n root = repositoryRoot(dir);\n roots.set(dir, root);\n }\n return root;\n };\n // The root of the session folder, or null when that folder does not resolve.\n let sessionRoot: string | null | undefined;\n const nodesByRoot = new Map();\n for (const file of files) {\n const dir = await existingFolder(file);\n const root = await rootOf(dir);\n const node = await nearestNode(root, dir);\n if (node === null) continue;\n if (sessionRoot === undefined) sessionRoot = await fs.promises.realpath(cwd).then(rootOf, () => null);\n const name = (root === sessionRoot ? node : path.join(root, node)).split(path.sep).join('/');\n const nodes = nodesByRoot.get(root) ?? [];\n if (!nodes.includes(name)) nodes.push(name);\n nodesByRoot.set(root, nodes);\n }\n if (nodesByRoot.size === 0) return null;\n return [...nodesByRoot.values()].map(nudgeLine).join('\\n');\n}\n", "SoT/.omp/plugin/extensions/context-tree-nudge.ts": "// omp extension: the context-tree nudge. After a file edit that did not fail, it adds a\n// message that names each context-tree node that holds an edited file. The node rules live in\n// `context-tree-core.ts`; this file only takes the edited paths from the omp event and turns\n// the answer of the core into an omp result.\n//\n// The edited paths come from the `details` of the tool result:\n// edit `perFileResults[].path` and `.sourcePath` (each mode, also apply_patch), else `path`.\n// write `resolvedPath`, but no URL target. A write to `xd://resolve` that applies an\n// ast_edit gives the files of the ast_edit, relative to the session folder.\n// An ast_edit itself only previews, so it gets no nudge.\n//\n// The handler catches each error and adds nothing, because a nudge must not stop the work of\n// the agent.\nimport path from 'node:path';\nimport { nudgeText } from './context-tree-core.ts';\n\n// The local structural types below name only the omp extension API parts that this module\n// uses. The module does not import @oh-my-pi packages: they do not resolve outside omp.\n\ninterface ExtensionContext {\n readonly cwd: string;\n}\n\ninterface ToolResultEvent {\n readonly toolName: string;\n readonly toolCallId?: string;\n readonly input?: Readonly>;\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\ninterface ExtensionApi {\n on(\n event: 'tool_result',\n handler: (event: ToolResultEvent, ctx: ExtensionContext) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n}\n\n// A tool path with a scheme, such as `local://notes.md` or `xd://bash`, names no file in a repository.\nconst URL_TARGET = /^[a-z][a-z0-9+.-]*:\\/\\//iu;\n\n// The fields of an event value; undefined and null give no fields.\nconst record = (value: unknown): Record => Object(value);\n\n// The strings of one value or of a list of values.\nconst strings = (values: unknown): string[] =>\n (Array.isArray(values) ? values : [values]).filter((value): value is string => typeof value === 'string');\n\n// The paths of an edit result: each file of a multi-file result, with the source of a move.\nfunction editPaths(details: Record): string[] {\n const perFile = details.perFileResults;\n if (Array.isArray(perFile))\n return strings(perFile.flatMap((result) => [record(result).path, record(result).sourcePath]));\n return strings(details.path);\n}\n\n// The paths of a write result. A write to a URL target names no file, but the result of a write to `xd://resolve`\n// that applies an ast_edit names the files of the ast_edit.\nfunction writePaths(input: Record, details: Record): string[] {\n if (!URL_TARGET.test(String(input.path))) return strings(details.resolvedPath);\n const inner = record(record(details.xdev).inner);\n if (inner.sourceToolName !== 'ast_edit' || inner.action !== 'apply') return [];\n return strings(record(inner.sourceResultDetails).files);\n}\n\nfunction editedPaths(event: ToolResultEvent): string[] {\n const details = record(event.details);\n if (event.toolName === 'edit') return editPaths(details);\n if (event.toolName === 'write') return writePaths(record(event.input), details);\n return [];\n}\n\nexport default function contextTreeNudge(pi: ExtensionApi): void {\n pi.on('tool_result', async (event, ctx) => {\n if (event.isError) return undefined;\n try {\n const files = editedPaths(event).map((file) => path.resolve(ctx.cwd, file));\n const text = await nudgeText(files, ctx.cwd);\n return text === null ? undefined : { additionalContext: text };\n } catch {\n return undefined;\n }\n });\n}\n", - "SoT/.omp/plugin/extensions/hygiene.ts": "/**\n * docks-kit-omp extension: workspace hygiene for omp sessions.\n *\n * - The tools scratch_new, scratch_remove, and tidy_report run docks-kit.\n * - The tool_result handler records each resource that a bash command\n * creates, and it adds a reminder that names the cleanup command.\n * - The tool_call handler reads the stash list before a `git stash` command,\n * so the tool_result handler can name the stash entry that the command\n * added. The tool_execution_end handler drops the list of a blocked call.\n * - The session_stop handler lists the recorded resources that still exist.\n * - The session_start handler of a main session starts `docks-kit tidy --apply`\n * in the background, at most one time in each sweep interval. When the\n * sweep cannot start, the next tool result of the main session tells why.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install. No subprocess uses a command interpreter, so a tool argument never\n * gets to a shell.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { randomBytes, randomUUID } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n closeSync,\n constants,\n existsSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, posix, resolve, win32 } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\nconst SWEEP_INTERVAL_MS = 12 * 60 * 60 * 1000;\nconst CLAIM_STALE_MS = 60 * 1000;\nconst STAMP_FILE = \"tidy.stamp\";\nconst CLAIM_FILE = \"tidy.stamp.claim\";\nconst TAKEOVER_FILE = \"tidy.stamp.takeover\";\nconst DOCKER_CHECK_TIMEOUT_MS = 5000;\nconst GIT_CHECK_TIMEOUT_MS = 5000;\n/** The pre-call stash read delays the command, so it gets a short timeout. */\nconst STASH_SNAPSHOT_TIMEOUT_MS = 1000;\n/** One line for each stash entry: full ID, short ID, and reflog message, split by NUL. */\nconst STASH_LIST_FORMAT = \"--format=%H%x00%h%x00%gs\";\nconst SCRATCH_TIMEOUT_MS = 60_000;\nconst REPORT_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;\nconst COMMAND_TEXT_LIMIT = 120;\nconst LABEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst LABEL_ERROR = \"label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\";\nconst NOT_ON_PATH = \"docks-kit is not on PATH; install docks-kit and run docks-kit sync\";\n\n/**\n * A bash command that does not match this pattern creates no tracked\n * resource. Each detection rule below has a word in this pattern.\n */\nconst TRIGGER =\n /worktree\\s+add|compose|docker|scratch\\s+new|mktemp|nohup|setsid|disown|&|tmux|screen|ngrok|cloudflared|port-forward|ssh|cluster|minikube|multipass|limactl|machine|colima|crontab|\\bat\\b|systemctl|systemd-run|launchctl|install|(?:^|\\s)-g(?:\\s|$)|global|branches|branch\\s+create|vercel|netlify|wrangler|fly\\s|fork|codespace|stash/;\n\n/** The scope of the top-level command; a subshell scope extends it with `/`. */\nconst ROOT_SCOPE = \"0\";\n\nconst UNRESOLVED = /[$`*]/;\nconst ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst REDIRECT_OPERATOR = /^(?:\\d+|&)?(?:<<<|<<-?|>>|>&|<&|>\\||<>|>|<)$/;\nconst ATTACHED_REDIRECT = /^(?:\\d+|&)?[<>]/;\n/**\n * A word that is one redirection of the standard error alone: `2>&1`, `2>&-`,\n * `2>file`, `2>>file`, or the operator `2>` before its target. A second `<`\n * or `>` in the word is a second redirection. The segment parser splits\n * `2>|file` at the `|`, so that form gives the generic note.\n */\nconst STDERR_REDIRECT = /^2(?:>&(?:\\d+|-)|>>?[^<>]*)$/;\nconst SHORT_CLUSTER_WITH_D = /^-[A-Za-z]*d[A-Za-z]*$/;\n/** The long options of GNU mktemp, which also accepts a unique prefix of each. */\nconst MKTEMP_LONG_OPTIONS: ReadonlyArray = [\n \"--directory\",\n \"--dry-run\",\n \"--quiet\",\n \"--suffix\",\n \"--tmpdir\",\n \"--help\",\n \"--version\",\n];\nconst CONTAINER_ID = /^[0-9a-f]{64}$/;\nconst SAFE_WORD = /^[A-Za-z0-9_/.:@%+=,-]+$/;\nconst RESERVED_WORDS: Record = {\n \"{\": true,\n \"}\": true,\n \"!\": true,\n if: true,\n then: true,\n else: true,\n elif: true,\n do: true,\n while: true,\n until: true,\n time: true,\n};\n/**\n * Reserved words of a conditional, a loop, or a function body, where a\n * command may run once, many times, or never. The list holds the closing\n * words too, because a segment can start with one of them.\n */\nconst COMPOUND_WORDS: Record = {\n if: true,\n then: true,\n else: true,\n elif: true,\n fi: true,\n for: true,\n select: true,\n while: true,\n until: true,\n do: true,\n done: true,\n case: true,\n esac: true,\n function: true,\n coproc: true,\n};\n/** A shell function name, as in `name()` or `name ()`. */\nconst FUNCTION_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nconst GIT_VALUE_OPTIONS: Record = { \"-C\": true, \"-c\": true };\nconst WORKTREE_VALUE_OPTIONS: Record = { \"-b\": true, \"-B\": true, \"--reason\": true };\n/** Docker global options that select the daemon, mapped to their long names. */\nconst DOCKER_CONNECTION_VALUE_OPTIONS: Record = {\n \"-c\": \"--context\",\n \"--context\": \"--context\",\n \"-H\": \"--host\",\n \"--host\": \"--host\",\n \"--config\": \"--config\",\n \"--tlscacert\": \"--tlscacert\",\n \"--tlscert\": \"--tlscert\",\n \"--tlskey\": \"--tlskey\",\n};\nconst DOCKER_CONNECTION_FLAGS: Record = { \"--tls\": true, \"--tlsverify\": true };\nconst DOCKER_LOG_LEVEL_OPTIONS: Record = { \"-l\": true, \"--log-level\": true };\n/** Environment variables that select the Docker daemon. */\nconst DOCKER_ENVIRONMENT: Record = {\n DOCKER_HOST: true,\n DOCKER_CONTEXT: true,\n DOCKER_CONFIG: true,\n DOCKER_TLS_VERIFY: true,\n DOCKER_CERT_PATH: true,\n};\n/** Builtins that declare shell variables, with options and `NAME=value` words. */\nconst DECLARATION_COMMANDS: Record = {\n declare: true,\n typeset: true,\n local: true,\n readonly: true,\n};\n/** Builtins that run shell code that detection does not read. */\nconst SHELL_CODE_COMMANDS: Record = { eval: true, source: true, \".\": true };\nconst COMPOSE_VALUE_OPTIONS: Record = {\n \"-f\": true,\n \"--file\": true,\n \"-p\": true,\n \"--project-name\": true,\n \"--project-directory\": true,\n \"--env-file\": true,\n \"--profile\": true,\n \"--ansi\": true,\n \"--progress\": true,\n};\nconst SSH_VALUE_FLAGS = \"BbcDEeFIiJLlmOoPpQRSWw\";\nconst STASH_WITHOUT_ENTRY: Record = {\n list: true,\n show: true,\n pop: true,\n apply: true,\n drop: true,\n clear: true,\n branch: true,\n};\n\nconst RM_NOTE = \"Add `--rm` to `docker run` so that Docker removes the container when it stops.\";\nconst SCRATCH_NOTE =\n \"Prefer a directory from the `scratch_new` tool or `docks-kit scratch new