From 7f3b6a3a49e7fc460863360d206f79331660addc Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:37:26 -0300 Subject: [PATCH 1/7] Add the --fast and --ultrafast root flags - Move the tier toggle and its lock path from the omp command to a new root command module, and accept both flags at the root of the CLI. - Refuse both flags together before any lock or write. - Move the in-process lock tests to the root command and add spawned tests of the public CLI. Refs #283 Verified: bunx vitest run cli/test/unit/rootFlags.test.ts cli/test/unit/ompFastMode.test.ts cli/test/unit/argv.test.ts cli/test/unit/ompCommand.test.ts; bun run check:types; bun run lint; bun run format --- cli/src/argv.ts | 5 +- cli/src/argvSurface.ts | 13 +- cli/src/commands/omp.ts | 103 +------------- cli/src/commands/root.ts | 133 +++++++++++++++++++ cli/src/engine-native/ompFastMode.ts | 2 +- cli/src/main.ts | 43 +----- cli/test/unit/argv.test.ts | 7 + cli/test/unit/ompFastMode.test.ts | 50 +++---- cli/test/unit/rootFlags.test.ts | 192 +++++++++++++++++++++++++++ 9 files changed, 366 insertions(+), 182 deletions(-) create mode 100644 cli/src/commands/root.ts create mode 100644 cli/test/unit/rootFlags.test.ts diff --git a/cli/src/argv.ts b/cli/src/argv.ts index 2761ea1ec..60c1519cd 100644 --- a/cli/src/argv.ts +++ b/cli/src/argv.ts @@ -9,6 +9,7 @@ import { tidyCommand } from "./commands/tidy"; import { planCommand } from "./commands/plan"; import { agentDocsCommand } from "./commands/agentDocs"; import { skillCommand } from "./commands/skill"; +import { rootCommand } from "./commands/root"; import { buildSurfaces, normalizeArgv, @@ -40,7 +41,7 @@ export const COMMANDS = [ skillCommand, ] as const; -const SURFACES: ArgvSurfaces = buildSurfaces(COMMANDS, GlobalFlag.BuiltIns); +const SURFACES: ArgvSurfaces = buildSurfaces(rootCommand, COMMANDS, GlobalFlag.BuiltIns); const reject = (message: string): ArgvOutcome => ({ kind: "reject", @@ -75,7 +76,7 @@ export const prepareArgv = (args: ReadonlyArray): ArgvOutcome => { const boundaryArgs = passthroughBoundary(args); const subcommand = subcommandName(boundaryArgs); const commandSurface = - subcommand === undefined ? undefined : SURFACES.commandSurfaces.get(subcommand); + subcommand === undefined ? SURFACES.rootSurface : SURFACES.commandSurfaces.get(subcommand); const { flags, normalizations } = scanArgv(boundaryArgs, commandSurface, SURFACES); const message = validateScannedArgv(subcommand, commandSurface, SURFACES, flags); if (message !== undefined) return reject(message); diff --git a/cli/src/argvSurface.ts b/cli/src/argvSurface.ts index 572504669..a9c961030 100644 --- a/cli/src/argvSurface.ts +++ b/cli/src/argvSurface.ts @@ -22,6 +22,8 @@ export interface CommandValue { } export interface ArgvSurfaces { + /** The flags of the root command, which apply only when no subcommand is given. */ + readonly rootSurface: FlagSurface; readonly commandSurfaces: ReadonlyMap; readonly globalSurface: GlobalFlagSurface; } @@ -141,6 +143,7 @@ const globalSurface = (builtIns: unknown): GlobalFlagSurface => { }; export const buildSurfaces = ( + root: CommandValue, commands: ReadonlyArray, builtIns: unknown, ): ArgvSurfaces => { @@ -150,7 +153,11 @@ export const buildSurfaces = ( const commandSurfaces: ReadonlyMap = new Map( commands.map((command) => [command.name, buildCommandSurface(command)]), ); - return { commandSurfaces, globalSurface: globalSurface(builtIns) }; + return { + rootSurface: buildCommandSurface(root), + commandSurfaces, + globalSurface: globalSurface(builtIns), + }; }; const flagNameOf = (token: string): string => { @@ -174,7 +181,7 @@ const declaredFlagName = ( const declaredInAnySurface = (name: string, surfaces: ArgvSurfaces): boolean => { if (canonicalFlagName(name, surfaces.globalSurface) !== undefined) return true; - for (const surface of surfaces.commandSurfaces.values()) { + for (const surface of [surfaces.rootSurface, ...surfaces.commandSurfaces.values()]) { if (canonicalFlagName(name, surface) !== undefined) return true; } return false; @@ -184,7 +191,7 @@ const takesValueInAnySurface = (name: string, surfaces: ArgvSurfaces): boolean = const globalName = canonicalFlagName(name, surfaces.globalSurface); if (globalName !== undefined && surfaces.globalSurface.valueFlags.includes(globalName)) return true; - for (const surface of surfaces.commandSurfaces.values()) { + for (const surface of [surfaces.rootSurface, ...surfaces.commandSurfaces.values()]) { const canonicalName = canonicalFlagName(name, surface); if (canonicalName !== undefined && surface.valueFlags.includes(canonicalName)) return true; } diff --git a/cli/src/commands/omp.ts b/cli/src/commands/omp.ts index 4b1eb6849..172af5112 100644 --- a/cli/src/commands/omp.ts +++ b/cli/src/commands/omp.ts @@ -21,17 +21,6 @@ import { renderFreeOverlay, type CatalogModel, } from "../engine-native/ompOverlay"; -import { - FAST_ON_TIER, - requireDeployedConfig, - toggleDeployedOpenAiTier, - ULTRAFAST_ON_TIER, - type FastToggle, - type OpenAiOnTier, -} from "../engine-native/ompFastMode"; -import { ompPaths } from "../engine-native/ompPaths"; -import { ExitError } from "../engine-native/parseArgs"; -import { withHomeAndFolderLocks } from "../engine-native/syncDispatch"; const model = Flag.String("model").pipe( Flag.withDescription("Free model selector to use and remember for omp sessions"), @@ -41,27 +30,6 @@ const pick = Flag.Boolean("pick").pipe( Flag.withDescription("Choose the free model interactively"), Flag.withDefault(false), ); -const fast = Flag.Boolean("fast").pipe( - Flag.withDescription( - "Toggle fast mode (tier.openai priority/none) for OpenAI and Codex models in the deployed omp config, then exit", - ), - Flag.withDefault(false), -); -const ultrafast = Flag.Boolean("ultrafast").pipe( - Flag.withDescription( - "Toggle ultrafast mode (tier.openai ultrafast/none) for OpenAI and Codex models in the deployed omp config, then exit", - ), - Flag.withDefault(false), -); - -/** The flag name and the omp slash command of each tier that a toggle turns on. */ -const TIER_MODES: Readonly< - Record -> = { - [FAST_ON_TIER]: { name: "fast", slash: "/fast on|off" }, - [ULTRAFAST_ON_TIER]: { name: "ultrafast", slash: "/fast ultra|off" }, -}; - const args: Argument.Argument> = Argument.String("args").pipe( Argument.withDescription("Arguments forwarded verbatim to omp"), Argument.variadic(), @@ -241,55 +209,7 @@ const pickLevel = (catalogModel: CatalogModel) => }); }); -/** - * Toggle `tier.openai` to or from `onTier` under the sync lock of `home` and - * the folder lock of the omp agent folder, with the wait and the held line of - * a sync. A sync also merges `config.yml` there. Return 0 after the toggle, 1 - * for a held lock, and 2 for a failed toggle or an invalid wait bound. - */ -async function toggleTierUnderLocks( - home: string, - agentDir: string, - onTier: OpenAiOnTier, -): Promise { - const configPath = p(agentDir, "config.yml"); - const err = (line: string) => console.error(line); - // Check config.yml before any lock. A missing file ends the run before the - // lock step can create the agent folder, and a folder that a sync creates - // during the home lock wait is never toggled without its folder lock. - try { - requireDeployedConfig(configPath); - } catch (error) { - err(error instanceof Error ? error.message : String(error)); - return 2; - } - try { - return await withHomeAndFolderLocks(home, [agentDir], err, async () => { - let toggle: FastToggle; - try { - toggle = toggleDeployedOpenAiTier(configPath, onTier); - } catch (error) { - err(error instanceof Error ? error.message : String(error)); - return 2; - } - const mode = TIER_MODES[onTier]; - const state = toggle.next === onTier ? "ON" : "OFF"; - console.log( - `omp ${mode.name} mode ${state} for OpenAI/Codex models: tier.openai ${toggle.previous} -> ${toggle.next} in ${configPath}`, - ); - console.log( - `New omp sessions use it; in a running session, use ${mode.slash} or restart omp.`, - ); - return 0; - }); - } catch (error) { - // An invalid DOCKS_KIT_SYNC_LOCK_WAIT_MS prints its error line, then throws ExitError(2). - if (error instanceof ExitError) return error.code; - throw error; - } -} - -export const ompCommand = Command.make("omp", { model, pick, fast, ultrafast, args }, (config) => +export const ompCommand = Command.make("omp", { model, pick, args }, (config) => Effect.gen(function* () { // Check the forwarded arguments before omp, the catalog, or kit.db, so a // rejected launch starts no process and writes nothing. @@ -300,27 +220,6 @@ export const ompCommand = Command.make("omp", { model, pick, fast, ultrafast, ar return yield* bail("Pass either --model or --pick, not both"); } - if (config.fast || config.ultrafast) { - const onTier = config.ultrafast ? ULTRAFAST_ON_TIER : FAST_ON_TIER; - const name = TIER_MODES[onTier].name; - const others = - Option.isSome(config.model) || - config.pick || - config.args.length > 0 || - (config.fast && config.ultrafast); - if (others) { - return yield* bail(`--${name} toggles ${name} mode and exits; pass it alone`); - } - const home = engineHome(process.env); - const agentDir = ompPaths({ home, env: process.env, platform: process.platform }).agentDir; - const code = yield* Effect.tryPromise({ - try: () => toggleTierUnderLocks(home, agentDir, onTier), - catch: (error) => (error instanceof Error ? error.message : String(error)), - }).pipe(Effect.catch((message) => bail(message))); - if (code !== 0) return yield* Effect.sync(() => process.exit(code)); - return; - } - const omp = yield* Effect.sync(() => which("omp")); if (omp === "") { return yield* bail("omp not found on PATH; install omp, then retry", 1); diff --git a/cli/src/commands/root.ts b/cli/src/commands/root.ts new file mode 100644 index 000000000..0fe13933f --- /dev/null +++ b/cli/src/commands/root.ts @@ -0,0 +1,133 @@ +/** + * The `docks-kit` root command without its subcommands: the command summary + * and the two root flags `--fast` and `--ultrafast`, which toggle omp's + * OpenAI service tier in the deployed config.yml. `main.ts` adds the + * subcommands; `argv.ts` derives the root flag surface from this value. + */ +import { Command, Flag } from "effect/cli"; +import { Console, Effect } from "effect"; + +import { bail } from "../engine"; +import { p } from "../engine-native/exec"; +import { engineHome } from "../engine-native/ompSession"; +import { + FAST_ON_TIER, + requireDeployedConfig, + toggleDeployedOpenAiTier, + ULTRAFAST_ON_TIER, + type FastToggle, + type OpenAiOnTier, +} from "../engine-native/ompFastMode"; +import { ompPaths } from "../engine-native/ompPaths"; +import { ExitError } from "../engine-native/parseArgs"; +import { withHomeAndFolderLocks } from "../engine-native/syncDispatch"; + +const fast = Flag.Boolean("fast").pipe( + Flag.withDescription( + "Toggle fast mode (tier.openai priority/none) for OpenAI and Codex models in the deployed omp config, then exit", + ), + Flag.withDefault(false), +); +const ultrafast = Flag.Boolean("ultrafast").pipe( + Flag.withDescription( + "Toggle ultrafast mode (tier.openai ultrafast/none) for OpenAI and Codex models in the deployed omp config, then exit", + ), + Flag.withDefault(false), +); + +/** The flag name and the omp slash command of each tier that a toggle turns on. */ +const TIER_MODES: Readonly< + Record +> = { + [FAST_ON_TIER]: { name: "fast", slash: "/fast on|off" }, + [ULTRAFAST_ON_TIER]: { name: "ultrafast", slash: "/fast ultra|off" }, +}; + +const SUMMARY: ReadonlyArray = [ + "docks-kit — portable AI coding agent config kit", + "", + " docks-kit sync [--dry-run] deploy the SoT to this machine", + " docks-kit update [--no-sync] self-update the kit, then sync", + " docks-kit toolchain [check|ensure|outdated] verified-version floors", + " docks-kit docs [topic] self-documentation", + " docks-kit --fast | --ultrafast toggle omp fast or ultrafast mode for OpenAI/Codex models", + " docks-kit scratch new|remove agent temporary files and directories", + " docks-kit tidy [--apply] [--repo ] [--report] remove safe agent leftovers", + " docks-kit plan [...] GitHub-issue plan records (plan-manager helper)", + " docks-kit agent-docs [...] agent-doc checks (agent-first-setup helpers)", + " docks-kit skill guard|score [...] SKILL.md validator and rubric score (write-skill helpers)", + "", + "Run 'docks-kit --help' for full option listings (also: --wizard, --completions).", +]; + +/** + * Toggle `tier.openai` to or from `onTier` under the sync lock of `home` and + * the folder lock of the omp agent folder, with the wait and the held line of + * a sync. A sync also merges `config.yml` there. Return 0 after the toggle, 1 + * for a held lock, and 2 for a failed toggle or an invalid wait bound. + */ +async function toggleTierUnderLocks( + home: string, + agentDir: string, + onTier: OpenAiOnTier, +): Promise { + const configPath = p(agentDir, "config.yml"); + const err = (line: string) => console.error(line); + // Check config.yml before any lock. A missing file ends the run before the + // lock step can create the agent folder, and a folder that a sync creates + // during the home lock wait is never toggled without its folder lock. + try { + requireDeployedConfig(configPath); + } catch (error) { + err(error instanceof Error ? error.message : String(error)); + return 2; + } + try { + return await withHomeAndFolderLocks(home, [agentDir], err, async () => { + let toggle: FastToggle; + try { + toggle = toggleDeployedOpenAiTier(configPath, onTier); + } catch (error) { + err(error instanceof Error ? error.message : String(error)); + return 2; + } + const mode = TIER_MODES[onTier]; + const state = toggle.next === onTier ? "ON" : "OFF"; + console.log( + `omp ${mode.name} mode ${state} for OpenAI/Codex models: tier.openai ${toggle.previous} -> ${toggle.next} in ${configPath}`, + ); + console.log( + `New omp sessions use it; in a running session, use ${mode.slash} or restart omp.`, + ); + return 0; + }); + } catch (error) { + // An invalid DOCKS_KIT_SYNC_LOCK_WAIT_MS prints its error line, then throws ExitError(2). + if (error instanceof ExitError) return error.code; + throw error; + } +} + +export const rootCommand = Command.make("docks-kit", { fast, ultrafast }, (config) => + Effect.gen(function* () { + if (config.fast && config.ultrafast) { + return yield* bail("Pass either --fast or --ultrafast, not both"); + } + if (!config.fast && !config.ultrafast) { + for (const line of SUMMARY) yield* Console.log(line); + return; + } + const onTier = config.ultrafast ? ULTRAFAST_ON_TIER : FAST_ON_TIER; + const home = engineHome(process.env); + const agentDir = ompPaths({ home, env: process.env, platform: process.platform }).agentDir; + const code = yield* Effect.tryPromise({ + try: () => toggleTierUnderLocks(home, agentDir, onTier), + catch: (error) => (error instanceof Error ? error.message : String(error)), + }).pipe(Effect.catch((message) => bail(message))); + if (code !== 0) return yield* Effect.sync(() => process.exit(code)); + }), +).pipe( + Command.withDescription( + "Portable AI coding agent config kit — SoT sync engine + helpers for Oh My Pi. --fast toggles OpenAI/Codex fast mode in the deployed omp config and exits; --ultrafast does the same for ultrafast mode.", + ), +); diff --git a/cli/src/engine-native/ompFastMode.ts b/cli/src/engine-native/ompFastMode.ts index 36a9a933d..f76866e11 100644 --- a/cli/src/engine-native/ompFastMode.ts +++ b/cli/src/engine-native/ompFastMode.ts @@ -1,5 +1,5 @@ /** - * `docks-kit omp --fast` and `docks-kit omp --ultrafast` toggle omp's OpenAI + * `docks-kit --fast` and `docks-kit --ultrafast` toggle omp's OpenAI * service tier in the deployed config.yml. `tier.openai: priority` is what * omp's `/fast on` selects for OpenAI and OpenAI-Codex models, `ultrafast` is * what `/fast ultra` selects, and `none` omits `service_tier`. The SoT does not diff --git a/cli/src/main.ts b/cli/src/main.ts index 4c344a050..a81e305b4 100755 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -1,51 +1,14 @@ #!/usr/bin/env bun import { Command, CliOutput } from "effect/cli"; import { BunRuntime, BunServices } from "@effect/platform-bun"; -import { Console, Effect, Layer } from "effect"; +import { Effect, Layer } from "effect"; import { EngineServicesLive } from "./services"; import { GENERATED_PACKAGE_VERSION } from "./generated/sotPayload"; import { COMMANDS, prepareArgv } from "./argv"; +import { rootCommand } from "./commands/root"; import { runEngineNative } from "./engine-native"; -const root = Command.make("docks-kit", {}, () => - Effect.gen(function* () { - yield* Console.log("docks-kit — portable AI coding agent config kit"); - yield* Console.log(""); - yield* Console.log( - " docks-kit sync [--dry-run] deploy the SoT to this machine", - ); - yield* Console.log( - " docks-kit update [--no-sync] self-update the kit, then sync", - ); - yield* Console.log(" docks-kit toolchain [check|ensure|outdated] verified-version floors"); - yield* Console.log(" docks-kit docs [topic] self-documentation"); - yield* Console.log(" docks-kit omp [--model|--pick] [...] free-model omp session"); - yield* Console.log( - " docks-kit scratch new|remove agent temporary files and directories", - ); - yield* Console.log( - " docks-kit tidy [--apply] [--repo ] [--report] remove safe agent leftovers", - ); - yield* Console.log( - " docks-kit plan [...] GitHub-issue plan records (plan-manager helper)", - ); - yield* Console.log( - " docks-kit agent-docs [...] agent-doc checks (agent-first-setup helpers)", - ); - yield* Console.log( - " docks-kit skill guard|score [...] SKILL.md validator and rubric score (write-skill helpers)", - ); - yield* Console.log(""); - yield* Console.log( - "Run 'docks-kit --help' for full option listings (also: --wizard, --completions).", - ); - }), -).pipe( - Command.withDescription( - "Portable AI coding agent config kit — SoT sync engine + helpers for Oh My Pi.", - ), - Command.withSubcommands(COMMANDS), -); +const root = rootCommand.pipe(Command.withSubcommands(COMMANDS)); // v4's default formatter renders `name vversion`, but the `docks-kit` launcher // compares `--version` against the bare `package.json` version. The CLI output diff --git a/cli/test/unit/argv.test.ts b/cli/test/unit/argv.test.ts index cbc3331e4..84719df38 100644 --- a/cli/test/unit/argv.test.ts +++ b/cli/test/unit/argv.test.ts @@ -171,6 +171,13 @@ describe("argument validation", () => { }); }); + it.each([[["--fast"]], [["--ultrafast"]]] as const)( + "accepts the root tier flag %j without a subcommand", + (input) => { + expect(prepareArgv(input)).toEqual({ kind: "accept", args: input }); + }, + ); + it.each([ [ "rejects an unknown subcommand before blaming one of its flags", diff --git a/cli/test/unit/ompFastMode.test.ts b/cli/test/unit/ompFastMode.test.ts index 35914ad3b..1d893e71d 100644 --- a/cli/test/unit/ompFastMode.test.ts +++ b/cli/test/unit/ompFastMode.test.ts @@ -18,7 +18,7 @@ import { join } from "node:path"; import { setTimeout as sleepMs } from "node:timers/promises"; import { parse } from "yaml"; -import { ompCommand } from "../../src/commands/omp"; +import { rootCommand } from "../../src/commands/root"; import { acquireKitLock, releaseKitLock, type KitLock } from "../../src/engine-native/kitLock"; import { FAST_ON_TIER, @@ -46,7 +46,7 @@ advisor: enabled: true `; -/** The toggle of `docks-kit omp --fast`. */ +/** The toggle of `docks-kit --fast`. */ const toggleFast = (text: string) => toggleOpenAiTier(text, FAST_ON_TIER); describe("toggleOpenAiTier with priority (--fast)", () => { @@ -145,11 +145,11 @@ describe("toggleDeployedOpenAiTier", () => { const FOLDER_LOCK = ".docks-kit-sync-lock.db"; /** - * Run `docks-kit omp ` in this process. Record what it prints and its - * exit code: the code of a `process.exit` call, else 1 for a failure and 0 - * for a success, as `BunRuntime.runMain` does. + * Run the `docks-kit` root command with `argv` in this process. Record what + * it prints and its exit code: the code of a `process.exit` call, else 1 for + * a failure and 0 for a success, as `BunRuntime.runMain` does. */ -async function runOmp( +async function runRoot( argv: ReadonlyArray, ): Promise<{ readonly exitCode: number; readonly output: string }> { const lines: Array = []; @@ -165,7 +165,7 @@ async function runOmp( }); const exit = await Effect.runPromiseExit( - Command.runWith(ompCommand, { version: "x" })(argv).pipe(Effect.provide(BunServices.layer)), + Command.runWith(rootCommand, { version: "x" })(argv).pipe(Effect.provide(BunServices.layer)), ); vi.restoreAllMocks(); @@ -173,7 +173,7 @@ async function runOmp( return { exitCode, output: lines.join("\n") }; } -/** A temporary HOME for `omp --fast` and `omp --ultrafast`, set in-process, with the lock wait bound `waitMs`. */ +/** A temporary HOME for `--fast` and `--ultrafast`, set in-process, with the lock wait bound `waitMs`. */ function fastHome(waitMs: string): { readonly home: string; readonly agentDir: string } { const home = realpathSync.native(mkdtempSync(join(tmpdir(), "omp-fast-lock-"))); roots.push(home); @@ -198,7 +198,7 @@ function heldLine(lock: string): string { return `another docks-kit sync holds ${lock}; run sync again after it ends`; } -describe("omp --fast under the folder lock", () => { +describe("--fast under the folder lock", () => { it("exits 1 with the held line and leaves config.yml unchanged while a sync holds the omp agent folder", async () => { // A short wait, so that the held lock ends the run quickly. const { agentDir } = fastHome("100"); @@ -209,7 +209,7 @@ describe("omp --fast under the folder lock", () => { const held = await takeLock(lock, false); try { - const run = await runOmp(["--fast"]); + const run = await runRoot(["--fast"]); expect(run.exitCode).toBe(1); expect(run.output).toContain(heldLine(lock)); @@ -228,7 +228,7 @@ describe("omp --fast under the folder lock", () => { const held = await takeLock(lock, true); try { - const run = await runOmp(["--fast"]); + const run = await runRoot(["--fast"]); expect(run.exitCode).toBe(1); expect(run.output).toContain(heldLine(lock)); @@ -246,7 +246,7 @@ describe("omp --fast under the folder lock", () => { let folderLock: KitLock | undefined; try { - const pending = runOmp(["--fast"]); + const pending = runRoot(["--fast"]); // The check before the locks ends the run at once; a run that waits is still pending. await Promise.race([pending, sleepMs(3000)]); expect(existsSync(join(home, ".omp"))).toBe(false); @@ -281,7 +281,7 @@ describe("omp --fast under the folder lock", () => { let folderLock: KitLock | undefined; try { - const pending = runOmp(["--fast"]); + const pending = runRoot(["--fast"]); await sleepMs(200); folderLock = await takeLock(lock, false); releaseKitLock(homeLock); @@ -297,7 +297,7 @@ describe("omp --fast under the folder lock", () => { }); }); -describe("omp --ultrafast", () => { +describe("--ultrafast", () => { it("toggles tier.openai to ultrafast and back to none, and keeps tier.anthropic", async () => { const { agentDir } = fastHome("100"); mkdirSync(agentDir, { recursive: true }); @@ -305,7 +305,7 @@ describe("omp --ultrafast", () => { writeFileSync(configPath, CONFIG.replace("anthropic: none", "anthropic: priority")); const shownPath = configPath.replaceAll("\\", "/"); - const on = await runOmp(["--ultrafast"]); + const on = await runRoot(["--ultrafast"]); expect(on.exitCode).toBe(0); expect(on.output.replaceAll("\\", "/")).toContain( `omp ultrafast mode ON for OpenAI/Codex models: tier.openai none -> ultrafast in ${shownPath}`, @@ -318,7 +318,7 @@ describe("omp --ultrafast", () => { anthropic: "priority", }); - const off = await runOmp(["--ultrafast"]); + const off = await runRoot(["--ultrafast"]); expect(off.exitCode).toBe(0); expect(off.output.replaceAll("\\", "/")).toContain( `omp ultrafast mode OFF for OpenAI/Codex models: tier.openai ultrafast -> none in ${shownPath}`, @@ -328,22 +328,4 @@ describe("omp --ultrafast", () => { anthropic: "priority", }); }); - - it.each([ - [["--ultrafast", "--fast"]], - [["--ultrafast", "--model", "free/model"]], - [["--ultrafast", "--pick"]], - [["--ultrafast", "hello"]], - ])("refuses %j and leaves config.yml unchanged", async (argv) => { - const { agentDir } = fastHome("100"); - mkdirSync(agentDir, { recursive: true }); - const configPath = join(agentDir, "config.yml"); - writeFileSync(configPath, CONFIG); - - const run = await runOmp(argv); - - expect(run.exitCode).not.toBe(0); - expect(run.output).toContain("--ultrafast toggles ultrafast mode and exits; pass it alone"); - expect(readFileSync(configPath, "utf8")).toBe(CONFIG); - }); }); diff --git a/cli/test/unit/rootFlags.test.ts b/cli/test/unit/rootFlags.test.ts new file mode 100644 index 000000000..ec2887049 --- /dev/null +++ b/cli/test/unit/rootFlags.test.ts @@ -0,0 +1,192 @@ +/** + * `docks-kit --fast` and `docks-kit --ultrafast` through the public CLI: each + * run spawns the real entry in a temporary home, so the toggle, its refusals, + * and the lock files are what a user sees. + */ +import { spawnSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { parse } from "yaml"; + +import { syncLockPath } from "../../src/engine-native/scratch"; +import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; +import { childEnv } from "../lib/goldenResources"; +import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; + +const CLI = cliEntry(); +const homes: Array = []; + +afterEach(() => { + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); +}); + +const CONFIG = `# user note +tier: + openai: none + anthropic: priority + +advisor: + enabled: true +`; + +/** The lock file that a writing sync takes inside the omp agent folder. */ +const FOLDER_LOCK = ".docks-kit-sync-lock.db"; + +/** A temporary home; `seed` writes the deployed omp config.yml. */ +function tempHome(seed: boolean): { readonly home: string; readonly configPath: string } { + const home = realpathSync.native(mkdtempSync(join(tmpdir(), "root-flags-"))); + homes.push(home); + const agentDir = join(home, ".omp", "agent"); + const configPath = join(agentDir, "config.yml"); + if (seed) { + mkdirSync(agentDir, { recursive: true }); + writeFileSync(configPath, CONFIG); + } + return { home, configPath }; +} + +/** + * Run the public CLI in `home`. The four agent-folder variables are empty, so + * the child resolves `/.omp/agent` and never a real profile folder. + */ +function run(home: string, args: ReadonlyArray) { + const result = spawnSync(BUN_RUNTIME, [CLI, ...args], { + encoding: "utf8", + env: childEnv({ + HOME: home, + USERPROFILE: home, + DOCKS_KIT_ENGINE: "", + PI_CODING_AGENT_DIR: "", + OMP_PROFILE: "", + PI_PROFILE: "", + PI_CONFIG_DIR: "", + DOCKS_KIT_SYNC_LOCK_WAIT_MS: "100", + }), + timeout: SPAWN_TIMEOUT_MS, + }); + // The kit joins its paths with "/", so compare output without separator style. + return { + status: result.status, + stdout: result.stdout.replaceAll("\\", "/"), + stderr: result.stderr.replaceAll("\\", "/"), + }; +} + +const shown = (path: string) => path.replaceAll("\\", "/"); + +describe("docks-kit --fast", () => { + it( + "turns fast mode on and off and changes only tier.openai", + () => { + const { home, configPath } = tempHome(true); + + const on = run(home, ["--fast"]); + expect(on.status).toBe(0); + expect(on.stdout).toContain( + `omp fast mode ON for OpenAI/Codex models: tier.openai none -> priority in ${shown(configPath)}`, + ); + expect(on.stdout).toContain( + "New omp sessions use it; in a running session, use /fast on|off or restart omp.", + ); + expect(readFileSync(configPath, "utf8")).toBe( + CONFIG.replace("openai: none", "openai: priority"), + ); + + const off = run(home, ["--fast"]); + expect(off.status).toBe(0); + expect(off.stdout).toContain( + `omp fast mode OFF for OpenAI/Codex models: tier.openai priority -> none in ${shown(configPath)}`, + ); + expect(readFileSync(configPath, "utf8")).toBe(CONFIG); + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "refuses a missing config.yml with exit 2 and creates no omp folder", + () => { + const { home, configPath } = tempHome(false); + + const result = run(home, ["--fast"]); + + expect(result.status).toBe(2); + expect(result.stderr).toContain( + `${shown(configPath)} does not exist; run 'docks-kit sync' first`, + ); + expect(existsSync(join(home, ".omp"))).toBe(false); + }, + SPAWN_TIMEOUT_MS, + ); + + it( + "stays a root flag: sync refuses it as its own unknown flag", + () => { + const { home, configPath } = tempHome(true); + + const result = run(home, ["sync", "--fast"]); + + expect(result.status).toBe(2); + expect(result.stderr).toContain("unknown flag --fast for 'sync'"); + expect(readFileSync(configPath, "utf8")).toBe(CONFIG); + }, + SPAWN_TIMEOUT_MS, + ); +}); + +describe("docks-kit --ultrafast", () => { + it( + "turns ultrafast mode on and off and changes only tier.openai", + () => { + const { home, configPath } = tempHome(true); + + const on = run(home, ["--ultrafast"]); + expect(on.status).toBe(0); + expect(on.stdout).toContain( + `omp ultrafast mode ON for OpenAI/Codex models: tier.openai none -> ultrafast in ${shown(configPath)}`, + ); + expect(on.stdout).toContain( + "New omp sessions use it; in a running session, use /fast ultra|off or restart omp.", + ); + expect(parse(readFileSync(configPath, "utf8"))).toEqual({ + tier: { openai: "ultrafast", anthropic: "priority" }, + advisor: { enabled: true }, + }); + + const off = run(home, ["--ultrafast"]); + expect(off.status).toBe(0); + expect(off.stdout).toContain( + `omp ultrafast mode OFF for OpenAI/Codex models: tier.openai ultrafast -> none in ${shown(configPath)}`, + ); + expect(readFileSync(configPath, "utf8")).toBe(CONFIG); + }, + SPAWN_TIMEOUT_MS, + ); +}); + +describe("docks-kit --fast --ultrafast", () => { + it.each([[["--fast", "--ultrafast"]], [["--ultrafast", "--fast"]]])( + "refuses %j with exit 2 before any lock or write", + (args) => { + const { home, configPath } = tempHome(true); + + const result = run(home, args); + + expect(result.status).toBe(2); + expect(result.stderr).toContain("Pass either --fast or --ultrafast, not both"); + expect(readFileSync(configPath, "utf8")).toBe(CONFIG); + expect(existsSync(syncLockPath(home))).toBe(false); + expect(existsSync(join(home, ".omp", "agent", FOLDER_LOCK))).toBe(false); + }, + SPAWN_TIMEOUT_MS, + ); +}); From 373af80a0713db3aa38353b090a33e362b26abcc Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:45:35 -0300 Subject: [PATCH 2/7] Remove the free-model omp launcher - Delete the omp command, the run overlay, and the session-model store. Move engineHome unchanged to engine-native/home.ts. - Stop importing the legacy state.json session model; keep kit.db schema 1 with its unused omp_session table, so older kits still open the store. - Drop the omp passthrough boundary from argv parsing. - Move the store and engineHome tests, delete the launcher tests, and pin `omp` as a removed name with a recording omp stub on PATH. - Clamp skill source ranges that the removals shortened. Refs #283 Verified: bunx vitest run cli/test/unit/removedNames.test.ts cli/test/unit/kitDb.test.ts cli/test/unit/home.test.ts cli/test/unit/argv.test.ts cli/test/unit/rootFlags.test.ts cli/test/unit/ompFastMode.test.ts cli/test/unit/skillMetadata.test.ts cli/test/unit/toolchain.test.ts cli/test/unit/scratch.test.ts; bun run check:types; bun run lint --- .agents/skills/engine-native-context/SKILL.md | 2 +- .agents/skills/toolchain-context/SKILL.md | 4 +- cli/src/argv.ts | 4 - cli/src/argvSurface.ts | 72 +-- cli/src/commands/omp.ts | 354 ----------- cli/src/commands/root.ts | 2 +- cli/src/commands/scratch.ts | 2 +- cli/src/commands/tidy.ts | 2 +- cli/src/engine-native/deps.ts | 2 +- cli/src/engine-native/engineCtx.ts | 2 +- cli/src/engine-native/home.ts | 15 + cli/src/engine-native/kitDb.ts | 87 +-- cli/src/engine-native/ompOverlay.ts | 268 --------- cli/src/engine-native/ompSession.ts | 67 --- cli/src/engine-native/sharedTypes.d.ts | 11 - cli/src/plan/services.ts | 2 +- cli/test/unit/argv.test.ts | 45 -- cli/test/unit/home.test.ts | 20 + cli/test/unit/kitDb.test.ts | 123 ++++ cli/test/unit/ompCommand.test.ts | 551 ------------------ cli/test/unit/ompOverlay.test.ts | 389 ------------- cli/test/unit/ompSession.test.ts | 251 -------- cli/test/unit/removedNames.test.ts | 93 ++- 23 files changed, 265 insertions(+), 2103 deletions(-) delete mode 100644 cli/src/commands/omp.ts create mode 100644 cli/src/engine-native/home.ts delete mode 100644 cli/src/engine-native/ompOverlay.ts delete mode 100644 cli/src/engine-native/ompSession.ts create mode 100644 cli/test/unit/home.test.ts create mode 100644 cli/test/unit/kitDb.test.ts delete mode 100644 cli/test/unit/ompCommand.test.ts delete mode 100644 cli/test/unit/ompOverlay.test.ts delete mode 100644 cli/test/unit/ompSession.test.ts diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md index 39113412b..908c70447 100644 --- a/.agents/skills/engine-native-context/SKILL.md +++ b/.agents/skills/engine-native-context/SKILL.md @@ -10,7 +10,7 @@ metadata: - path: cli/src/engine.ts lines: "1-53" - path: cli/src/main.ts - lines: "1-89" + lines: "1-60" - path: cli/src/engine-native/exec.ts lines: "1-346" - path: cli/src/engine-native/jq.ts diff --git a/.agents/skills/toolchain-context/SKILL.md b/.agents/skills/toolchain-context/SKILL.md index 8045df467..1dcd75e9c 100644 --- a/.agents/skills/toolchain-context/SKILL.md +++ b/.agents/skills/toolchain-context/SKILL.md @@ -16,11 +16,11 @@ metadata: - path: cli/src/engine-native/deps.ts lines: "1-224" - path: cli/src/engine-native/kitDb.ts - lines: "1-240" + lines: "1-177" - path: cli/src/engine-native/ompSync.ts lines: "1-122" - path: cli/src/engine-native/sharedTypes.d.ts - lines: "1-23" + lines: "1-12" - path: SoT/toolchain.json lines: "1-15" updated: "2026-11-27" diff --git a/cli/src/argv.ts b/cli/src/argv.ts index 60c1519cd..373028a46 100644 --- a/cli/src/argv.ts +++ b/cli/src/argv.ts @@ -3,7 +3,6 @@ import { docsCommand } from "./commands/docs"; import { syncCommand } from "./commands/sync"; import { toolchainCommand } from "./commands/toolchain"; import { updateCommand } from "./commands/update"; -import { ompCommand } from "./commands/omp"; import { scratchCommand } from "./commands/scratch"; import { tidyCommand } from "./commands/tidy"; import { planCommand } from "./commands/plan"; @@ -14,7 +13,6 @@ import { buildSurfaces, normalizeArgv, scanArgv, - spliceOmpBoundary, subcommandName as scanSubcommandName, type ArgvSurfaces, } from "./argvSurface"; @@ -33,7 +31,6 @@ export const COMMANDS = [ updateCommand, toolchainCommand, docsCommand, - ompCommand, scratchCommand, tidyCommand, planCommand, @@ -67,7 +64,6 @@ const spliceRawBoundary = (args: ReadonlyArray, word: string): ReadonlyA const passthroughBoundary = (args: ReadonlyArray): ReadonlyArray => { const word = subcommandName(args); - if (word === "omp") return spliceOmpBoundary(args, SURFACES); return word !== undefined && RAW_PASSTHROUGH.has(word) ? spliceRawBoundary(args, word) : args; }; diff --git a/cli/src/argvSurface.ts b/cli/src/argvSurface.ts index a9c961030..95265071d 100644 --- a/cli/src/argvSurface.ts +++ b/cli/src/argvSurface.ts @@ -1,9 +1,8 @@ /** * Flag grammar and parsing for the Effect CLI layer: flag surfaces derived - * from caller-supplied command values, argv scanning/normalization, - * subcommand detection, and the omp passthrough boundary. Pure: surfaces are - * built from structural command values, so this module never touches Effect - * CLI globals or process state. + * from caller-supplied command values, argv scanning/normalization, and + * subcommand detection. Pure: surfaces are built from structural command + * values, so this module never touches Effect CLI globals or process state. */ export interface FlagSurface { @@ -350,68 +349,3 @@ export const normalizeArgv = ( } return normalized; }; - -// Without the injected `--`, Effect 4 rejects a forwarded flag such as `-p` or -// `--mode` as unrecognized. The omp launcher therefore owns a passthrough -// boundary: the first token after the `omp` word that is neither a flag -// declared on the omp or global surface nor a value consumed by such a flag -// starts the verbatim tail forwarded to omp. An undeclared long flag joins the -// tail too, because most omp flags are long (`--mode`, `--continue`, -// `--models`), and omp itself reports an unrecognized one accurately. Use -// `docks-kit omp -- --model x` to reach omp's own same-named flag. -export const spliceOmpBoundary = ( - args: ReadonlyArray, - surfaces: ArgvSurfaces, -): ReadonlyArray => { - const surface = surfaces.commandSurfaces.get("omp"); - let ompIndex = -1; - for (let index = 0; index < args.length; index++) { - const token = args[index] as string; - if (token === "--") return args; - const name = flagNameOf(token); - if (token === name && takesValueInAnySurface(name, surfaces)) { - const next = args[index + 1]; - if (next === "--") return args; - if ( - next !== undefined && - !(next.startsWith("-") && declaredInAnySurface(flagNameOf(next), surfaces)) - ) { - index++; - continue; - } - } - if (!token.startsWith("-")) { - ompIndex = index; - break; - } - } - if (ompIndex === -1 || args[ompIndex] !== "omp") return args; - for (let index = ompIndex + 1; index < args.length; index++) { - const token = args[index] as string; - // An explicit delimiter already marks the tail; a second one would be - // forwarded to omp as a literal argument. - if (token === "--") return args; - if (!token.startsWith("-")) { - return [...args.slice(0, index), "--", ...args.slice(index)]; - } - const name = flagNameOf(token); - const canonical = declaredFlagName(name, surface, surfaces); - if (canonical === undefined) return [...args.slice(0, index), "--", ...args.slice(index)]; - const takesValue = - surface?.valueFlags.includes(canonical) === true || - surfaces.globalSurface.valueFlags.includes(canonical); - if (takesValue && !token.includes("=")) { - const next = args[index + 1]; - if ( - next !== undefined && - !( - next.startsWith("-") && - declaredFlagName(flagNameOf(next), surface, surfaces) !== undefined - ) - ) { - index++; - } - } - } - return args; -}; diff --git a/cli/src/commands/omp.ts b/cli/src/commands/omp.ts deleted file mode 100644 index 172af5112..000000000 --- a/cli/src/commands/omp.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { Argument, Command, Flag, Prompt } from "effect/cli"; -import { Console, Effect, Option } from "effect"; -import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; -import { bail } from "../engine"; -import { capture, p, spawnHost, which } from "../engine-native/exec"; -import { kitCacheDir } from "../engine-native/scratch"; -import { - DEFAULT_OMP_SESSION_MODEL, - engineHome, - readOmpSessionModel, - writeOmpSessionModel, - type OmpSessionModel, -} from "../engine-native/ompSession"; -import { - buildOmpArgs, - ladderCeiling, - ompChildEnvironment, - overlayFileName, - planEffortChoice, - parseFreeModels, - renderFreeOverlay, - type CatalogModel, -} from "../engine-native/ompOverlay"; - -const model = Flag.String("model").pipe( - Flag.withDescription("Free model selector to use and remember for omp sessions"), - Flag.optional, -); -const pick = Flag.Boolean("pick").pipe( - Flag.withDescription("Choose the free model interactively"), - Flag.withDefault(false), -); -const args: Argument.Argument> = Argument.String("args").pipe( - Argument.withDescription("Arguments forwarded verbatim to omp"), - Argument.variadic(), -); - -export type FreeSelectorResolution = - | { readonly ok: true; readonly model: CatalogModel } - | { readonly ok: false; readonly message: string }; - -// Pure selector matching so the picker rule stays testable without spawning omp. -// An exact selector always wins; otherwise one case-insensitive substring hit -// across the free selectors resolves, because a longer exact selector is easy -// to mistype and the catalog is small enough to disambiguate safely. -export function resolveFreeSelector( - input: string, - free: ReadonlyArray, -): FreeSelectorResolution { - const trimmed = input.trim(); - if (trimmed === "") { - return { ok: false, message: "Model selector must not be empty or blank" }; - } - const exact = free.find((candidate) => candidate.selector === trimmed); - if (exact !== undefined) return { ok: true, model: exact }; - const lowered = trimmed.toLowerCase(); - const matches = free.filter((candidate) => candidate.selector.toLowerCase().includes(lowered)); - const list = free.map((candidate) => candidate.selector).join(", "); - if (matches.length === 0) { - return { - ok: false, - message: `Model '${trimmed}' is not in the free catalog. Free models: ${list}`, - }; - } - const only = matches[0]; - if (matches.length === 1 && only !== undefined) return { ok: true, model: only }; - return { - ok: false, - message: `Model '${trimmed}' is ambiguous; matches: ${matches.map((candidate) => candidate.selector).join(", ")}. Pass the exact selector.`, - }; -} - -/** - * Every omp profile that the forwarded arguments can select, in argv order. - * omp reads `--profile ` or `--profile=`, the last one wins, and - * it rejects a missing or empty name. The scan does not stop at `--`, - * because omp can read that `--` as the value of a flag such as - * `--system-prompt` and still select a later profile. - */ -export type ForwardedProfile = - | { readonly ok: true; readonly profiles: ReadonlyArray } - | { readonly ok: false; readonly message: string }; - -export function forwardedProfile(forwarded: ReadonlyArray): ForwardedProfile { - const profiles: Array = []; - for (let index = 0; index < forwarded.length; index++) { - const arg = forwarded[index]!; - let value: string | undefined; - if (arg === "--profile") { - value = forwarded[index + 1]; - if (value === undefined || value.startsWith("-")) value = ""; - else index++; - } else if (arg.startsWith("--profile=")) { - value = arg.slice("--profile=".length); - } else { - continue; - } - if (value === "") return { ok: false, message: "--profile requires a profile name" }; - profiles.push(value); - } - return { ok: true, profiles }; -} - -// omp flags that can select a model the free overlay does not control. -const MODEL_SELECTING_FLAGS: Record = { - "--config": true, - "--model": true, - "--smol": true, - "--slow": true, - "--plan": true, - "--models": true, - "--provider": true, - "--prewalk-into": true, - "--plan-yolo-into": true, -}; - -export type ForwardedFlagCheck = - | { readonly ok: true } - | { readonly ok: false; readonly message: string }; - -/** - * Reject a forwarded omp flag that can select a model outside the free - * session. The scan does not stop at `--`, because omp can read that `--` as - * the value of a flag and then parse the next token as a flag. - */ -export function rejectedForwardedFlag(forwarded: ReadonlyArray): ForwardedFlagCheck { - for (const arg of forwarded) { - const equals = arg.indexOf("="); - const flag = equals === -1 ? arg : arg.slice(0, equals); - if (MODEL_SELECTING_FLAGS[flag] !== true) continue; - const configNote = - flag === "--config" - ? " To load another config, list it in PI_CONFIG_FILES, which omp loads below the overlay." - : ""; - return { - ok: false, - message: `Forwarded ${flag} can select a model outside the free session. For a free model, put --model before other arguments or use --pick; for a paid model, run omp directly.${configNote}`, - }; - } - return { ok: true }; -} - -const loadFreeCatalog = ( - omp: string, - profile: string | undefined, -): Effect.Effect> => - Effect.gen(function* () { - // omp takes --profile only before its subcommand. - const catalogArgs = [ - ...(profile === undefined ? [] : ["--profile", profile]), - "models", - "--json", - ]; - const command = `omp ${catalogArgs.join(" ")}`; - const raw = yield* Effect.promise(() => capture(omp, catalogArgs)); - if (raw === "") { - return yield* bail( - `'${command}' returned no output; verify omp runs on this host, then retry`, - ); - } - let parsed: unknown; - try { - parsed = JSON.parse(raw) as unknown; - } catch { - return yield* bail( - `'${command}' returned output that is not JSON; verify the omp version, then retry`, - ); - } - const free = parseFreeModels(parsed); - if (free.length === 0) { - return yield* bail(`'${command}' listed no free models; verify the omp login, then retry`); - } - return free; - }); - -/** - * Ask for the thinking level of one model. Every choice comes from that - * model own ladder, because omp rejects a `:level` suffix the model does not - * publish. A model with no ladder and a model with one level are settled - * without a question. Every role runs at the chosen level. - */ -const pickLevel = (catalogModel: CatalogModel) => - Effect.gen(function* () { - const plan = planEffortChoice(catalogModel.thinking); - if (plan.kind === "none") { - yield* Console.error( - `${catalogModel.name} publishes no thinking levels; the model default applies`, - ); - return undefined; - } - if (plan.kind === "fixed") { - yield* Console.error(`${catalogModel.name} publishes one thinking level: ${plan.level}`); - return plan.level; - } - // Prompt.Select always starts on the first entry and offers no initial - // index, so the list runs highest first and Enter keeps the ceiling. - return yield* Prompt.Select({ - message: "Thinking level for every role", - choices: [...plan.levels].reverse().map((level) => ({ - title: level, - value: level, - description: - level === plan.highest - ? "highest this model offers" - : level === plan.levels[0] - ? "lowest this model offers" - : "", - })), - }); - }); - -export const ompCommand = Command.make("omp", { model, pick, args }, (config) => - Effect.gen(function* () { - // Check the forwarded arguments before omp, the catalog, or kit.db, so a - // rejected launch starts no process and writes nothing. - const forwardedFlag = rejectedForwardedFlag(config.args); - if (!forwardedFlag.ok) return yield* bail(forwardedFlag.message); - - if (Option.isSome(config.model) && config.pick) { - return yield* bail("Pass either --model or --pick, not both"); - } - - const omp = yield* Effect.sync(() => which("omp")); - if (omp === "") { - return yield* bail("omp not found on PATH; install omp, then retry", 1); - } - - const home = engineHome(process.env); - // Check the terminal before the catalog spawn, so a non-interactive run - // fails with the actionable message instead of an omp subprocess first. - if (config.pick && (!process.stdin.isTTY || !process.stdout.isTTY)) { - return yield* bail("Picking needs a terminal; pass --model instead"); - } - // Every launch reads the live catalog, because a remembered or default - // model can be renamed, repriced, or lose its provider login. omp then - // silently starts a paid default model instead. omp can run the - // environment's profile or any forwarded one, so the session model must - // be free in the catalog of each. - const profile = forwardedProfile(config.args); - if (!profile.ok) return yield* bail(profile.message); - const candidates: Array = [undefined]; - for (const name of profile.profiles) { - if (!candidates.includes(name)) candidates.push(name); - } - const catalogs: Array> = []; - for (const candidate of candidates) { - catalogs.push(yield* loadFreeCatalog(omp, candidate)); - } - // --model and --pick choose from the catalog of the last forwarded - // profile, which omp selects when no flag consumes it. - const free = catalogs[candidates.indexOf(profile.profiles.at(-1))]!; - // The value the launcher writes is the value it runs, so a concurrent - // launcher or a failed read of kit.db cannot change this session. - let chosen: OmpSessionModel | undefined; - if (Option.isSome(config.model)) { - const resolved = resolveFreeSelector(config.model.value, free); - if (!resolved.ok) return yield* bail(resolved.message); - chosen = { - selector: resolved.model.selector, - thinking: ladderCeiling(resolved.model.thinking), - }; - } - - if (config.pick) { - const pickedSelector = yield* Prompt.Select({ - message: "Choose the free model for this omp session", - choices: free.map((candidate) => { - const ceiling = ladderCeiling(candidate.thinking); - return { - title: `${candidate.name} — ${candidate.selector}`, - value: candidate.selector, - description: - ceiling === undefined - ? `model default thinking; ${candidate.contextWindow} context` - : `thinking to ${ceiling}; ${candidate.contextWindow} context`, - }; - }), - }); - const match = free.find((candidate) => candidate.selector === pickedSelector); - if (match === undefined) { - return yield* bail(`Model '${pickedSelector}' is not in the free catalog`); - } - chosen = { selector: match.selector, thinking: yield* pickLevel(match) }; - } - - const session: OmpSessionModel = - chosen ?? (yield* Effect.sync(() => readOmpSessionModel(home))) ?? DEFAULT_OMP_SESSION_MODEL; - const freeInEveryProfile = catalogs.every((catalog) => - catalog.some((candidate) => candidate.selector === session.selector), - ); - if (!freeInEveryProfile) { - return yield* bail( - `free model '${session.selector}' is not available in the omp catalog (renamed, repriced, or provider not logged in); log in to its provider or choose another with --model or --pick`, - ); - } - - if (chosen !== undefined) { - const remembered = chosen; - yield* Effect.sync(() => writeOmpSessionModel(home, remembered)); - } - - // A stable cache path, not a temp file deleted at exit, because omp may - // re-read the overlay during a live session. The name carries a digest of - // the rendered overlay, so a second launcher on another model or level - // cannot rewrite the file a running session still reads. - const directory = kitCacheDir(home); - const overlayPath = p(directory, overlayFileName(session)); - yield* Effect.sync(() => { - // `mode` applies only when mkdir creates the path, so an existing - // permissive cache directory keeps its mode until the chmod below. - mkdirSync(directory, { recursive: true, mode: 0o700 }); - chmodSync(directory, 0o700); - writeFileSync(overlayPath, renderFreeOverlay(session), { mode: 0o600 }); - chmodSync(overlayPath, 0o600); - }); - - // A level-free model states the model default so the line never shows - // an undefined level. - const levelText = - typeof session.thinking === "string" && session.thinking.trim() !== "" - ? `${session.thinking} thinking` - : "the model default thinking level"; - yield* Console.error( - `Starting omp with ${session.selector} at ${levelText} (session only; deployed config unchanged)`, - ); - - // An exported model variable would set its role above the overlay, so the - // session gets the overlay value and the user sees what changed. - const childEnvironment = ompChildEnvironment(process.env, overlayPath, session); - for (const name of childEnvironment.replaced) { - yield* Console.error( - `${name} is set; this session uses ${childEnvironment.env[name]} instead`, - ); - } - - const child = yield* Effect.sync(() => - spawnHost("omp", buildOmpArgs(overlayPath, session, config.args), { - stdio: "inherit", - env: childEnvironment.env, - }), - ); - if (child.error !== undefined) { - return yield* bail( - `Failed to start omp: ${child.error instanceof Error ? child.error.message : String(child.error)}`, - ); - } - // A signalled child reports a null status, which must not look successful. - return yield* Effect.sync(() => process.exit(child.status ?? 1)); - }), -).pipe( - Command.withDescription( - "Start omp with every chat-model role set to the remembered free model for this run only. The launcher starts 'omp launch' with an explicit --model, so omp reads a forwarded subcommand name as message text and a resumed session keeps the free model. It rejects forwarded flags that can select another model (--config, --model, --smol, --slow, --plan, --models, --provider, --prewalk-into, --plan-yolo-into); run omp directly for a paid model or a subcommand. The web-search role keeps the deployed provider order, which can include a paid model. No deployed configuration changes; --model or --pick remembers a new free default. Every launch checks the model against the live free catalog of each candidate profile. --fast instead toggles OpenAI/Codex fast mode in the deployed omp config and exits; --ultrafast does the same for ultrafast mode.", - ), -); diff --git a/cli/src/commands/root.ts b/cli/src/commands/root.ts index 0fe13933f..916434617 100644 --- a/cli/src/commands/root.ts +++ b/cli/src/commands/root.ts @@ -9,7 +9,7 @@ import { Console, Effect } from "effect"; import { bail } from "../engine"; import { p } from "../engine-native/exec"; -import { engineHome } from "../engine-native/ompSession"; +import { engineHome } from "../engine-native/home"; import { FAST_ON_TIER, requireDeployedConfig, diff --git a/cli/src/commands/scratch.ts b/cli/src/commands/scratch.ts index b1e78c593..bf987d831 100644 --- a/cli/src/commands/scratch.ts +++ b/cli/src/commands/scratch.ts @@ -4,7 +4,7 @@ import { Argument, Command } from "effect/cli"; import { Console, Effect } from "effect"; import { bail } from "../engine"; -import { engineHome } from "../engine-native/ompSession"; +import { engineHome } from "../engine-native/home"; import { allowedRemovalRoots, createScratchDir, diff --git a/cli/src/commands/tidy.ts b/cli/src/commands/tidy.ts index 6516f78c7..22b84bc16 100644 --- a/cli/src/commands/tidy.ts +++ b/cli/src/commands/tidy.ts @@ -4,7 +4,7 @@ import { Command, Flag } from "effect/cli"; import { Console, Effect, Option } from "effect"; import { bail } from "../engine"; -import { engineHome } from "../engine-native/ompSession"; +import { engineHome } from "../engine-native/home"; import { acquireKitLock, releaseKitLock } from "../engine-native/kitLock"; import { scratchRoot, tidyApplyLockPath } from "../engine-native/scratch"; import { diff --git a/cli/src/engine-native/deps.ts b/cli/src/engine-native/deps.ts index acd80aca7..9153f42ae 100644 --- a/cli/src/engine-native/deps.ts +++ b/cli/src/engine-native/deps.ts @@ -10,7 +10,7 @@ import { isAbsolute } from "node:path"; import { capture, captureWithin, commandExists, p, which, type CaptureOutcome } from "./exec"; -import { engineHome } from "./ompSession"; +import { engineHome } from "./home"; import { hostOs, platformName, rawPlatform } from "./os"; import type { HostOs, Invocation } from "./os/types"; import { field } from "./toolchain"; diff --git a/cli/src/engine-native/engineCtx.ts b/cli/src/engine-native/engineCtx.ts index b967810fb..4ef4a89d0 100644 --- a/cli/src/engine-native/engineCtx.ts +++ b/cli/src/engine-native/engineCtx.ts @@ -3,7 +3,7 @@ * the environment. Split from index.ts, which re-exports the public surface * so existing import paths keep working. */ -import { engineHome } from "./ompSession"; +import { engineHome } from "./home"; import type { TerminalLease } from "./logger"; import type { BunRuntimeState } from "./bun"; import { kitHome } from "../kitHome"; diff --git a/cli/src/engine-native/home.ts b/cli/src/engine-native/home.ts new file mode 100644 index 000000000..d3e90cf29 --- /dev/null +++ b/cli/src/engine-native/home.ts @@ -0,0 +1,15 @@ +/** The engine home root that locates the kit store, the caches, and the omp folders. */ +import { homedir } from "node:os"; + +/** + * Resolve the engine home root the way the harness resolves `~`. On Windows, + * USERPROFILE applies and HOME is ignored. Elsewhere, HOME applies. The + * platform home is the fallback. + */ +export function engineHome( + env: NodeJS.ProcessEnv = process.env, + platform: NodeJS.Platform = process.platform, +): string { + const home = platform === "win32" ? env["USERPROFILE"] : env["HOME"]; + return home !== undefined && home !== "" ? home : homedir(); +} diff --git a/cli/src/engine-native/kitDb.ts b/cli/src/engine-native/kitDb.ts index aebd8916e..7500ae871 100644 --- a/cli/src/engine-native/kitDb.ts +++ b/cli/src/engine-native/kitDb.ts @@ -1,9 +1,9 @@ /** * Per-machine kit store at ~/.docks-kit/kit.db. This module is the only code - * that opens the database: it applies the schema migrations, imports the - * legacy ~/.docks-kit/state.json once, and serves the network lookup cache. + * that opens the database: it applies the schema migrations and serves the + * network lookup cache. */ -import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; import { GENERATED_PACKAGE_VERSION } from "../generated/sotPayload"; @@ -11,14 +11,13 @@ import { p } from "./exec"; /** * Append-only. Never edit or reorder a shipped entry. A release that changes the - * schema appends one SQL string. The state table omp_session gets - * data-preserving migrations; cache_entry may be dropped and recreated + * schema appends one SQL string. cache_entry may be dropped and recreated * because every row can be refetched. */ const MIGRATIONS: ReadonlyArray = [ - // omp_session.advisor_thinking has had no use since 0.22.22, and - // harness_selection has had no use since 0.24.0. They stay only to keep - // schema 1, which older kits still open; nothing reads or writes them. + // harness_selection has had no use since 0.24.0, and omp_session has had + // no use since 0.32.0, which removed the free-model launcher. They stay only + // to keep schema 1, which older kits still open; nothing reads or writes them. `CREATE TABLE harness_selection ( harness TEXT PRIMARY KEY CHECK (harness IN ('claude','codex','agents','omp')) ) STRICT, WITHOUT ROWID; @@ -89,68 +88,9 @@ function migrate(db: DatabaseSync): boolean { }); } -interface LegacySession { - readonly selector: string; - readonly thinking: string | null; -} - -export function isNonBlankString(value: unknown): value is string { - return typeof value === "string" && value.trim() !== ""; -} - -/** A blank or non-string value is stored as NULL. */ -export function nonBlankOrNull(value: unknown): string | null { - return isNonBlankString(value) ? value : null; -} - -// Same validation the JSON store applied: root object, version 1, non-blank -// selector and levels. The legacy harness selection is not imported: sync -// has one harness and reads no selection. -function parseLegacySession(file: string): LegacySession | undefined { - let parsed: unknown; - try { - parsed = JSON.parse(readFileSync(file, "utf8")) as unknown; - } catch { - return undefined; - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; - if (!("version" in parsed) || parsed.version !== 1) return undefined; - - const entry = "ompSession" in parsed ? parsed.ompSession : undefined; - if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return undefined; - const selector = nonBlankOrNull("selector" in entry ? entry.selector : undefined); - if (selector === null) return undefined; - return { - selector, - thinking: nonBlankOrNull("thinking" in entry ? entry.thinking : undefined), - }; -} - -function importLegacyState(db: DatabaseSync, legacy: string): void { - inTransaction(db, () => { - const rows = db.prepare("SELECT count(*) AS n FROM omp_session").get()?.["n"]; - if (rows !== 0) return; - const session = parseLegacySession(legacy); - if (session === undefined) return; - db.prepare("INSERT INTO omp_session (id, selector, thinking) VALUES (1, ?, ?)").run( - session.selector, - session.thinking, - ); - }); - // An invalid file is renamed too, so no later run parses it again. - try { - renameSync(legacy, `${legacy}.migrated`); - } catch (error) { - // A parallel process renamed it first. - const code = typeof error === "object" && error !== null && "code" in error ? error.code : ""; - if (code !== "ENOENT") throw error; - } -} - /** - * Open kit.db, migrate it, import the legacy state file once, and run fn. - * A read with neither kit.db nor state.json present creates nothing and - * returns undefined. + * Open kit.db, migrate it, and run fn. A read without kit.db creates nothing + * and returns undefined. */ export function withKitDb( home: string, @@ -158,8 +98,7 @@ export function withKitDb( fn: (db: DatabaseSync) => T, ): T | undefined { const file = kitDbFile(home); - const legacy = p(home, ".docks-kit", "state.json"); - if (access === "read" && !existsSync(file) && !existsSync(legacy)) return undefined; + if (access === "read" && !existsSync(file)) return undefined; const directory = p(home, ".docks-kit"); // A read of an existing kit.db changes no permissions, so it works on a @@ -181,12 +120,10 @@ export function withKitDb( "PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;", ); const migrated = migrate(db); - const importing = existsSync(legacy); - if (importing) importLegacyState(db, legacy); const result = fn(db); // Fold the WAL into kit.db so a copy of kit.db alone holds every row. - // Reads can migrate or import too, so they checkpoint after writing. - if (access === "write" || migrated || importing) { + // A read can migrate too, so it checkpoints after a migration. + if (access === "write" || migrated) { db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); } return result; diff --git a/cli/src/engine-native/ompOverlay.ts b/cli/src/engine-native/ompOverlay.ts deleted file mode 100644 index 5bde1e590..000000000 --- a/cli/src/engine-native/ompOverlay.ts +++ /dev/null @@ -1,268 +0,0 @@ -/** - * Run overlay for `docks-kit omp`. The overlay merges over the deployed omp - * config for one run only. It sets the 16 roles in ROLE_ORDER to the free - * model and empties the 12 retry chains in FALLBACK_ORDER and the chains keyed - * by the free model. omp merges the overlay key by key, so each deployed retry - * chain that is not in FALLBACK_ORDER stays as deployed. The `web` role and - * its retry chain are not in the overlay, so the deployed web-search provider - * order applies, and that order can include a paid chat model. A deployed - * `advisor`, `plan`, `slow`, or `designer` chain also stays, but a retry of - * the free model uses the empty chain keyed by that model first. Every other - * key falls through to the deployed config. - */ -import { createHash } from "node:crypto"; -import { delimiter } from "node:path"; -import type { OmpSessionModel } from "./ompSession"; - -export interface CatalogModel { - readonly selector: string; - readonly name: string; - readonly thinking: ReadonlyArray; - readonly contextWindow: number; -} - -/** Thinking levels from lowest to highest effort. */ -export const THINKING_LADDER: ReadonlyArray = [ - "minimal", - "low", - "medium", - "high", - "xhigh", - "max", -]; - -/** - * One overlay file per distinct model and level combination, so a second - * launcher cannot rewrite the file a running session still reads. omp - * reloads a changed overlay mid-session, so the digest covers the exact - * rendered overlay: the selector, the level, and every rendered key. A - * selector carries a slash and may carry other characters a host rejects in - * a file name, so unsafe characters in the readable prefix become hyphens. - */ -export function overlayFileName(model: OmpSessionModel): string { - const safe = model.selector.replace(/[^A-Za-z0-9._-]/g, "-"); - const digest = createHash("sha256").update(renderFreeOverlay(model)).digest("hex").slice(0, 8); - return `omp-free-${safe}-${digest}.yml`; -} - -/** - * Role keys in the order used by SoT/.omp/config.yml for readable diffs. The - * SoT does not set `advisor`, `memory`, and `judge`, so they come last. An - * unset role falls back to the omp built-in priority chain, which can name a - * paid model. omp takes the `/advisor on` model from the `advisor` role and - * uses `slow` only when that role is unset, so the overlay pins `advisor` - * too: a deployed or project advisor role would otherwise send the advisor - * to a paid model. The `web` role is left out on purpose, so the - * deployed web-search provider order applies. - */ -const ROLE_ORDER: ReadonlyArray = [ - "smol", - "designer", - "plan", - "commit", - "task", - "vision", - "tiny", - "default", - "slow", - "fable", - "switch_fable", - "astra", - "reviewer", - "code_reviewer", - "plan_reviewer", - "advisor", - "memory", - "judge", -]; - -/** - * Retry chain keys in the order used by SoT/.omp/config.yml, then `memory` and - * `judge`. An explicit empty chain stops omp from using its built-in priority - * chain. The `web` chain is left out, so the deployed chain applies. - */ -const FALLBACK_ORDER: ReadonlyArray = [ - "default", - "task", - "vision", - "smol", - "tiny", - "commit", - "switch_fable", - "fable", - "astra", - "reviewer", - "code_reviewer", - "plan_reviewer", - "memory", - "judge", -]; - -/** - * Collect free models from parsed `omp models --json` output. The function is - * total because catalog output varies across omp versions, and one malformed - * row must not discard the remaining picker list. - */ -export function parseFreeModels(catalogJson: unknown): ReadonlyArray { - if (typeof catalogJson !== "object" || catalogJson === null || Array.isArray(catalogJson)) { - return []; - } - const models = (catalogJson as Record)["models"]; - if (!Array.isArray(models)) return []; - const found: Array = []; - for (const row of models) { - if (typeof row !== "object" || row === null || Array.isArray(row)) continue; - const record = row as Record; - const selector = record["selector"]; - if (typeof selector !== "string" || selector.length === 0) continue; - const cost = record["cost"]; - if (typeof cost !== "object" || cost === null || Array.isArray(cost)) continue; - const charges = cost as Record; - if (charges["input"] !== 0 || charges["output"] !== 0) continue; - // omp prices a usage-billed or plan-included model at zero, so a zero - // cost is not proof of a free model. Older omp output has no status. - const status = record["pricingStatus"]; - if (typeof status === "string" && status !== "free" && status !== "unknown") continue; - const rawName = record["name"]; - const name = typeof rawName === "string" && rawName.length > 0 ? rawName : selector; - const rawLevels = record["thinking"]; - // Keep only known ladder levels in ladder order so an unknown future - // level never reaches a role value that omp would reject. - const thinking = THINKING_LADDER.filter( - (level) => Array.isArray(rawLevels) && (rawLevels as Array).includes(level), - ); - const rawWindow = record["contextWindow"]; - const contextWindow = - typeof rawWindow === "number" && Number.isFinite(rawWindow) ? rawWindow : 0; - found.push({ selector, name, thinking, contextWindow }); - } - // Sort by selector so the picker list is stable across catalog orderings. - found.sort((a, b) => (a.selector < b.selector ? -1 : a.selector > b.selector ? 1 : 0)); - return found; -} - -/** - * Resolve the highest ladder level a model supports. A model without a - * recognized ladder yields undefined so callers never invent a level the - * model would reject at session start. - */ -export function ladderCeiling(levels: ReadonlyArray): string | undefined { - for (let index = THINKING_LADDER.length - 1; index >= 0; index -= 1) { - if (levels.includes(THINKING_LADDER[index] as string)) return THINKING_LADDER[index] as string; - } - return undefined; -} - -/** - * What the picker may ask about thinking levels for one model. omp accepts a - * `:level` suffix on a role only for a level the model publishes, so the - * question set comes from the model own ladder: no ladder means no question, - * a single level means no choice to make, and two or more levels mean one - * level choice for every role. - */ -export type EffortPlan = - | { readonly kind: "none" } - | { readonly kind: "fixed"; readonly level: string } - | { readonly kind: "choose"; readonly levels: ReadonlyArray; readonly highest: string }; - -export function planEffortChoice(levels: ReadonlyArray): EffortPlan { - const known = THINKING_LADDER.filter((level) => levels.includes(level)); - const only = known[0]; - if (only === undefined) return { kind: "none" }; - if (known.length === 1) return { kind: "fixed", level: only }; - return { kind: "choose", levels: known, highest: known[known.length - 1] as string }; -} - -/** A thinking level the overlay can render, or undefined for a blank one. */ -function renderableLevel(level: string | undefined): string | undefined { - return typeof level === "string" && level.trim() !== "" ? level : undefined; -} - -/** - * The value the overlay gives every role. The overlay, the session `--model`, - * and the child environment all use it, so the three cannot drift apart. A - * model without a level gets the bare selector so the deployed level applies. - */ -function roleValue(model: OmpSessionModel): string { - const thinking = renderableLevel(model.thinking); - return thinking === undefined ? model.selector : `${model.selector}:${thinking}`; -} - -/** - * Render the run overlay as YAML text. Empty fallback chains keep a retry - * from falling back onto a paid model. A model without a level renders bare - * selectors with no thinking keys so the deployed values apply. - */ -export function renderFreeOverlay(model: OmpSessionModel): string { - const thinking = renderableLevel(model.thinking); - const lines: Array = ["# Generated per run by docks-kit omp. Edits are overwritten."]; - if (thinking !== undefined) lines.push(`defaultThinkingLevel: ${thinking}`); - lines.push("modelRoles:"); - for (const role of ROLE_ORDER) { - lines.push(` ${role}: ${roleValue(model)}`); - } - if (thinking !== undefined) lines.push("task:", ` maxEffort: ${thinking}`); - lines.push("retry:", " fallbackChains:"); - for (const chain of FALLBACK_ORDER) { - lines.push(` ${chain}: []`); - } - // A chain keyed by the selector outranks a role chain, so a project or - // PI_CONFIG_FILES chain for the free model could otherwise reach a paid - // model. The session can run the model at any level, `off` included. - for (const level of [undefined, "off", ...THINKING_LADDER]) { - const key = level === undefined ? model.selector : `${model.selector}:${level}`; - lines.push(` ${JSON.stringify(key)}: []`); - } - return `${lines.join("\n")}\n`; -} - -/** - * Build the omp argv. `launch` first makes omp read every forwarded word as - * message text, so no omp subcommand, with its own model selection, runs - * through the launcher. The explicit `--model` outranks a restored session - * model, so `--continue` and `--resume` keep the free model. - */ -export function buildOmpArgs( - overlayPath: string, - session: OmpSessionModel, - passthrough: ReadonlyArray, -): ReadonlyArray { - return ["launch", "--config", overlayPath, "--model", roleValue(session), ...passthrough]; -} - -// Variables that omp reads at launch to set a role above every config layer. -const MODEL_ENV_NAMES: ReadonlyArray = ["PI_SMOL_MODEL", "PI_SLOW_MODEL", "PI_PLAN_MODEL"]; - -export interface OmpChildEnvironment { - readonly env: Record; - /** Model variables whose non-empty parent value the overlay value replaced. */ - readonly replaced: ReadonlyArray; -} - -/** - * The omp session environment. The model variables get the overlay role - * values, because removing them would let a `.env` file refill them. The - * overlay joins PI_CONFIG_FILES, so an omp that the session's bash tool - * starts loads it too. - */ -export function ompChildEnvironment( - parent: Readonly>, - overlayPath: string, - session: OmpSessionModel, -): OmpChildEnvironment { - const inherited = (parent["PI_CONFIG_FILES"] ?? "") - .split(delimiter) - .filter((entry) => entry !== ""); - const env: Record = { - ...parent, - PI_CONFIG_FILES: [...inherited, overlayPath].join(delimiter), - }; - const replaced: Array = []; - const value = roleValue(session); - for (const name of MODEL_ENV_NAMES) { - const previous = parent[name]; - if (previous !== undefined && previous !== "" && previous !== value) replaced.push(name); - env[name] = value; - } - return { env, replaced }; -} diff --git a/cli/src/engine-native/ompSession.ts b/cli/src/engine-native/ompSession.ts deleted file mode 100644 index de5218e29..000000000 --- a/cli/src/engine-native/ompSession.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * The omp session model that `docks-kit omp` stores in ~/.docks-kit/kit.db - * (kitDb.ts), and the engine home root that locates the kit store. - */ -import { homedir } from "node:os"; - -import { isNonBlankString, nonBlankOrNull, withKitDb } from "./kitDb"; -import type { OmpSessionModel } from "./sharedTypes"; - -export type { OmpSessionModel }; - -export const DEFAULT_OMP_SESSION_MODEL: OmpSessionModel = { - selector: "opencode-zen/muse-spark-1.3-contributor-free", - thinking: "xhigh", -}; - -/** - * Resolve the engine home root the way the harness resolves `~`. On Windows, - * USERPROFILE applies and HOME is ignored. Elsewhere, HOME applies. The - * platform home is the fallback. - */ -export function engineHome( - env: NodeJS.ProcessEnv = process.env, - platform: NodeJS.Platform = process.platform, -): string { - const home = platform === "win32" ? env["USERPROFILE"] : env["HOME"]; - return home !== undefined && home !== "" ? home : homedir(); -} - -// Read the stored session model without throwing so a corrupt store falls -// back to the default instead of breaking sync. -export function readOmpSessionModel(home: string): OmpSessionModel | undefined { - try { - return withKitDb(home, "read", (db) => { - const row = db.prepare("SELECT selector, thinking FROM omp_session WHERE id = 1").get(); - const selector = row?.["selector"]; - if (!isNonBlankString(selector)) return undefined; - const thinking = row?.["thinking"]; - const model: OmpSessionModel = { - selector, - ...(isNonBlankString(thinking) ? { thinking } : {}), - }; - return model; - }); - } catch { - return undefined; - } -} - -export function writeOmpSessionModel(home: string, model: OmpSessionModel): void { - // A blank selector would make omp resolve an arbitrary model, so reject it - // before anything reaches disk. - if (!isNonBlankString(model.selector)) { - throw new Error("Omp session model selector must be a non-empty string"); - } - // Store a blank or absent level as NULL so a switch to a level-free model - // leaves no stale level behind. - const thinking = nonBlankOrNull(model.thinking); - withKitDb(home, "write", (db) => - db - .prepare( - `INSERT INTO omp_session (id, selector, thinking) VALUES (1, ?, ?) -ON CONFLICT(id) DO UPDATE SET selector = excluded.selector, thinking = excluded.thinking`, - ) - .run(model.selector, thinking), - ); -} diff --git a/cli/src/engine-native/sharedTypes.d.ts b/cli/src/engine-native/sharedTypes.d.ts index 0760705b5..0bb26c363 100644 --- a/cli/src/engine-native/sharedTypes.d.ts +++ b/cli/src/engine-native/sharedTypes.d.ts @@ -8,16 +8,5 @@ import type { Json } from "./jq"; /** Manifest-record object: the `{ [key]: Json }` shape redeclared across manifest readers. */ export type JsonObject = { [key: string]: Json }; -/** - * omp session model (moved from ompSession.ts, which re-exports it so existing - * import paths keep working). - */ -export interface OmpSessionModel { - readonly selector: string; - // Session ceiling; absent when the model publishes no ladder, so no - // invented level ever reaches a selector that omp must resolve. - readonly thinking?: string; -} - /** Injected HTTP client: the subset of fetch the network lookups call. */ export type FetchLike = (url: string, init?: RequestInit) => Promise; diff --git a/cli/src/plan/services.ts b/cli/src/plan/services.ts index 13de746ff..12c7f346e 100644 --- a/cli/src/plan/services.ts +++ b/cli/src/plan/services.ts @@ -7,7 +7,7 @@ import fs from "node:fs"; import { Context, Duration, Effect, Layer, Predicate } from "effect"; -import { engineHome } from "../engine-native/ompSession"; +import { engineHome } from "../engine-native/home"; import { createScratchDir, scratchRoot } from "../engine-native/scratch"; import { FileError, SpawnError, type RepositoryInfo } from "./types"; diff --git a/cli/test/unit/argv.test.ts b/cli/test/unit/argv.test.ts index 84719df38..8ce799866 100644 --- a/cli/test/unit/argv.test.ts +++ b/cli/test/unit/argv.test.ts @@ -18,7 +18,6 @@ const REGISTERED_SUBCOMMANDS = [ "update", "toolchain", "docs", - "omp", "scratch", "tidy", "plan", @@ -268,50 +267,6 @@ describe("argument validation", () => { }); }); -describe("omp passthrough boundary", () => { - it.each([ - [ - "forwards a short flag tail behind an injected delimiter", - ["omp", "-p", "hi"], - ["omp", "--", "-p", "hi"], - ], - [ - "keeps a declared value flag and its value before the boundary", - ["omp", "--model", "x", "-p", "hi"], - ["omp", "--model", "x", "--", "-p", "hi"], - ], - [ - "starts the tail at a positional message", - ["omp", "fix the bug"], - ["omp", "--", "fix the bug"], - ], - [ - "preserves an explicit delimiter before an omp flag sharing the launcher's name", - ["omp", "--", "--model", "upstream"], - ["omp", "--", "--model", "upstream"], - ], - ["leaves a lone picker flag unchanged", ["omp", "--pick"], ["omp", "--pick"]], - ["leaves help unchanged", ["omp", "--help"], ["omp", "--help"]], - [ - "forwards an undeclared long flag and its value", - ["omp", "--mode", "json", "-p", "hi"], - ["omp", "--", "--mode", "json", "-p", "hi"], - ], - [ - "forwards omp's own --models without confusing it with --model", - ["omp", "--models", "a,b"], - ["omp", "--", "--models", "a,b"], - ], - [ - "skips a global option value before locating the omp passthrough", - ["--log-level", "debug", "omp", "-p", "hi"], - ["--log-level", "debug", "omp", "--", "-p", "hi"], - ], - ] as const)("%s", (_name, input, args) => { - expect(prepareArgv(input)).toEqual({ kind: "accept", args }); - }); -}); - describe("subcommand resolution", () => { it.each([ [ diff --git a/cli/test/unit/home.test.ts b/cli/test/unit/home.test.ts new file mode 100644 index 000000000..0589dd9ae --- /dev/null +++ b/cli/test/unit/home.test.ts @@ -0,0 +1,20 @@ +import { homedir } from "node:os"; +import { describe, expect, it } from "vitest"; + +import { engineHome } from "../../src/engine-native/home"; + +describe("engineHome", () => { + it("resolves the engine home from HOME with a homedir fallback", () => { + expect(engineHome({ HOME: "/fixture/home" }, "linux")).toBe("/fixture/home"); + expect(engineHome({}, "linux")).toBe(homedir()); + expect(engineHome({ HOME: "" }, "darwin")).toBe(homedir()); + }); + + it("resolves the engine home from USERPROFILE on Windows and ignores HOME", () => { + expect(engineHome({ HOME: "C:\\msys64\\home\\u", USERPROFILE: "C:\\Users\\u" }, "win32")).toBe( + "C:\\Users\\u", + ); + expect(engineHome({ HOME: "C:\\msys64\\home\\u" }, "win32")).toBe(homedir()); + expect(engineHome({ HOME: "C:\\msys64\\home\\u", USERPROFILE: "" }, "win32")).toBe(homedir()); + }); +}); diff --git a/cli/test/unit/kitDb.test.ts b/cli/test/unit/kitDb.test.ts new file mode 100644 index 000000000..6dfbbf679 --- /dev/null +++ b/cli/test/unit/kitDb.test.ts @@ -0,0 +1,123 @@ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { kitDbFile, readCache, withKitDb, writeCache } from "../../src/engine-native/kitDb"; + +const NOW = 1_700_000_000_000; +const DAY_MS = 86_400_000; + +let home = ""; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "docks-kit-db-")); +}); + +afterEach(() => { + rmSync(home, { recursive: true, force: true }); +}); + +describe("kit store", () => { + it("creates no store when a read finds no kit.db", () => { + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBeUndefined(); + expect(existsSync(kitDbFile(home))).toBe(false); + }); + + it("treats a corrupt SQLite store as a cache miss", () => { + mkdirSync(join(home, ".docks-kit")); + writeFileSync(kitDbFile(home), "not a SQLite database"); + + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBeUndefined(); + }); + + it("refuses a store from a newer schema and keeps its rows", () => { + writeCache(home, "toolchain:bun", "1.4.5", NOW); + const db = new DatabaseSync(kitDbFile(home)); + db.exec("PRAGMA user_version = 99"); + db.close(); + + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBeUndefined(); + expect(() => withKitDb(home, "write", () => undefined)).toThrow( + /schema 99.*Upgrade docks-kit/s, + ); + const after = new DatabaseSync(kitDbFile(home), { readOnly: true }); + const version = after.prepare("PRAGMA user_version").get()?.["user_version"]; + const rows = after.prepare("SELECT payload FROM cache_entry").all(); + after.close(); + expect(version).toBe(99); + expect(rows).toEqual([{ payload: "1.4.5" }]); + }); + + it("keeps schema 1 with its unused tables, so an older kit still opens the store", () => { + writeCache(home, "toolchain:bun", "1.4.5", NOW); + + const db = new DatabaseSync(kitDbFile(home), { readOnly: true }); + const version = db.prepare("PRAGMA user_version").get()?.["user_version"]; + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name") + .all(); + db.close(); + expect(version).toBe(1); + expect(tables).toEqual([ + { name: "cache_entry" }, + { name: "harness_selection" }, + { name: "omp_session" }, + ]); + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBe("1.4.5"); + }); + + it("creates a private store and directory under the selected home", () => { + writeCache(home, "toolchain:bun", "1.4.5", NOW); + + const stateFile = kitDbFile(home); + expect(existsSync(stateFile)).toBe(true); + if (process.platform !== "win32") { + expect(statSync(stateFile).mode & 0o777).toBe(0o600); + expect(statSync(join(home, ".docks-kit")).mode & 0o777).toBe(0o700); + } + }); + + it("tightens an existing permissive state directory to 0700", () => { + if (process.platform === "win32") return; + mkdirSync(join(home, ".docks-kit"), { recursive: true, mode: 0o755 }); + chmodSync(join(home, ".docks-kit"), 0o755); + + writeCache(home, "toolchain:bun", "1.4.5", NOW); + + expect(statSync(join(home, ".docks-kit")).mode & 0o777).toBe(0o700); + }); + + it("reads an existing store without changing its permissions", () => { + if (process.platform === "win32") return; + writeCache(home, "toolchain:bun", "1.4.5", NOW); + chmodSync(join(home, ".docks-kit"), 0o755); + chmodSync(kitDbFile(home), 0o644); + + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBe("1.4.5"); + expect(statSync(join(home, ".docks-kit")).mode & 0o777).toBe(0o755); + expect(statSync(kitDbFile(home)).mode & 0o777).toBe(0o644); + }); + + it("keeps the stores of separate homes independent", () => { + const otherHome = mkdtempSync(join(tmpdir(), "docks-kit-db-other-")); + try { + writeCache(home, "toolchain:bun", "first", NOW); + writeCache(otherHome, "toolchain:bun", "second", NOW); + + expect(readCache(home, "toolchain:bun", DAY_MS, NOW)).toBe("first"); + expect(readCache(otherHome, "toolchain:bun", DAY_MS, NOW)).toBe("second"); + } finally { + rmSync(otherHome, { recursive: true, force: true }); + } + }); +}); diff --git a/cli/test/unit/ompCommand.test.ts b/cli/test/unit/ompCommand.test.ts deleted file mode 100644 index e62be5c6f..000000000 --- a/cli/test/unit/ompCommand.test.ts +++ /dev/null @@ -1,551 +0,0 @@ -import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; -import { delimiter, join } from "node:path"; -import { afterAll, describe, expect, it } from "vitest"; -import { parse } from "yaml"; - -import { - forwardedProfile, - rejectedForwardedFlag, - resolveFreeSelector, -} from "../../src/commands/omp"; -import { readOmpSessionModel } from "../../src/engine-native/ompSession"; -import { kitDbFile } from "../../src/engine-native/kitDb"; -import { overlayFileName, type CatalogModel } from "../../src/engine-native/ompOverlay"; -import { runPublicCli } from "../lib/goldenExecution"; -import { cleanupTemporaryDirs, makeStubDir } from "../lib/goldenResources"; -import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; - -const NATIVE = { nativeHost: true } as const; -afterAll(cleanupTemporaryDirs); - -const FREE: ReadonlyArray = [ - { - selector: "opencode-zen/muse-spark-1.3-contributor-free", - name: "Muse Spark 1.3 Free", - thinking: ["minimal", "low", "medium", "high", "xhigh"], - contextWindow: 1048576, - }, - { - selector: "opencode-zen/glm-4.7-free", - name: "GLM 4.7 Free", - thinking: ["minimal", "low", "medium"], - contextWindow: 204800, - }, -]; - -describe("resolveFreeSelector", () => { - it("prefers an exact selector over another free selector that contains it", () => { - const resolved = resolveFreeSelector(" opencode-zen/glm-4.7-free ", [ - ...FREE, - { ...FREE[1]!, selector: "opencode-zen/glm-4.7-free-extended" }, - ]); - expect(resolved).toEqual({ ok: true, model: FREE[1] }); - }); - - it("matches a unique case-insensitive substring", () => { - const resolved = resolveFreeSelector("SPARK", FREE); - expect(resolved).toEqual({ ok: true, model: FREE[0] }); - }); - - it("rejects an ambiguous substring by listing the matches", () => { - expect(resolveFreeSelector("opencode-zen", FREE)).toEqual({ - ok: false, - message: - "Model 'opencode-zen' is ambiguous; matches: opencode-zen/muse-spark-1.3-contributor-free, opencode-zen/glm-4.7-free. Pass the exact selector.", - }); - }); - - it("rejects an unknown selector without choosing a paid model", () => { - expect(resolveFreeSelector("opencode-zen/kimi-paid", FREE)).toEqual({ - ok: false, - message: - "Model 'opencode-zen/kimi-paid' is not in the free catalog. Free models: opencode-zen/muse-spark-1.3-contributor-free, opencode-zen/glm-4.7-free", - }); - }); - - it("rejects a blank model selector", () => { - expect(resolveFreeSelector(" \t ", FREE)).toEqual({ - ok: false, - message: "Model selector must not be empty or blank", - }); - }); -}); - -describe("forwardedProfile", () => { - it("lists every --profile and --profile= value in argv order", () => { - expect(forwardedProfile(["-p", "hi"])).toEqual({ ok: true, profiles: [] }); - expect(forwardedProfile(["--profile", "work", "-p", "hi"])).toEqual({ - ok: true, - profiles: ["work"], - }); - expect(forwardedProfile(["--profile=work"])).toEqual({ ok: true, profiles: ["work"] }); - expect(forwardedProfile(["--profile", "a", "--profile=b"])).toEqual({ - ok: true, - profiles: ["a", "b"], - }); - expect(forwardedProfile(["--profile", "a", "-p", "x", "--profile=b"])).toEqual({ - ok: true, - profiles: ["a", "b"], - }); - }); - - it("does not stop at -- because omp can read that -- as the value of a flag", () => { - // In `--system-prompt -- --profile work`, omp takes `--` as the prompt - // and selects the work profile. - expect(forwardedProfile(["--system-prompt", "--", "--profile", "work"])).toEqual({ - ok: true, - profiles: ["work"], - }); - expect(forwardedProfile(["--", "--profile", "work"])).toEqual({ - ok: true, - profiles: ["work"], - }); - }); - - it("rejects a missing or empty profile name as omp does", () => { - for (const args of [["--profile"], ["--profile", "-p", "hi"], ["--profile="]]) { - expect(forwardedProfile(args)).toEqual({ - ok: false, - message: "--profile requires a profile name", - }); - } - }); -}); - -describe("rejectedForwardedFlag", () => { - const MODEL_FLAGS = [ - "--config", - "--model", - "--smol", - "--slow", - "--plan", - "--models", - "--provider", - "--prewalk-into", - "--plan-yolo-into", - ] as const; - - const expectRejected = (args: ReadonlyArray, flag: string): string => { - const result = rejectedForwardedFlag(args); - expect(result.ok).toBe(false); - const message = result.ok ? "" : result.message; - expect(message).toContain(flag); - expect(message).toContain("--model "); - expect(message).toContain("--pick"); - expect(message).toContain("run omp directly"); - return message; - }; - - it.each(MODEL_FLAGS)("rejects %s in the --flag value and --flag=value forms", (flag) => { - expectRejected(["-p", "hi", flag, "paid/x"], flag); - expectRejected(["-p", "hi", `${flag}=paid/x`], flag); - }); - - it("names PI_CONFIG_FILES for a forwarded --config", () => { - expect(expectRejected(["--config", "extra.yml"], "--config")).toContain("PI_CONFIG_FILES"); - expect(expectRejected(["--config=extra.yml"], "--config")).toContain("PI_CONFIG_FILES"); - }); - - it("rejects a model flag after a forwarded -- because omp can read that -- as a value", () => { - expectRejected(["-p", "hi", "--", "--smol", "x"], "--smol"); - expectRejected(["--api-key", "--", "--model", "x"], "--model"); - }); - - it.each([ - [[]], - [["--continue"]], - [["-c"]], - [["--resume", "abc"]], - [["-p", "hi"]], - [["--thinking", "high"]], - [["--advisor"]], - [["--prewalk"]], - [["--plan-yolo"]], - [["--profile", "work"]], - [["--api-key", "k"]], - [["fix the --model docs"]], - ])("allows %j", (args) => { - expect(rejectedForwardedFlag(args)).toEqual({ ok: true }); - }); -}); - -describe("omp command", () => { - const selector = "opencode-zen/glm-4.7-free"; - const levelFreeSelector = "provider/level-free"; - const stubDir = makeStubDir( - { - omp: `if (args[0] === "models" && args[1] === "--json") { - console.log(JSON.stringify({models:[ - {selector:"${selector}",name:"GLM Free",thinking:["low","high"],contextWindow:204800,cost:{input:0,output:0}}, - {selector:"${levelFreeSelector}",name:"Level Free",thinking:[],contextWindow:4096,cost:{input:0,output:0}}, - {selector:"provider/paid",name:"Paid",thinking:["high"],contextWindow:4096,cost:{input:0,output:1}} - ]})) -}`, - }, - NATIVE, - ); - - it( - "starts with a private free overlay, remembers it, then switches without rewriting it", - () => { - const first = runPublicCli( - ["omp", "--model", "GLM", "-p", "hello"], - "home-fresh", - stubDir, - NATIVE, - ); - expect(first.exitCode).toBe(0); - expect(first.stderr).toContain( - `Starting omp with ${selector} at high thinking (session only; deployed config unchanged)`, - ); - expect(first.stdout).toBe(""); - expect(readOmpSessionModel(first.home)).toEqual({ selector, thinking: "high" }); - - const overlayDir = join(first.home, ".cache", "docks-kit"); - const [firstName] = readdirSync(overlayDir); - expect(firstName).toBe(overlayFileName({ selector, thinking: "high" })); - const firstPath = join(overlayDir, firstName!); - if (process.platform !== "win32") { - expect(statSync(overlayDir).mode & 0o777).toBe(0o700); - expect(statSync(firstPath).mode & 0o777).toBe(0o600); - } - const firstOverlay = readFileSync(firstPath, "utf8"); - expect(parse(firstOverlay)).toMatchObject({ - defaultThinkingLevel: "high", - modelRoles: { - default: `${selector}:high`, - advisor: `${selector}:high`, - code_reviewer: `${selector}:high`, - plan_reviewer: `${selector}:high`, - }, - retry: { fallbackChains: { default: [], code_reviewer: [], plan_reviewer: [] } }, - }); - const argvLog = join(first.home, ".golden-argv.log"); - expect(readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - `omp\tlaunch --config ${first.home}/.cache/docks-kit/${firstName} --model ${selector}:high -p hello`, - ]); - - const options = { ...NATIVE, reuseHome: first.home }; - const plain = runPublicCli(["omp", "-p", "again"], "home-fresh", stubDir, options); - expect(plain.exitCode).toBe(0); - // Every plain launch checks the remembered model against the live catalog. - expect(readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - `omp\tlaunch --config ${first.home}/.cache/docks-kit/${firstName} --model ${selector}:high -p again`, - ]); - - const switched = runPublicCli( - ["omp", "--model", levelFreeSelector], - "home-fresh", - stubDir, - options, - ); - expect(switched.exitCode).toBe(0); - expect(switched.stderr).toContain( - `Starting omp with ${levelFreeSelector} at the model default thinking level (session only; deployed config unchanged)`, - ); - expect(readOmpSessionModel(first.home)).toEqual({ selector: levelFreeSelector }); - // The session runs the --model value it wrote, not a re-read of kit.db, - // which held the earlier model before this run. - expect(readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - `omp\tlaunch --config ${first.home}/.cache/docks-kit/${overlayFileName({ selector: levelFreeSelector })} --model ${levelFreeSelector}`, - ]); - const names = readdirSync(overlayDir); - expect(names).toHaveLength(2); - const secondPath = join( - overlayDir, - names.find((name) => name !== firstName)!, - ); - const second = parse(readFileSync(secondPath, "utf8")) as Record; - expect(second).not.toHaveProperty("defaultThinkingLevel"); - expect(second).not.toHaveProperty("task"); - expect((second["modelRoles"] as Record)["default"]).toBe(levelFreeSelector); - expect((second["modelRoles"] as Record)["advisor"]).toBe(levelFreeSelector); - expect(readFileSync(firstPath, "utf8")).toBe(firstOverlay); - expect(existsSync(join(first.home, ".omp", "agent"))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "gives the omp session the overlay and the overlay role models in its environment", - () => { - // The session call logs the variables that select a model or load a - // config, so the test sees what omp and its bash tool inherit. - const envStub = makeStubDir( - { - omp: `if (args[0] === "models" && args[1] === "--json") { - console.log(JSON.stringify({models:[ - {selector:"${selector}",name:"GLM Free",thinking:["low","high"],contextWindow:204800,cost:{input:0,output:0}} - ]})) -} else { - const pick = (name) => process.env[name] ?? null; - appendFileSync(process.env.HOME + "/.omp-env.log", JSON.stringify({ - PI_CONFIG_FILES: pick("PI_CONFIG_FILES"), - PI_SMOL_MODEL: pick("PI_SMOL_MODEL"), - PI_SLOW_MODEL: pick("PI_SLOW_MODEL"), - PI_PLAN_MODEL: pick("PI_PLAN_MODEL"), - }) + "\\n") -}`, - }, - NATIVE, - ); - const inherited = join("team", "omp-extra.yml"); - const run = runPublicCli(["omp", "--model", "GLM", "-p", "hello"], "home-fresh", envStub, { - ...NATIVE, - env: { PI_SMOL_MODEL: "paid/x", PI_CONFIG_FILES: inherited }, - }); - expect(run.exitCode, run.stderr).toBe(0); - const overlayDir = join(run.home, ".cache", "docks-kit"); - const [overlayName] = readdirSync(overlayDir); - // The launcher joins the overlay path with "/", as the argv below shows, - // also on Windows. - const overlayPath = `${run.home}/.cache/docks-kit/${overlayName}`; - const roles = (parse(readFileSync(overlayPath, "utf8")) as Record)[ - "modelRoles" - ] as Record; - const logged = readFileSync(join(run.home, ".omp-env.log"), "utf8").trim().split("\n"); - expect(logged.map((line) => JSON.parse(line) as unknown)).toEqual([ - { - PI_CONFIG_FILES: [inherited, overlayPath].join(delimiter), - PI_SMOL_MODEL: roles["smol"], - PI_SLOW_MODEL: roles["slow"], - PI_PLAN_MODEL: roles["plan"], - }, - ]); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - `omp\tlaunch --config ${run.home}/.cache/docks-kit/${overlayName} --model ${selector}:high -p hello`, - ]); - // One warning for the exported variable the launcher replaced, none - // for the two variables the parent did not set. - const stderrLines = run.stderr.split("\n"); - expect(stderrLines.filter((line) => line.includes("PI_SMOL_MODEL"))).toHaveLength(1); - expect(stderrLines.filter((line) => line.includes("PI_SLOW_MODEL"))).toEqual([]); - expect(stderrLines.filter((line) => line.includes("PI_PLAN_MODEL"))).toEqual([]); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "sends a forwarded omp subcommand word to the free session as message text", - () => { - // `launch` first makes omp read `commit` as a prompt instead of running - // its commit subcommand with its own model selection. - const run = runPublicCli(["omp", "--model", "GLM", "commit"], "home-fresh", stubDir, NATIVE); - expect(run.exitCode, run.stderr).toBe(0); - const [overlayName] = readdirSync(join(run.home, ".cache", "docks-kit")); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - `omp\tlaunch --config ${run.home}/.cache/docks-kit/${overlayName} --model ${selector}:high commit`, - ]); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "refuses a noninteractive picker before contacting omp or creating session state", - () => { - const run = runPublicCli(["omp", "--pick"], "home-fresh", stubDir, NATIVE); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain("Picking needs a terminal; pass --model instead"); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe(""); - expect(existsSync(kitDbFile(run.home))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "refuses a plain launch whose default model is not in the free catalog", - () => { - // The stub catalog does not list DEFAULT_OMP_SESSION_MODEL, as on a host - // with no opencode login. - const run = runPublicCli(["omp", "-p", "hello"], "home-fresh", stubDir, NATIVE); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain( - "free model 'opencode-zen/muse-spark-1.3-contributor-free' is not available in the omp catalog (renamed, repriced, or provider not logged in); log in to its provider or choose another with --model or --pick", - ); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe("omp\tmodels --json\n"); - expect(existsSync(join(run.home, ".cache", "docks-kit"))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "refuses a plain launch whose remembered model left the free catalog", - () => { - const first = runPublicCli(["omp", "--model", "GLM"], "home-fresh", stubDir, NATIVE); - expect(first.exitCode).toBe(0); - const repriced = makeStubDir( - { - omp: `if (args[0] === "models" && args[1] === "--json") { - console.log(JSON.stringify({models:[ - {selector:"${selector}",name:"GLM",thinking:["low","high"],contextWindow:204800,cost:{input:1,output:1}}, - {selector:"${levelFreeSelector}",name:"Level Free",thinking:[],contextWindow:4096,cost:{input:0,output:0}} - ]})) -}`, - }, - NATIVE, - ); - const run = runPublicCli(["omp"], "home-fresh", repriced, { - ...NATIVE, - reuseHome: first.home, - }); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain(`free model '${selector}' is not available in the omp catalog`); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe("omp\tmodels --json\n"); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "rejects a malformed catalog before saving a model or starting omp", - () => { - const badCatalog = makeStubDir( - { omp: `if (args[0] === "models") console.log("not JSON")` }, - NATIVE, - ); - const run = runPublicCli(["omp", "--model", "GLM"], "home-fresh", badCatalog, NATIVE); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain( - "'omp models --json' returned output that is not JSON; verify the omp version, then retry", - ); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe("omp\tmodels --json\n"); - expect(existsSync(kitDbFile(run.home))).toBe(false); - expect(existsSync(join(run.home, ".cache", "docks-kit"))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "resolves --model in the last forwarded profile and checks the model in every candidate profile", - () => { - // Each profile has its own login and catalog. `free-model` is ambiguous - // in the default catalog and unique in the work catalog, and the - // resolved model is free in both. - const profiles = makeStubDir( - { - omp: `const at = args.indexOf("models"); -if (at !== -1 && args[at + 1] === "--json") { - const profile = args[0] === "--profile" ? args[1] : "default"; - const free = (selector) => ({selector,name:selector,thinking:["high"],contextWindow:4096,cost:{input:0,output:0}}); - const catalogs = { - default: [free("shared/free-model"), free("shared/free-model-plus")], - work: [free("shared/free-model")], - }; - console.log(JSON.stringify({models:catalogs[profile] ?? []})) -}`, - }, - NATIVE, - ); - const first = runPublicCli( - ["omp", "--model", "free-model", "--profile", "work", "-p", "hi"], - "home-fresh", - profiles, - NATIVE, - ); - expect(first.exitCode, first.stderr).toBe(0); - expect(readOmpSessionModel(first.home)).toEqual({ - selector: "shared/free-model", - thinking: "high", - }); - const argvLog = join(first.home, ".golden-argv.log"); - const [overlayName] = readdirSync(join(first.home, ".cache", "docks-kit")); - expect(readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - "omp\t--profile work models --json", - `omp\tlaunch --config ${first.home}/.cache/docks-kit/${overlayName} --model shared/free-model:high --profile work -p hi`, - ]); - - // A plain launch under --profile= checks the remembered model - // against every candidate catalog too. - const plain = runPublicCli(["omp", "--profile=work"], "home-fresh", profiles, { - ...NATIVE, - reuseHome: first.home, - }); - expect(plain.exitCode, plain.stderr).toBe(0); - expect(readFileSync(argvLog, "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - "omp\t--profile work models --json", - `omp\tlaunch --config ${first.home}/.cache/docks-kit/${overlayName} --model shared/free-model:high --profile=work`, - ]); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "refuses a launch whose model is free in the environment profile but not in a forwarded profile", - () => { - // omp reads `--` as the --system-prompt value and then selects the - // work profile, whose catalog does not list the session model. - const profiles = makeStubDir( - { - omp: `const at = args.indexOf("models"); -if (at !== -1 && args[at + 1] === "--json") { - const profile = args[0] === "--profile" ? args[1] : "default"; - const free = (selector) => ({selector,name:selector,thinking:["high"],contextWindow:4096,cost:{input:0,output:0}}); - const catalogs = { - default: [free("opencode-zen/muse-spark-1.3-contributor-free"), free("shared/free-model")], - work: [free("shared/free-model")], - }; - console.log(JSON.stringify({models:catalogs[profile] ?? []})) -}`, - }, - NATIVE, - ); - const run = runPublicCli( - ["omp", "--system-prompt", "--", "--profile", "work", "-p", "hi"], - "home-fresh", - profiles, - NATIVE, - ); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain( - "free model 'opencode-zen/muse-spark-1.3-contributor-free' is not available", - ); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8").trim().split("\n")).toEqual([ - "omp\tmodels --json", - "omp\t--profile work models --json", - ]); - expect(existsSync(join(run.home, ".cache", "docks-kit"))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "rejects a forwarded model flag before contacting omp", - () => { - const run = runPublicCli( - ["omp", "-p", "hi", "--smol", "paid/x"], - "home-fresh", - stubDir, - NATIVE, - ); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain("--smol"); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe(""); - expect(existsSync(kitDbFile(run.home))).toBe(false); - expect(existsSync(join(run.home, ".cache", "docks-kit"))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); - - it( - "rejects a forwarded --profile without a name before contacting omp", - () => { - const run = runPublicCli( - ["omp", "--model", "GLM", "--profile"], - "home-fresh", - stubDir, - NATIVE, - ); - expect(run.exitCode).toBe(2); - expect(run.stderr).toContain("--profile requires a profile name"); - expect(readFileSync(join(run.home, ".golden-argv.log"), "utf8")).toBe(""); - expect(existsSync(kitDbFile(run.home))).toBe(false); - }, - SPAWN_TIMEOUT_MS, - ); -}); diff --git a/cli/test/unit/ompOverlay.test.ts b/cli/test/unit/ompOverlay.test.ts deleted file mode 100644 index 9964d7c16..000000000 --- a/cli/test/unit/ompOverlay.test.ts +++ /dev/null @@ -1,389 +0,0 @@ -import { readFileSync } from "node:fs"; -import { delimiter, join, resolve } from "node:path"; -import { describe, expect, it } from "vitest"; -import { parse } from "yaml"; - -import type { OmpSessionModel } from "../../src/engine-native/ompSession"; -import { - buildOmpArgs, - ladderCeiling, - ompChildEnvironment, - overlayFileName, - parseFreeModels, - planEffortChoice, - renderFreeOverlay, - THINKING_LADDER, -} from "../../src/engine-native/ompOverlay"; - -const FREE_SELECTOR = "opencode-zen/muse-spark-1.3-contributor-free"; - -const REPO_DIR = resolve(import.meta.dirname, "..", "..", ".."); - -// Keys the overlay leaves to the deployed config on purpose. The `web` role -// and its chain keep the deployed web-search provider order. The launcher -// docs state that this order can include a paid model. -const DEPLOYED_ONLY_KEYS = ["web"]; - -const ROLE_KEYS = [ - "smol", - "designer", - "plan", - "commit", - "task", - "vision", - "tiny", - "default", - "slow", - "fable", - "switch_fable", - "astra", - "reviewer", - "code_reviewer", - "plan_reviewer", - "advisor", - "memory", - "judge", -]; - -const FALLBACK_KEYS = [ - "default", - "task", - "vision", - "smol", - "tiny", - "commit", - "switch_fable", - "fable", - "astra", - "reviewer", - "code_reviewer", - "plan_reviewer", - "memory", - "judge", -]; - -// Free catalog ladders can skip medium or xhigh entirely. -const LADDER_FULL = ["minimal", "low", "medium", "high", "xhigh"]; -const LADDER_NO_XHIGH = ["minimal", "low", "medium", "high"]; -const LADDER_LOW_HIGH_MAX = ["low", "high", "max"]; -const LADDER_EMPTY: ReadonlyArray = []; - -function fallbackChains(parsed: Record): Record { - return (parsed["retry"] as Record)["fallbackChains"] as Record; -} - -function renderedRoles(model: OmpSessionModel): Record { - const parsed = parse(renderFreeOverlay(model)) as Record; - return parsed["modelRoles"] as Record; -} - -const LADDER_MODEL: OmpSessionModel = { selector: FREE_SELECTOR, thinking: "high" }; -const LEVEL_FREE_MODEL: OmpSessionModel = { selector: "provider/ling-free" }; -const OVERLAY_PATH = join("cache", "docks-kit", "omp-free.yml"); - -describe("omp free-session overlay", () => { - it("sets every chat-model role, the advisor included, to one free selector and level", () => { - const parsed = parse( - renderFreeOverlay({ selector: FREE_SELECTOR, thinking: "xhigh" }), - ) as Record; - expect(parsed["defaultThinkingLevel"]).toBe("xhigh"); - const roles = parsed["modelRoles"] as Record; - for (const role of ROLE_KEYS) { - expect(roles[role]).toBe(`${FREE_SELECTOR}:xhigh`); - } - const task = parsed["task"] as Record; - expect(task["maxEffort"]).toBe("xhigh"); - const chains = fallbackChains(parsed); - for (const key of FALLBACK_KEYS) { - expect(chains[key]).toEqual([]); - } - // A free advisor retries through the empty chains keyed by the model. - expect("advisor" in chains).toBe(false); - }); - - it("resolves the ceiling from the model own ladder without guessing", () => { - expect(ladderCeiling(LADDER_FULL)).toBe("xhigh"); - expect(ladderCeiling(LADDER_NO_XHIGH)).toBe("high"); - expect(ladderCeiling(LADDER_LOW_HIGH_MAX)).toBe("max"); - expect(ladderCeiling(LADDER_EMPTY)).toBeUndefined(); - }); - - it("renders the chosen max level for every role", () => { - const roles = renderedRoles({ selector: "provider/big-pickle", thinking: "max" }); - for (const role of ROLE_KEYS) { - expect(roles[role]).toBe("provider/big-pickle:max"); - } - }); - - it("renders a level-free model with bare chat selectors and no thinking keys", () => { - const parsed = parse(renderFreeOverlay({ selector: "provider/ling-free" })) as Record< - string, - unknown - >; - expect("defaultThinkingLevel" in parsed).toBe(false); - expect("task" in parsed).toBe(false); - const roles = parsed["modelRoles"] as Record; - for (const role of ROLE_KEYS) { - expect(roles[role]).toBe("provider/ling-free"); - } - const chains = fallbackChains(parsed); - for (const key of FALLBACK_KEYS) { - expect(chains[key]).toEqual([]); - } - }); - - it("keeps zero-cost rows and rejects paid and unpriced models", () => { - const catalog = { - models: [ - { - selector: "paid/input", - name: "Paid input", - thinking: ["low"], - contextWindow: 100, - cost: { input: 1, output: 0 }, - }, - { - selector: "paid/output", - name: "Paid output", - thinking: ["low"], - contextWindow: 100, - cost: { input: 0, output: 1 }, - }, - { selector: "unpriced/model" }, - // omp prices usage-billed and plan-included models at zero cost. - { - selector: "cursor/default", - name: "Auto", - thinking: [], - contextWindow: 100, - cost: { input: 0, output: 0 }, - pricingStatus: "variable", - }, - { - selector: "plan/included", - name: "Included", - thinking: [], - contextWindow: 100, - cost: { input: 0, output: 0 }, - pricingStatus: "included", - }, - { - selector: "status/unknown", - name: "Unknown status", - thinking: [], - contextWindow: 100, - cost: { input: 0, output: 0 }, - pricingStatus: "unknown", - }, - { - selector: FREE_SELECTOR, - name: "Muse Spark 1.3 Free", - thinking: ["minimal", "low", "medium", "high", "xhigh", "ultra"], - contextWindow: 1048576, - cost: { input: 0, output: 0 }, - pricingStatus: "free", - }, - "not-a-row", - { selector: "", cost: { input: 0, output: 0 } }, - ], - }; - expect(parseFreeModels(catalog)).toEqual([ - { - selector: FREE_SELECTOR, - name: "Muse Spark 1.3 Free", - thinking: ["minimal", "low", "medium", "high", "xhigh"], - contextWindow: 1048576, - }, - { selector: "status/unknown", name: "Unknown status", thinking: [], contextWindow: 100 }, - ]); - expect(parseFreeModels(undefined)).toEqual([]); - expect(parseFreeModels({})).toEqual([]); - }); - - it("keeps distinct models and levels in separate, repeatable overlay files", () => { - const high = { selector: "opencode-zen/muse", thinking: "high" }; - const name = overlayFileName(high); - expect(name).toMatch(/^omp-free-[A-Za-z0-9._-]+\.yml$/); - expect(overlayFileName({ ...high })).toBe(name); - // A running session reloads its overlay when the file changes, so another - // level for the same model must not share the file. - expect(overlayFileName({ selector: "opencode-zen/muse", thinking: "xhigh" })).not.toBe(name); - // These selectors have the same sanitized spelling but must not overwrite - // each other's live-session overlay. - expect(overlayFileName({ selector: "opencode-zen/muse" })).not.toBe( - overlayFileName({ selector: "opencode-zen-muse" }), - ); - }); - - it("covers every deployed role and retry chain or declares it deployed-only", () => { - const sot = parse(readFileSync(join(REPO_DIR, "SoT", ".omp", "config.yml"), "utf8")) as Record< - string, - unknown - >; - const overlay = parse( - renderFreeOverlay({ selector: FREE_SELECTOR, thinking: "xhigh" }), - ) as Record; - const overlayRoles = Object.keys(overlay["modelRoles"] as Record); - const overlayChains = Object.keys(fallbackChains(overlay)); - const sotRoles = Object.keys(sot["modelRoles"] as Record); - const sotChains = Object.keys(fallbackChains(sot)); - expect( - sotRoles.filter((key) => !overlayRoles.includes(key) && !DEPLOYED_ONLY_KEYS.includes(key)), - ).toEqual([]); - expect( - sotChains.filter((key) => !overlayChains.includes(key) && !DEPLOYED_ONLY_KEYS.includes(key)), - ).toEqual([]); - // A deployed-only key must stay out of the overlay, or the docs that - // describe it as deployed would be wrong. - for (const key of DEPLOYED_ONLY_KEYS) { - expect(overlayRoles).not.toContain(key); - expect(overlayChains).not.toContain(key); - } - }); - - it("asks nothing when the model publishes no usable ladder", () => { - expect(planEffortChoice([])).toEqual({ kind: "none" }); - // An unknown future level is not a level omp would accept from the kit. - expect(planEffortChoice(["turbo"])).toEqual({ kind: "none" }); - }); - - it("settles a single-level model without a question", () => { - expect(planEffortChoice(["high"])).toEqual({ kind: "fixed", level: "high" }); - }); - - it("offers only the levels the model publishes, lowest first", () => { - const plan = planEffortChoice(["high", "minimal", "medium"]); - expect(plan).toEqual({ - kind: "choose", - levels: ["minimal", "medium", "high"], - highest: "high", - }); - }); - - it("allows a model whose top level is max rather than xhigh", () => { - expect(planEffortChoice(["low", "high", "max"])).toEqual({ - kind: "choose", - levels: ["low", "high", "max"], - highest: "max", - }); - }); -}); - -describe("free model fallback chains", () => { - it.each([ - ["a model with a ladder", LADDER_MODEL], - ["a level-free model", LEVEL_FREE_MODEL], - ])( - "empties the chains keyed by the selector, :off, and every ladder level for %s", - (_label, model) => { - // A chain keyed by the model outranks a role chain, and the session can - // run the free model at any concrete level. - const chains = fallbackChains(parse(renderFreeOverlay(model)) as Record); - expect(chains[model.selector]).toEqual([]); - expect(chains[`${model.selector}:off`]).toEqual([]); - for (const level of THINKING_LADDER) { - expect(chains[`${model.selector}:${level}`]).toEqual([]); - } - for (const key of FALLBACK_KEYS) { - expect(chains[key]).toEqual([]); - } - }, - ); -}); - -describe("buildOmpArgs", () => { - it("starts omp with launch, the overlay, and the session model at its level", () => { - const args = buildOmpArgs(OVERLAY_PATH, LADDER_MODEL, ["-p", "commit"]); - expect(args).toEqual([ - "launch", - "--config", - OVERLAY_PATH, - "--model", - `${FREE_SELECTOR}:high`, - "-p", - "commit", - ]); - // The explicit model is the overlay's default role, so a restored - // session model cannot replace it. - expect(args[4]).toBe(renderedRoles(LADDER_MODEL)["default"]); - }); - - it("passes the bare selector for a model without a ladder", () => { - const args = buildOmpArgs(OVERLAY_PATH, LEVEL_FREE_MODEL, ["--continue"]); - expect(args).toEqual([ - "launch", - "--config", - OVERLAY_PATH, - "--model", - "provider/ling-free", - "--continue", - ]); - expect(args[4]).toBe(renderedRoles(LEVEL_FREE_MODEL)["default"]); - }); -}); - -describe("ompChildEnvironment", () => { - const roles = renderedRoles(LADDER_MODEL); - - it("adds the overlay and the overlay role models to an empty environment", () => { - expect(ompChildEnvironment({}, OVERLAY_PATH, LADDER_MODEL)).toEqual({ - env: { - PI_CONFIG_FILES: OVERLAY_PATH, - PI_SMOL_MODEL: roles["smol"], - PI_SLOW_MODEL: roles["slow"], - PI_PLAN_MODEL: roles["plan"], - }, - replaced: [], - }); - }); - - it("uses the bare selector for a level-free model", () => { - const bare = renderedRoles(LEVEL_FREE_MODEL); - const { env } = ompChildEnvironment({}, OVERLAY_PATH, LEVEL_FREE_MODEL); - expect(env["PI_SMOL_MODEL"]).toBe(bare["smol"]); - expect(env["PI_SLOW_MODEL"]).toBe(bare["slow"]); - expect(env["PI_PLAN_MODEL"]).toBe(bare["plan"]); - }); - - it("appends the overlay after the inherited PI_CONFIG_FILES entries and keeps other variables", () => { - const inherited = [join("team", "a.yml"), "", join("team", "b.yml")].join(delimiter); - const { env } = ompChildEnvironment( - { PI_CONFIG_FILES: inherited, KEEP_ME: "1" }, - OVERLAY_PATH, - LADDER_MODEL, - ); - expect(env["PI_CONFIG_FILES"]).toBe( - [join("team", "a.yml"), join("team", "b.yml"), OVERLAY_PATH].join(delimiter), - ); - expect(env["KEEP_ME"]).toBe("1"); - }); - - it("lists only a non-empty parent model variable that differs from the overlay value", () => { - const { env, replaced } = ompChildEnvironment( - { PI_SMOL_MODEL: "paid/x", PI_SLOW_MODEL: roles["slow"], PI_PLAN_MODEL: "" }, - OVERLAY_PATH, - LADDER_MODEL, - ); - expect(replaced).toEqual(["PI_SMOL_MODEL"]); - expect(env["PI_SMOL_MODEL"]).toBe(roles["smol"]); - expect(env["PI_SLOW_MODEL"]).toBe(roles["slow"]); - expect(env["PI_PLAN_MODEL"]).toBe(roles["plan"]); - }); - - it("lists replaced variables in smol, slow, plan order", () => { - const { replaced } = ompChildEnvironment( - { PI_PLAN_MODEL: "paid/p", PI_SLOW_MODEL: "paid/s", PI_SMOL_MODEL: "paid/x" }, - OVERLAY_PATH, - LADDER_MODEL, - ); - expect(replaced).toEqual(["PI_SMOL_MODEL", "PI_SLOW_MODEL", "PI_PLAN_MODEL"]); - }); - - it("does not mutate the parent environment", () => { - const parent = { PI_CONFIG_FILES: join("team", "a.yml"), PI_SMOL_MODEL: "paid/x" }; - const before = { ...parent }; - const { env } = ompChildEnvironment(parent, OVERLAY_PATH, LADDER_MODEL); - expect(parent).toEqual(before); - expect(env).not.toBe(parent); - }); -}); diff --git a/cli/test/unit/ompSession.test.ts b/cli/test/unit/ompSession.test.ts deleted file mode 100644 index 2be0a1272..000000000 --- a/cli/test/unit/ompSession.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -import { - chmodSync, - existsSync, - mkdirSync, - mkdtempSync, - rmSync, - statSync, - writeFileSync, -} from "node:fs"; -import { homedir, tmpdir } from "node:os"; -import { join } from "node:path"; -import { DatabaseSync } from "node:sqlite"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; - -import { kitDbFile } from "../../src/engine-native/kitDb"; -import { - engineHome, - readOmpSessionModel, - writeOmpSessionModel, -} from "../../src/engine-native/ompSession"; - -let home = ""; - -function legacyFile(): string { - return join(home, ".docks-kit", "state.json"); -} - -function writeLegacyState(content: string): void { - mkdirSync(join(home, ".docks-kit"), { recursive: true }); - writeFileSync(legacyFile(), content); -} - -/** The rows of `harness_selection`, which schema 1 keeps and nothing reads. */ -function harnessRows(): Array { - const db = new DatabaseSync(kitDbFile(home), { readOnly: true }); - try { - return db.prepare("SELECT harness FROM harness_selection").all(); - } finally { - db.close(); - } -} - -beforeEach(() => { - home = mkdtempSync(join(tmpdir(), "docks-omp-session-")); -}); - -afterEach(() => { - rmSync(home, { recursive: true, force: true }); -}); - -describe("kit store", () => { - it("imports the session model of a valid legacy state.json once and renames it", () => { - writeLegacyState( - JSON.stringify({ - version: 1, - harnesses: ["omp", "agents"], - ompSession: { selector: "a/b", thinking: "high" }, - }), - ); - - expect(readOmpSessionModel(home)).toEqual({ selector: "a/b", thinking: "high" }); - expect(existsSync(legacyFile())).toBe(false); - expect(existsSync(`${legacyFile()}.migrated`)).toBe(true); - }); - - it("imports no harness selection from a legacy state.json", () => { - writeLegacyState( - JSON.stringify({ - version: 1, - harnesses: ["omp", "agents"], - ompSession: { selector: "a/b" }, - }), - ); - - expect(readOmpSessionModel(home)).toEqual({ selector: "a/b" }); - expect(harnessRows()).toEqual([]); - }); - - it("does not replace a stored session model with a late legacy file", () => { - writeOmpSessionModel(home, { selector: "provider/current", thinking: "high" }); - writeLegacyState( - JSON.stringify({ - version: 1, - ompSession: { selector: "provider/old", thinking: "low" }, - }), - ); - - expect(readOmpSessionModel(home)).toEqual({ - selector: "provider/current", - thinking: "high", - }); - expect(existsSync(legacyFile())).toBe(false); - expect(existsSync(`${legacyFile()}.migrated`)).toBe(true); - }); - - it("imports nothing from an invalid legacy file and still renames it", () => { - writeLegacyState("{invalid"); - - expect(readOmpSessionModel(home)).toBeUndefined(); - expect(existsSync(legacyFile())).toBe(false); - expect(existsSync(`${legacyFile()}.migrated`)).toBe(true); - }); - - it("ignores an unsupported legacy state version", () => { - writeLegacyState( - JSON.stringify({ - version: 2, - ompSession: { selector: "provider/too-new" }, - }), - ); - - expect(readOmpSessionModel(home)).toBeUndefined(); - expect(existsSync(legacyFile())).toBe(false); - expect(existsSync(`${legacyFile()}.migrated`)).toBe(true); - }); - - it("creates no store when a read finds neither file", () => { - expect(readOmpSessionModel(home)).toBeUndefined(); - expect(existsSync(kitDbFile(home))).toBe(false); - }); - - it("treats a corrupt SQLite store as a missing session model", () => { - mkdirSync(join(home, ".docks-kit")); - writeFileSync(kitDbFile(home), "not a SQLite database"); - - expect(readOmpSessionModel(home)).toBeUndefined(); - }); - - it("refuses a store from a newer schema", () => { - writeOmpSessionModel(home, { selector: "provider/current" }); - const db = new DatabaseSync(kitDbFile(home)); - db.exec("PRAGMA user_version = 99"); - db.close(); - - expect(readOmpSessionModel(home)).toBeUndefined(); - expect(() => writeOmpSessionModel(home, { selector: "provider/next" })).toThrow( - /schema 99.*Upgrade docks-kit/s, - ); - const after = new DatabaseSync(kitDbFile(home), { readOnly: true }); - const version = after.prepare("PRAGMA user_version").get()?.["user_version"]; - const rows = after.prepare("SELECT selector FROM omp_session").all(); - after.close(); - expect(version).toBe(99); - expect(rows).toEqual([{ selector: "provider/current" }]); - }); - - it("records the schema migration and preserves rows across opens", () => { - writeOmpSessionModel(home, { selector: "a/b" }); - - const db = new DatabaseSync(kitDbFile(home), { readOnly: true }); - const version = db.prepare("PRAGMA user_version").get()?.["user_version"]; - db.close(); - expect(version).toBe(1); - expect(readOmpSessionModel(home)).toEqual({ selector: "a/b" }); - }); - - it("creates a private store and directory under the selected home", () => { - writeOmpSessionModel(home, { selector: "a/b" }); - - const stateFile = kitDbFile(home); - expect(existsSync(stateFile)).toBe(true); - if (process.platform !== "win32") { - expect(statSync(stateFile).mode & 0o777).toBe(0o600); - expect(statSync(join(home, ".docks-kit")).mode & 0o777).toBe(0o700); - } - }); - - it("tightens an existing permissive state directory to 0700", () => { - if (process.platform === "win32") return; - mkdirSync(`${home}/.docks-kit`, { recursive: true, mode: 0o755 }); - chmodSync(`${home}/.docks-kit`, 0o755); - - writeOmpSessionModel(home, { selector: "a/b" }); - - expect(statSync(`${home}/.docks-kit`).mode & 0o777).toBe(0o700); - }); - - it("reads an existing store without changing its permissions", () => { - if (process.platform === "win32") return; - writeOmpSessionModel(home, { selector: "a/b" }); - chmodSync(`${home}/.docks-kit`, 0o755); - chmodSync(kitDbFile(home), 0o644); - - expect(readOmpSessionModel(home)).toEqual({ selector: "a/b" }); - expect(statSync(`${home}/.docks-kit`).mode & 0o777).toBe(0o755); - expect(statSync(kitDbFile(home)).mode & 0o777).toBe(0o644); - }); - - it("keeps the session models of separate homes independent", () => { - const otherHome = mkdtempSync(join(tmpdir(), "docks-omp-session-other-")); - try { - writeOmpSessionModel(home, { selector: "provider/first" }); - writeOmpSessionModel(otherHome, { selector: "provider/second" }); - - expect(readOmpSessionModel(home)).toEqual({ selector: "provider/first" }); - expect(readOmpSessionModel(otherHome)).toEqual({ selector: "provider/second" }); - } finally { - rmSync(otherHome, { recursive: true, force: true }); - } - }); - - it("resolves the engine home from HOME with a homedir fallback", () => { - expect(engineHome({ HOME: "/fixture/home" }, "linux")).toBe("/fixture/home"); - expect(engineHome({}, "linux")).toBe(homedir()); - expect(engineHome({ HOME: "" }, "darwin")).toBe(homedir()); - }); - - it("resolves the engine home from USERPROFILE on Windows and ignores HOME", () => { - expect(engineHome({ HOME: "C:\\msys64\\home\\u", USERPROFILE: "C:\\Users\\u" }, "win32")).toBe( - "C:\\Users\\u", - ); - expect(engineHome({ HOME: "C:\\msys64\\home\\u" }, "win32")).toBe(homedir()); - expect(engineHome({ HOME: "C:\\msys64\\home\\u", USERPROFILE: "" }, "win32")).toBe(homedir()); - }); -}); - -describe("omp session model state", () => { - it("drops a blank legacy level and the retired advisor level on import", () => { - writeLegacyState( - JSON.stringify({ - version: 1, - ompSession: { selector: "provider/model-free", thinking: " ", advisorThinking: "low" }, - }), - ); - - expect(readOmpSessionModel(home)).toEqual({ selector: "provider/model-free" }); - }); - - it("leaves no stale level behind when a level-free model overwrites a levelled one", () => { - writeOmpSessionModel(home, { selector: "provider/model-free", thinking: "xhigh" }); - - writeOmpSessionModel(home, { selector: "provider/other-free" }); - - expect(readOmpSessionModel(home)).toEqual({ selector: "provider/other-free" }); - }); - - it("stores whitespace-only levels as absent", () => { - writeOmpSessionModel(home, { selector: "provider/model-free", thinking: " " }); - - expect(readOmpSessionModel(home)).toEqual({ selector: "provider/model-free" }); - }); - - it("rejects a blank selector without losing the saved model", () => { - writeOmpSessionModel(home, { selector: "provider/current", thinking: "high" }); - - expect(() => writeOmpSessionModel(home, { selector: " ", thinking: "xhigh" })).toThrow( - /selector/i, - ); - expect(readOmpSessionModel(home)).toEqual({ selector: "provider/current", thinking: "high" }); - }); -}); diff --git a/cli/test/unit/removedNames.test.ts b/cli/test/unit/removedNames.test.ts index 80683c0fa..c76f894f4 100644 --- a/cli/test/unit/removedNames.test.ts +++ b/cli/test/unit/removedNames.test.ts @@ -4,33 +4,77 @@ * home folder. Codex left in 0.23.0 (#181), Claude Code in the same release * (#182), and universal skills, the sync targets, `--prune`, and the * `harnesses` and `skills` commands left in 0.24.0 (#183). - * `--skip-plugin-refresh` left in 0.30.0 (#252). + * `--skip-plugin-refresh` left in 0.30.0 (#252). The `omp` free-model + * launcher left in 0.32.0 (#283). */ import { spawnSync } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { delimiter, join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; -import { cliEntry } from "../lib/cliEntry"; +import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; const CLI = cliEntry(); const home = mkdtempSync(join(tmpdir(), "removed-names-")); +const stubDir = mkdtempSync(join(tmpdir(), "removed-names-bin-")); +afterAll(() => { + rmSync(home, { recursive: true, force: true }); + rmSync(stubDir, { recursive: true, force: true }); +}); + +// A stub `omp` first on PATH records each call, so a refusal that still +// reached the removed launcher shows up as a call instead of a real session. +const ompCalls = join(stubDir, "omp-calls.log"); +const ompSource = join(stubDir, "omp.mjs"); +writeFileSync( + ompSource, + `import { appendFileSync } from "node:fs";\nappendFileSync(${JSON.stringify(ompCalls)}, process.argv.slice(2).join(" ") + "\\n");\n`, +); +if (process.platform === "win32") { + writeFileSync( + join(stubDir, "omp.cmd"), + `@echo off\r\n"${process.execPath}" "${ompSource}" %*\r\n`, + ); +} else { + const stub = join(stubDir, "omp"); + writeFileSync(stub, `#!/bin/sh\nexec "${process.execPath}" "${ompSource}" "$@"\n`); + chmodSync(stub, 0o755); +} + // The CLI reads its home from USERPROFILE on Windows and from HOME elsewhere. -const env = { ...process.env, HOME: home, USERPROFILE: home }; -afterAll(() => rmSync(home, { recursive: true, force: true })); +// The four agent-folder variables are empty, so the child resolves +// `/.omp/agent` and never a real profile folder. +const envFor = (root: string) => ({ + ...process.env, + HOME: root, + USERPROFILE: root, + PI_CODING_AGENT_DIR: "", + OMP_PROFILE: "", + PI_PROFILE: "", + PI_CONFIG_DIR: "", + PATH: `${stubDir}${delimiter}${process.env["PATH"] ?? ""}`, +}); const HARNESS_FILES = [".agents", ".claude", ".claude.json", ".codex"]; /** Run the public CLI, then check that the refusal wrote no harness file. */ -function run(args: ReadonlyArray) { - const result = spawnSync("bun", [CLI, ...args], { +function run(args: ReadonlyArray, root = home) { + const result = spawnSync(BUN_RUNTIME, [CLI, ...args], { encoding: "utf8", - env, + env: envFor(root), timeout: SPAWN_TIMEOUT_MS, }); for (const file of HARNESS_FILES) { - expect(existsSync(join(home, file)), `${args.join(" ")}: ${file}`).toBe(false); + expect(existsSync(join(root, file)), `${args.join(" ")}: ${file}`).toBe(false); } return result; } @@ -107,6 +151,35 @@ describe("names removed by the omp-only cutover", () => { SPAWN_TIMEOUT_MS, ); + it( + "refuses the removed omp launcher and its toggles without starting omp or writing config.yml", + () => { + // Its own home, with a deployed config.yml that a removed toggle must leave unchanged. + const ompHome = mkdtempSync(join(tmpdir(), "removed-names-omp-")); + try { + const CONFIG = "tier:\n openai: none\n"; + const configPath = join(ompHome, ".omp", "agent", "config.yml"); + mkdirSync(join(ompHome, ".omp", "agent"), { recursive: true }); + writeFileSync(configPath, CONFIG); + + const bare = run(["omp"], ompHome); + expect(bare.status).toBe(1); + expect(bare.stderr).toContain('Unknown subcommand "omp" for "docks-kit"'); + + const toggle = run(["omp", "--fast"], ompHome); + expect(toggle.status).toBe(2); + expect(toggle.stderr).toContain("unknown command 'omp'"); + + expect(existsSync(ompCalls)).toBe(false); + expect(readFileSync(configPath, "utf8")).toBe(CONFIG); + expect(existsSync(join(ompHome, ".docks-kit", "kit.db"))).toBe(false); + } finally { + rmSync(ompHome, { recursive: true, force: true }); + } + }, + SPAWN_TIMEOUT_MS, + ); + it( "refuses the removed toolchain upgrade operation", () => { From 6b097a4dbcc20d37dacfcc56ac95c60c6eaeef22 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:48:31 -0300 Subject: [PATCH 3/7] Check the packaged root tier flags in the package smoke - Toggle --fast on and off in a temporary home of the installed package, with the agent-folder variables empty, and check that both root flags together exit 2 with no write. Refs #283 Verified: bun run smoke:package; bun run lint; bun run check:types --- cli/scripts/package-smoke.ts | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/cli/scripts/package-smoke.ts b/cli/scripts/package-smoke.ts index 14a6d7510..f5c65af0d 100644 --- a/cli/scripts/package-smoke.ts +++ b/cli/scripts/package-smoke.ts @@ -334,6 +334,63 @@ function assertUnrelatedFolderRuns(workDir: string, binaryPath: string, expected } } +const TIER_CONFIG = "# smoke\ntier:\n openai: none\n"; + +/** + * The packaged root flags toggle `tier.openai` in a temporary home. The four + * agent-folder variables are empty, so the toggle can write only the seeded + * config.yml of that home, never a real omp profile. + */ +function assertTierToggles(workDir: string, binaryPath: string): void { + const home = join(workDir, "tier-home"); + const configPath = join(home, ".omp", "agent", "config.yml"); + mkdirSync(join(home, ".omp", "agent"), { recursive: true }); + writeFileSync(configPath, TIER_CONFIG); + const env: NodeJS.ProcessEnv = { + ...CHILD_ENV, + HOME: home, + USERPROFILE: home, + PI_CODING_AGENT_DIR: "", + OMP_PROFILE: "", + PI_PROFILE: "", + PI_CONFIG_DIR: "", + }; + const runToggle = (args: ReadonlyArray) => + spawnSync(binaryPath, args, { cwd: home, encoding: "utf8", env }); + + for (const [next, state] of [ + ["priority", "ON"], + ["none", "OFF"], + ] as const) { + const run = runToggle(["--fast"]); + requireSuccess("installed docks-kit --fast", run); + const config = readFileSync(configPath, "utf8"); + if (!run.stdout.includes(`fast mode ${state}`) || !config.includes(`openai: ${next}`)) { + fail( + `assertion "installed --fast toggles tier.openai to ${next}" failed: observed ` + + `${JSON.stringify(run.stdout.trim())} and config ${JSON.stringify(config)}. Repair: check the root ` + + `--fast flag in cli/src/commands/root.ts and the bundle build.`, + ); + } + console.log(`[package-smoke] docks-kit --fast: ${run.stdout.trim().split("\n")[0]}`); + } + + const both = runToggle(["--fast", "--ultrafast"]); + const unchanged = readFileSync(configPath, "utf8") === TIER_CONFIG; + if ( + both.status !== 2 || + !both.stderr.includes("Pass either --fast or --ultrafast, not both") || + !unchanged + ) { + fail( + `assertion "installed --fast --ultrafast exits 2 with no write" failed: observed exit ` + + `${both.status ?? "unknown"}, stderr ${JSON.stringify(both.stderr.trim())}, config unchanged ${unchanged}. ` + + `Repair: refuse both root flags before any lock or write in cli/src/commands/root.ts.`, + ); + } + console.log("[package-smoke] docks-kit --fast --ultrafast: exit 2, config.yml unchanged"); +} + function median(samples: ReadonlyArray): number { const sorted = [...samples].sort((a, b) => a - b); const middle = Math.floor(sorted.length / 2); @@ -404,6 +461,7 @@ function smoke(workDir: string, manifest: Manifest, pins: ReadonlyArray): v const binaryPath = assertBinTarget(consumerDir); assertTarballContents(tarball); assertUnrelatedFolderRuns(workDir, binaryPath, manifest.version); + assertTierToggles(workDir, binaryPath); assertStartTime(consumerDir, binaryPath); } From f65ef567b9938dbea4d4669fd8185d23d1cd08e6 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:49:41 -0300 Subject: [PATCH 4/7] Document the root tier flags and release 0.32.0 - Replace the launcher text in the README, cli/AGENTS.md, the CLI docs, DESIGN.md, and the omp-sync, sync-orchestration, and tidy skills with the root --fast and --ultrafast flags. - Add the 0.32.0 changelog entry with the replacement for each old form. - Bump to 0.32.0; rebuild the talk bundle, the payload, and both goldens. Refs #283 Verified: bun run check:generated; bun run golden:dryrun; bun run golden:mutation; bunx vitest run cli/test/unit/skillMetadata.test.ts --- .agents/skills/omp-sync-context/SKILL.md | 31 ++- .../references/state-and-launcher.md | 111 ++++------ .../sync-orchestration-context/SKILL.md | 23 +- .agents/skills/tidy-context/SKILL.md | 2 +- CHANGELOG.md | 27 +++ README.md | 5 +- SoT/.omp/plugin/extensions/talk.js | 2 +- cli/AGENTS.md | 26 +-- cli/docs/flags.md | 63 ++---- cli/docs/omp-models.md | 206 ++---------------- cli/docs/overview.md | 2 +- cli/src/engine-native/DESIGN.md | 4 +- cli/src/generated/sotPayload.ts | 6 +- cli/test/goldens/dryrun.json | 4 +- cli/test/goldens/mutation.json | 48 ++-- package.json | 2 +- 16 files changed, 184 insertions(+), 378 deletions(-) diff --git a/.agents/skills/omp-sync-context/SKILL.md b/.agents/skills/omp-sync-context/SKILL.md index 37670e0e9..09d7a22d0 100644 --- a/.agents/skills/omp-sync-context/SKILL.md +++ b/.agents/skills/omp-sync-context/SKILL.md @@ -1,6 +1,6 @@ --- name: omp-sync-context -description: "Use when changing the docks-kit omp harness: the omp sync pipeline (ompSync.ts, syncDispatch.ts engineSync), omp paths (ompPaths.ts), deploy, YAML merge, and retired-key prune of config.yml and models.yml (ompFileDeploy.ts, ompYaml.ts, ompRemovals.ts), the plugin pass and the docks marketplace retirement (ompPlugins.ts, ompKitPlugin.ts, ompChild.ts), the session model in kit.db (ompSession.ts, kitDb.ts), or the docks-kit omp free-session launcher (commands/omp.ts, ompOverlay.ts). Covers the dry-run boundary, the pi-intercom notice, the omp folder locks and the omp child environment (ompWriteFolders, spawnOmp, omp --fast), and private file modes. Not for cross-cutting sync flags (use sync-orchestration-context) or tool pins (use toolchain-context)." +description: "Use when changing the omp harness of docks-kit: the omp sync pipeline (ompSync.ts, syncDispatch.ts engineSync), omp paths (ompPaths.ts), deploy, YAML merge, and retired-key prune of config.yml and models.yml (ompFileDeploy.ts, ompYaml.ts, ompRemovals.ts), the plugin pass and the docks marketplace retirement (ompPlugins.ts, ompKitPlugin.ts, ompChild.ts), the kit store kit.db (kitDb.ts), or the root tier toggles docks-kit --fast and --ultrafast (commands/root.ts, ompFastMode.ts). Covers the dry-run boundary, the pi-intercom notice, the omp folder locks and the omp child environment (ompWriteFolders, spawnOmp, toggleTierUnderLocks), and private file modes. Not for cross-cutting sync flags (use sync-orchestration-context) or tool pins (use toolchain-context)." user-invocable: false metadata: pattern: tool-wrapper @@ -21,14 +21,12 @@ metadata: lines: "1-123" - path: cli/src/engine-native/ompYaml.ts lines: "1-213" - - path: cli/src/engine-native/ompSession.ts - lines: "1-67" + - path: cli/src/engine-native/home.ts + lines: "1-15" - path: cli/src/engine-native/kitDb.ts - lines: "1-240" - - path: cli/src/engine-native/ompOverlay.ts - lines: "1-264" - - path: cli/src/commands/omp.ts - lines: "1-426" + lines: "1-177" + - path: cli/src/commands/root.ts + lines: "1-133" - path: cli/src/engine-native/syncDispatch.ts lines: "1-215" - path: cli/src/engine-native/atomicWrite.ts @@ -42,7 +40,7 @@ metadata: # omp Sync Context -EngineNative owns omp configuration deployment, plugin reconciliation, and the omp session model. +EngineNative owns omp configuration deployment, plugin reconciliation, the kit store, and the root tier toggles. Use this context for omp-specific behavior only. Pointers here name concepts, not coordinates — if a path or symbol moved, trust the stated purpose and re-locate it (grep the symbol) before acting. @@ -95,8 +93,8 @@ and `bunx vitest run cli/test/unit/ompPaths.test.ts -t "prefers OMP_PROFILE even - Change omp deployment file modes, backups, or restart triggers. - Change the retired-entry prune in `ompRemovals.ts` — `syncOmpRemovals` or `syncOmpModelRemovals`. - Change omp plugin reconciliation or the retirement of the former `docks` marketplace plugins. -- Change `readOmpSessionModel` or `writeOmpSessionModel` in `ompSession.ts`. -- Change the free-session run overlay in `ompOverlay.ts` or the launcher in `cli/src/commands/omp.ts`. +- Change the kit store in `kitDb.ts` — `withKitDb`, `MIGRATIONS`, `readCache`, or `writeCache`. +- Change the root tier toggles in `cli/src/commands/root.ts` — `toggleTierUnderLocks` — or in `ompFastMode.ts`. - Change the omp pipeline call in `syncDispatch.ts` — `engineSync`. Use `sync-orchestration-context` for a sync flag. @@ -232,11 +230,10 @@ folder of `ompSync.ts ompWriteFolders`: the `ompPaths` `agentDir` and the `agentDir`, an empty `/` folder can appear. - `~/.docks-kit/omp-plugin` and the retired upgrade-log folder that each sync removes stay under the home, so the home lock covers them. -- `commands/omp.ts toggleFastUnderLocks` checks `/config.yml` before +- `commands/root.ts toggleTierUnderLocks` checks `/config.yml` before any lock (`ompFastMode.ts requireDeployedConfig`). A missing file exits 2, - and the run creates no omp folder. Otherwise it runs `docks-kit omp --fast` - or `--ultrafast` - under the home sync lock and always the `agentDir` lock + and the run creates no omp folder. Otherwise it runs `docks-kit --fast` or + `--ultrafast` under the home sync lock and always the `agentDir` lock (`syncDispatch.ts withHomeAndFolderLocks`), with the wait and the held line of a sync. - The locks cover the folder that the kit deploys into, not the target of a @@ -250,7 +247,7 @@ folder of `ompSync.ts ompWriteFolders`: the `ompPaths` `agentDir` and the Verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "shared omp agent folder"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "shared omp data root"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps each omp child on the locked config root"`, -and `bunx vitest run cli/test/unit/ompFastMode.test.ts -t "omp --fast under the folder lock"`. +and `bunx vitest run cli/test/unit/ompFastMode.test.ts -t "--fast under the folder lock"`. ### Private Mode Pattern @@ -274,7 +271,7 @@ and `bunx vitest run cli/test/unit/ompKitPlugin.test.ts -t "removes stale files - `references/yaml-merge.md` - YAML merge contract and the retired-entry prune. - `references/plugins-and-marketplace.md` - plugin constraints, the retirement of the former marketplace plugins, inventory contract, dry-run rules, and the pi-intercom notice. -- `references/state-and-launcher.md` - kit.db state store, session model, and the free-session launcher. +- `references/state-and-launcher.md` - kit.db store (schema, migrations, unused tables, too-new refusal, cache) and the root tier toggles. ## Change Checklist diff --git a/.agents/skills/omp-sync-context/references/state-and-launcher.md b/.agents/skills/omp-sync-context/references/state-and-launcher.md index 0fc77ab17..736c9af58 100644 --- a/.agents/skills/omp-sync-context/references/state-and-launcher.md +++ b/.agents/skills/omp-sync-context/references/state-and-launcher.md @@ -1,74 +1,59 @@ -# omp State Store And Launcher +# Kit Store And Root Tier Toggles Part of `omp-sync-context`. Read the SKILL.md constraints first. -## Local State Store +## Kit Store -Store the omp session model in the SQLite store `~/.docks-kit/kit.db`, table -`omp_session`. The `harness_selection` table has had no use since 0.24.0 and -stays in `kitDb.ts MIGRATIONS[0]` only to keep schema 1; a `DROP` migration -would raise the schema and make older kits refuse the store. -Resolve that path from the engine home with `kitDb.ts kitDbFile`. +The SQLite store `~/.docks-kit/kit.db` holds the TTL cache `cache_entry`, +which `toolchain outdated` uses through `kitDb.ts readCache` and `writeCache`. +Schema 1 also keeps the tables `omp_session` and `harness_selection`. No code +reads or writes them. They stay in `kitDb.ts MIGRATIONS[0]` only to keep +schema 1, so older kits still open the store; a `DROP` migration would raise +the schema and make older kits refuse the store. +Resolve the store path from the engine home (`home.ts engineHome`) with +`kitDb.ts kitDbFile`. Open the store only through `kitDb.ts withKitDb`, which applies the migrations. Append a new migration to `kitDb.ts MIGRATIONS`; never edit a shipped entry. +Give `cache_entry` a drop-and-recreate migration when its shape changes, +because every row can be fetched again. Write the state directory with mode `0700`. Chmod the database file to mode `0600`. -Never create the store on a read when neither `kit.db` nor `state.json` exists. - -`withKitDb` imports the session model of a legacy `~/.docks-kit/state.json` -once, when `omp_session` is empty, and renames the file to -`state.json.migrated`. It imports no harness selection. -Each table has one writer. - -`ompSession.ts readOmpSessionModel` treats a missing, corrupt, or too-new -store as no stored session model. +Never create the store on a read when `kit.db` does not exist. +A read of an existing store changes no permissions, so it works on a home +that cannot be written. + +`withKitDb` refuses a store whose `user_version` is above +`KIT_DB_SCHEMA_VERSION` with `KitDbTooNewError`, which tells the user to run +`docks-kit update`. The check runs again under the migration lock, so a +newer kit that migrates in parallel is never downgraded. +`readCache` treats a missing, corrupt, or too-new store as a cache miss, and +`writeCache` ignores a failed write, because the cache is an optimization. +Cache rows carry the kit version as fingerprint, so a new release fetches +them again. `sync` never opens `kit.db`. -Every `docks-kit omp` launch writes a run overlay under `kitCacheDir`; -only `--model` or `--pick` writes the `omp_session` table. -`docks-kit omp --fast` and `--ultrafast` write only `tier.openai` in the -deployed `config.yml`, through `ompFastMode.ts toggleDeployedOpenAiTier`. -The session model entry stores a required free model selector and an optional session thinking level. -Every overlay role, `advisor` included, runs that one level. -Compute the level once at set time from the catalog row of the chosen model. -Derive the level from that model's own ladder, never from the global ladder -constant: free-model ladders differ per model, and some publish no `medium` -or no ladder (`cli/docs/omp-models.md`; verify: `omp models --json`). -Store no level for a model without a ladder, and render a bare selector for it. -An invented level makes omp fail when the session starts, not when the user -chooses the model. -Treat a missing, blank, or malformed entry as no stored model, and resolve it -to `DEFAULT_OMP_SESSION_MODEL`. -Never throw on a corrupt entry, because a launcher that refuses to start is -worse than one that starts on the default free model. -Drop the level field when it is blank, so a stale level never -survives a switch to a level-free model. - -Anchor storage at `ompSession.ts` — `readOmpSessionModel` and `writeOmpSessionModel` — the `omp_session` table opened through `kitDb.ts withKitDb`. -Anchor rendering at `ompOverlay.ts` — `ladderCeiling`, `planEffortChoice`, and `renderFreeOverlay` — per-model ladder derivation, the picker question set, and empty fallback chains, including the chains keyed by the free model at every level. - -The launcher enforces the free model before omp starts. -Reject each forwarded flag that can select a model, in both forms and also after a `--`, because omp can read that `--` as a flag value. -Start omp with `launch` first, so a forwarded subcommand name becomes message text. -Pass the session model as an explicit `--model`, so a restored session model cannot replace it. -Set the three model variables in the child environment instead of removing them, because omp refills an unset variable from its `.env` files. -Check the session model against the free catalog of every candidate profile. -Do not claim that the launcher controls these paths, which can still select a paid model: model selection inside a running session, the `web` role and its chain, the model-kind roles, and extensions and hooks. -`cli/docs/omp-models.md` `### Model selection outside the launcher` owns the list. -Anchor input checks at `cli/src/commands/omp.ts` — `rejectedForwardedFlag` and `forwardedProfile` — the rejected model flags and the candidate profiles, scanned past `--`. -Anchor the launch at `ompOverlay.ts` — `buildOmpArgs` and `ompChildEnvironment` — `launch` first, the explicit `--model`, the model variables, and the `PI_CONFIG_FILES` append. - Verify the store: -`bunx vitest run cli/test/unit/ompSession.test.ts -t "creates no store when a read finds neither file"`, -`bunx vitest run cli/test/unit/ompSession.test.ts -t "imports no harness selection from a legacy state.json"`, -`bunx vitest run cli/test/unit/ompSession.test.ts -t "treats a corrupt SQLite store as a missing session model"`, -`bunx vitest run cli/test/unit/ompSession.test.ts -t "refuses a store from a newer schema"`, -and `bunx vitest run cli/test/unit/ompSession.test.ts -t "leaves no stale level behind when a level-free model overwrites a levelled one"`. - -Verify the launcher and the overlay: -`bunx vitest run cli/test/unit/ompCommand.test.ts -t "rejects a model flag after a forwarded"`, -`bunx vitest run cli/test/unit/ompCommand.test.ts -t "refuses a launch whose model is free in the environment profile but not in a forwarded profile"`, -`bunx vitest run cli/test/unit/ompOverlay.test.ts -t "starts omp with launch, the overlay, and the session model at its level"`, -`bunx vitest run cli/test/unit/ompOverlay.test.ts -t "lists replaced variables in smol, slow, plan order"`, -`bunx vitest run cli/test/unit/ompOverlay.test.ts -t "renders a level-free model with bare chat selectors and no thinking keys"`, -and `bunx vitest run cli/test/unit/ompFastMode.test.ts -t "turns fast on and changes only tier.openai"`. +`bunx vitest run cli/test/unit/kitDb.test.ts -t "creates no store when a read finds no kit.db"`, +`bunx vitest run cli/test/unit/kitDb.test.ts -t "treats a corrupt SQLite store as a cache miss"`, +`bunx vitest run cli/test/unit/kitDb.test.ts -t "refuses a store from a newer schema and keeps its rows"`, +and `bunx vitest run cli/test/unit/kitDb.test.ts -t "keeps schema 1 with its unused tables, so an older kit still opens the store"`. + +## Root Tier Toggles + +`docks-kit --fast` and `docks-kit --ultrafast` are flags of the `docks-kit` +root command (`cli/src/commands/root.ts`). A subcommand does not accept them. +They write only `tier.openai` in the deployed `config.yml`, through +`ompFastMode.ts toggleDeployedOpenAiTier`, and they never open `kit.db`. +`--fast` toggles between `priority` and `none`; `--ultrafast` toggles between +`ultrafast` and `none`. Any value other than the ON tier of the flag switches +to that ON tier. +Both flags together exit 2 with `Pass either --fast or --ultrafast, not both` +before any lock or write. +`root.ts toggleTierUnderLocks` owns the config check and the locks (see +SKILL.md `### Folder Locks`). + +Verify the toggles: +`bunx vitest run cli/test/unit/ompFastMode.test.ts -t "turns fast on and changes only tier.openai"`, +`bunx vitest run cli/test/unit/rootFlags.test.ts -t "turns fast mode on and off and changes only tier.openai"`, +`bunx vitest run cli/test/unit/rootFlags.test.ts -t "turns ultrafast mode on and off and changes only tier.openai"`, +and `bunx vitest run cli/test/unit/rootFlags.test.ts -t "with exit 2 before any lock or write"`. diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index 7c4c0e7aa..fa121b51a 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -8,13 +8,15 @@ metadata: - path: docks-kit lines: "1-100" - path: cli/src/main.ts - lines: "1-88" + lines: "1-60" + - path: cli/src/commands/root.ts + lines: "1-133" - path: cli/src/argv.ts lines: "1-59" - path: cli/src/argvValidate.ts lines: "1-57" - path: cli/src/argvSurface.ts - lines: "1-410" + lines: "1-351" - path: cli/src/engine.ts lines: "1-53" - path: cli/src/kitHome.ts @@ -131,7 +133,7 @@ For the doctor report and Bun managed install, use | Invocation | Path | Notes | |-----------|------|-------| | `./docks-kit ` | Host check, then Bun-from-source | The launcher rejects a host outside the support matrix, finds or installs Bun, runs `bun install --frozen-lockfile` when `node_modules/effect` is absent, and then runs `cli/src/main.ts`. It never runs a file in `cli/dist/`, so a leftover binary cannot mask newer source. | -| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` skips `prepareArgv` and Effect and calls `runEngineNative` directly with `{ envGlobals: true }`. Otherwise mutating commands run through `engine(args)`. The root command registers `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use. A new subcommand needs an entry there and a `Console.log` line in the hand-written root overview in `main.ts`. A new engine mode also needs a `case` arm in `index.ts runEngineNative`. | +| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` skips `prepareArgv` and Effect and calls `runEngineNative` directly with `{ envGlobals: true }`. Otherwise mutating commands run through `engine(args)`. `main.ts` adds `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use, to `commands/root.ts rootCommand` through `Command.withSubcommands`. A new subcommand needs an entry there and a line in the hand-written root overview `root.ts SUMMARY`. A new engine mode also needs a `case` arm in `index.ts runEngineNative`. | | `cli/src/argv.ts` | `prepareArgv` | Validates and normalizes argv before Effect parses it. See § Public Argv Layer. | | `cli/src/engine.ts` | `engine` | Exits 2 on an unsupported host or `DOCKS_KIT_ENGINE=bash`, then runs EngineNative in-process with `{ envGlobals: false }`. `native-raw` is the harness-private golden channel. | | `cli/src/engine-native/index.ts` | `runEngineNative(argv, services?, options?)` | Builds `ctx` through `engineCtx.ts makeCtx`, then dispatches `toolchain` and `sync`. Any other first word also runs sync. `options.envGlobals` defaults to false; only the `main.ts` `native-raw` branch passes `{ envGlobals: true }`. | @@ -144,8 +146,10 @@ Do not add a new fallback behind `DOCKS_KIT_ENGINE`. `cli/src/argv.ts prepareArgv` runs before Effect parses anything. It scans argv against the surfaces that `argvSurface.ts buildSurfaces` derives from the -command definitions. `argvValidate.ts validateScannedArgv` then rejects with -exit 2. It checks in this order: +command definitions: one surface for each subcommand, and `rootSurface` for +the flags of the root command. `rootSurface` applies only when argv names no +subcommand. `argvValidate.ts validateScannedArgv` then rejects with exit 2. It +checks in this order: 1. An unknown command that also carries a flag that the scan cannot resolve. A bare unknown command passes this layer, and Effect rejects it with exit 1. @@ -159,8 +163,10 @@ exit 2. It checks in this order: - A removed flag such as `--prune`, `--agents`, `--omp`, or `--remove-plugins` gets the plain `unknown flag for 'sync'` refusal. The kit keeps no rename-hint table. +- The root flags `--fast` and `--ultrafast` are local to the root command, so + `docks-kit sync --fast` gets `unknown flag --fast for 'sync'` and exit 2. -(verify: `bunx vitest run cli/test/unit/removedNames.test.ts -t "refuses the removed sync flags as unknown flags"`, `bunx vitest run cli/test/unit/argv.test.ts -t "rejects --prune as unknown now that universal skills are gone"`, and `bunx vitest run cli/test/unit/argv.test.ts -t "rejects a separate boolean literal after the sync dry-run boolean"`) +(verify: `bunx vitest run cli/test/unit/removedNames.test.ts -t "refuses the removed sync flags as unknown flags"`, `bunx vitest run cli/test/unit/argv.test.ts -t "rejects --prune as unknown now that universal skills are gone"`, `bunx vitest run cli/test/unit/argv.test.ts -t "rejects a separate boolean literal after the sync dry-run boolean"`, and `bunx vitest run cli/test/unit/rootFlags.test.ts -t "stays a root flag: sync refuses it as its own unknown flag"`) ## Core Patterns @@ -252,8 +258,9 @@ each writer of such a folder also takes `/.docks-kit-sync-lock.db` chmod, and the lock keeps the folder mode (`privateDirectory: false`). The omp pipeline then runs `ensureDirectory` (mode 0700) under the locks. - `withHomeAndFolderLocks(home, folders, err, body)` takes the home lock and - the folder locks outside a sync run. `docks-kit omp --fast` uses it for the - omp agent folder (see `omp-sync-context`). + the folder locks outside a sync run. `docks-kit --fast` and + `docks-kit --ultrafast` use it for the omp agent folder (see + `omp-sync-context`). - A dry run (`ctx.dryRun`) takes no folder lock and creates no folder. The held line and the wait bound are those of the home lock. diff --git a/.agents/skills/tidy-context/SKILL.md b/.agents/skills/tidy-context/SKILL.md index 7dd1b150f..7c68f8d7a 100644 --- a/.agents/skills/tidy-context/SKILL.md +++ b/.agents/skills/tidy-context/SKILL.md @@ -171,7 +171,7 @@ Probes: `bunx vitest run cli/test/unit/scratch.test.ts -t "refuses a symbolic li - A module-level set keeps each held connection, so the garbage collector cannot close a lock that a caller dropped. - `releaseKitLock` runs `ROLLBACK`, closes the connection, and removes it from the set. - The database stays in rollback journal mode. Never set WAL on a lock file. -- Lock files: `scratch.ts tidyApplyLockPath` gives `~/.cache/docks-kit/tidy-lock.db` (`tidy --apply`). `syncLockPath` gives `sync-lock.db` (sync and `omp --fast`; see `sync-orchestration-context`). `folderSyncLockPath` gives `/.docks-kit-sync-lock.db` in an agents or omp folder that a sync or `omp --fast` writes. These locks keep the folder mode (`privateDirectory: false`). A legacy text `tidy.lock` is not a database, and no code reads it. +- Lock files: `scratch.ts tidyApplyLockPath` gives `~/.cache/docks-kit/tidy-lock.db` (`tidy --apply`). `syncLockPath` gives `sync-lock.db` (sync, `--fast`, and `--ultrafast`; see `sync-orchestration-context`). `folderSyncLockPath` gives `/.docks-kit-sync-lock.db` in an agents or omp folder that a sync or a root tier toggle writes. These locks keep the folder mode (`privateDirectory: false`). A legacy text `tidy.lock` is not a database, and no code reads it. - Probes: `bunx vitest run cli/test/unit/kitLock.test.ts -t "lets exactly one of 8 racing processes"`; `bunx vitest run cli/test/unit/kitLock.test.ts -t "lets exactly one of 4 racers that start at the same moment"`; `bunx vitest run cli/test/unit/kitLock.test.ts -t "lets a contender take the lock after the holder process gets SIGKILL"`; `bunx vitest run cli/test/unit/kitLock.test.ts -t "keeps the lock across a forced garbage collection"`. ### Report diff --git a/CHANGELOG.md b/CHANGELOG.md index 20d2fd0e4..8a5120cb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## 2026-12-01 - docks-kit 0.32.0: root fast tier flags replace the free-model launcher + +The kit no longer starts omp sessions (DocksDocks/docks-kit#283). Run `omp` +directly for every session. The two OpenAI and Codex tier toggles are now +flags of `docks-kit` itself. + +### Changed + +- `docks-kit --fast` toggles `tier.openai` between `priority` and `none` in + the deployed omp `config.yml`, and `docks-kit --ultrafast` toggles it + between `ultrafast` and `none`. They replace `docks-kit omp --fast` and + `docks-kit omp --ultrafast`, with the same output, locks, and exit codes. +- Both flags together exit 2 with `Pass either --fast or --ultrafast, not + both`, before any lock or write. + +### Removed + +- `docks-kit omp`, with `--model`, `--pick`, and its forwarded arguments. + The command is now an unknown subcommand. Replace `docks-kit omp [args]` + with `omp [args]`, and choose a model with omp's own `--model` or + `/model`. Replace `docks-kit omp --fast` with `docks-kit --fast`, and + `docks-kit omp --ultrafast` with `docks-kit --ultrafast`. +- The remembered free model in `~/.docks-kit/kit.db` and the one-time import + of a legacy `~/.docks-kit/state.json`. The store keeps its schema, so an + older kit still opens it; no code reads the old table now. The cached run + overlays under `~/.cache/docks-kit` stay until you remove them. + ## 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. diff --git a/README.md b/README.md index 0fe57a985..1bab94eea 100644 --- a/README.md +++ b/README.md @@ -37,9 +37,8 @@ Invoke-WebRequest. ```text docks-kit sync [--dry-run] deploy the omp SoT to this machine docks-kit update [--no-sync] self-update the kit (autodetects checkout vs global install), then sync -docks-kit omp [--model |--pick] [args...] one omp session on a free model, nothing deployed changes -docks-kit omp --fast toggle omp fast mode for OpenAI/Codex models, then exit -docks-kit omp --ultrafast toggle omp ultrafast mode for OpenAI/Codex models, then exit +docks-kit --fast toggle omp fast mode for OpenAI/Codex models, then exit +docks-kit --ultrafast toggle omp ultrafast mode for OpenAI/Codex models, then exit docks-kit toolchain [check|ensure |outdated] verified-version floors for external tools docks-kit scratch new|remove agent temporary files and directories docks-kit tidy [--apply] [--report] remove safe agent leftovers diff --git a/SoT/.omp/plugin/extensions/talk.js b/SoT/.omp/plugin/extensions/talk.js index f5df07b48..314264934 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