@codeworksh/cli 0.0.1-dev.20260918040208 → 0.0.1-dev.20260918042316
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{catalog-DobwC9tt.mjs → catalog-Cv1zoZ5S.mjs} +2 -2
- package/{catalog-DobwC9tt.mjs.map → catalog-Cv1zoZ5S.mjs.map} +1 -1
- package/{error-Cr8LvfEq.mjs → error-zJGKAF4a.mjs} +220 -3539
- package/error-zJGKAF4a.mjs.map +1 -0
- package/{generate-BMJEbGEP.mjs → generate-DdscbX3w.mjs} +2 -2
- package/{generate-BMJEbGEP.mjs.map → generate-DdscbX3w.mjs.map} +1 -1
- package/{harness-hle7yBVs.mjs → harness-BBTdWdhx.mjs} +2 -2
- package/{harness-hle7yBVs.mjs.map → harness-BBTdWdhx.mjs.map} +1 -1
- package/index.mjs +5 -5
- package/{list-crXAfyCe.mjs → list-C6BrwuV-.mjs} +3 -3
- package/{list-crXAfyCe.mjs.map → list-C6BrwuV-.mjs.map} +1 -1
- package/package.json +4 -1
- package/{providers-BcJ_s8zf.mjs → providers-fO-GJuXn.mjs} +3 -3
- package/{providers-BcJ_s8zf.mjs.map → providers-fO-GJuXn.mjs.map} +1 -1
- package/{run-B4mqUQsS.mjs → run-CgPOJ-wJ.mjs} +3 -3
- package/{run-B4mqUQsS.mjs.map → run-CgPOJ-wJ.mjs.map} +1 -1
- package/{serve-CRUpKDkt.mjs → serve-Du6luqoi.mjs} +3 -3
- package/{serve-CRUpKDkt.mjs.map → serve-Du6luqoi.mjs.map} +1 -1
- package/error-Cr8LvfEq.mjs.map +0 -1
package/error-Cr8LvfEq.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-Cr8LvfEq.mjs","names":["AbsolutePath","ID","Usage","Service","make","resolve","layer","layer","Str","path","Global.resolve","defaultLayer","reasonOf","ID","define","AbsolutePath","Info","ID","Status","Info","RepoSchema.Vcs","ID","Kind","Status","ID","Info","ProjectSchema.ID","AbsolutePath","SandboxInstance.ID","Model","EventSchema.ID","ProjectSchema.Status","SandboxInstance.ID","SandboxInstance.Kind","SandboxInstance.Ownership","SandboxInstance.Status","SandboxInstance.PersistedError","AbsolutePath","SpaceSchema.Kind","SpaceSchema.Status","SessionSchema.IDFromDb","Error","providerCategory","SessionSchema.ID","SessionMessageSchema.ID","PromptSchema.Prompt","PromptSchema.Delivery","EventSchema.define","EventSchema.AikitAssistantMessage","ToolProgress","EventSchema.AikitToolCallTerminalPart","SessionFailure.Error","SessionSchema.InterruptReason","EventSchema.inventory","EventSchema.durable","EventList.DurableDefinitions","Schema","EffectSchema","Manifest","Service","layer","EventSchema.versionedType","Service","withCwd","path","Shell","FileSystem","SandboxFileSystem.Service","ShellTag","Hash.fast","SandboxInstance.toColumn","Service","fromRow","SpaceSchema.Info","SandboxInstance.fromField","layer","SandboxIO.FileSystem","SandboxIO.Current","SandboxInstance.toField","AbsolutePath","Service","SessionSchema.AssistantEnvelopeUsage","SessionSchema.MessageEnvelopeIdentity","decodeCompactionData","SessionSchema.CompactionData","decodeJsonObject","SessionSchema.JsonObject","encodeJsonObject","layer","Event.Service","Space.fromRow","EventList.SessionForked","Database.defaultLayer","SessionSchema.JsonObject","parseJson","SessionSchema.CompactionData","Service","layer","Session.Service","Session.SessionNotFoundError","SandboxInstance.ID","SandboxInstance.Status","SandboxInstance.PersistedError","errorMessage","providerError","Buffer","make","SandboxFileSystem.isNotFoundError","layer","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","layer","Local.Vfs","Process.host","reserved","make","SandboxDriver.erase","layer","layer","Shell","make","SandboxInstance.ID","Local.layer","HostExe.layer","EnvNodeJSDefault.layer","SandboxInstance.PersistedError","encodeUnknownJson","isSandboxProviderError","providerError","make","SandboxDriverRegistry.Registry","SandboxStore.make","SandboxIO.resolveMountCwd","SandboxInstance.isMountable","SandboxIO.FileSystem","SandboxIO.Shell","SandboxIO.Current","SandboxFileSystem.withCwd","shellWithCwd","Space.archiveEnv","layer","Buffer","make","Seed.initialize","Buffer","Shell","make","transport","Local.Vfs","Local.layer","EnvBash.transport","transport","Local.Vfs","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","SandboxDriver.RuntimeConfigBase","make","providerError","SandboxDriver.driver","EnvInMemory.make","transport","make","Seed.initialize","Local.Vfs","layer","Process.host","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","make","EnvSqldb.layer","providerError","SandboxDriver.driver","EnvSqldb.make","transport","Service","resolvePath","make","DEFAULT_CWD","SandboxIO.resolveMountCwd","SandboxInstance.PersistedError","Remote","statsFrom","providerFrom","Buffer","SandboxFileSystem.realpathScripts","exec","execArgv","transport","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","resourceLayer","SandboxResource.Service","Options","CreateConfig","RuntimeConfig","SandboxDriver.AbsolutePath","name","statusFrom","make","SandboxProvider.makeRedactor","SandboxProvider.providerError","SandboxDriver.driver","EnvDaytona.mountCwd","EnvDaytona.transport","sandbox","SandboxDriver.module","resolvePath","make","SandboxInstance.PersistedError","sanitizeSandboxError","Buffer","SandboxFileSystem.isNotFoundError","SandboxFileSystem.realpathScripts","collect","stream","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","SandboxResource.Service","RuntimeConfig","SandboxDriver.AbsolutePath","name","make","EnvVercel.credentialsFrom","SandboxProvider.makeRedactor","SandboxProvider.providerError","EnvVercel.sanitizeProviderError","SandboxDriver.driver","EnvVercel.createSandbox","EnvVercel.transport","SandboxDriver.module","Service","layer","SandboxIO.Shell","AbsolutePath","path","AbsolutePath","SandboxInstance.ID","Service","normalize","layer","SandboxIO.FileSystem","Git.Service","SandboxFs.up","path","AbsolutePath","SandboxFs.realpath","SandboxFs.readFileSafe","Hash.fast","AbsolutePath","Service","layer","SandboxIO.FileSystem","Git.Service","Git.resolvePath","SandboxFs.realpath","Hash.fast","SandboxInstance.toColumn","Service","layer","SandboxIO.FileSystem","Repo.Service","Worktree.Service","Space.Service","SandboxIO.Current","ProjectSchema.Info","SandboxFs.isDirectory","AbsolutePath","path","SandboxFs.up","Space.id","Ref","AbsolutePath","SpaceSchema.Info","ProjectSchema.Info","Service","layer","SandboxIO.Current","Project.Service","Repo.layer","Worktree.layer","Space.layer","Git.layer","SandboxInstance.ID","Service","Service","SessionMessageSchema.ID","SessionSchema.ID","SessionMessageSchema.ID","make","Event.Service","EventList.PromptAdmitted","EventList.Prompted","Service","layer","Session.Service","SessionInput.make","RunnerExecution.Service","SessionInput.LifecycleConflict","Session.SessionNotFoundError","SessionInput.equivalent","Service","EventList.Definitions","layer","latest","EventSchema.latest","isRecord","normalize","path","URL","homedir","parse","npa","Manifest","run","fs","path","failure","path","Package.parse","fs","load","Package.install","make","Loader.validate","isRecord","Loader.failure","Loader.classify","Loader.load","define","define","make","Shell","define","Tool.define","Tool.implement","define","SandboxIO.Shell","Tool.provide","make","layer","RunnerExecution.Service","Session.Service","SandboxController.Controller","Runner.Service","Event.Service","RunCoordinator.make","EventList.ExecutionStarted","EventList.ExecutionSucceeded","EventList.ExecutionInterrupted","EventList.ExecutionFailed","SessionFailure.fromCause","Session.SessionNotFoundError","Session.SessionLinkedSpaceNotFoundError","SandboxIO.Current","SandboxIO.FileSystem","Runner.SandboxDirectoryNotFoundError","Location.layerMounted","make","Event.Service","Runner.LLMStreamError","EventList.LLMStarted","EventList.LLMTextStart","EventList.LLMTextDelta","EventList.LLMTextEnd","EventList.LLMThinkingStart","EventList.LLMThinkingDelta","EventList.LLMThinkingEnd","EventList.LLMEnded","EventList.LLMFailed","AikitModel","reserved","Model","Runner.ProviderAuthenticationError","Runner.ProviderConfigurationError","Runner.ProviderAuthorizationError","Runner.ProviderModelUnavailableError","Runner.ProviderRateLimitError","Runner.ProviderQuotaError","Runner.ProviderInvalidRequestError","Runner.ProviderContentPolicyError","Runner.ProviderTimeoutError","Runner.ProviderTransportError","Runner.ProviderUnavailableError","Runner.ProviderInvalidResponseError","Runner.ProviderUnknownError","Runner.ProviderError","resolve","Runner.ModelCatalogError","Runner.ModelNotFoundError","aikitStream","make","run","SessionSchema.ID","SessionMessageSchema.ID","EventSchema.AikitToolCallTerminalPart","endTime","result","make","make","Executor.make","make","make","make","makeTools","makePrompt","makeCatalog","run","make","Service","layer","exports","Global.appConfigDir","parseJsonc","printParseErrorCode","normalize","Service","load","layer","Global.Service","layer","SessionRuntime.Service","Settings.Service","Event.Service","SandboxIO.Current","Location.Service","LLM.resolve","setup","layer","Runner.Service","Context.Service","Event.Service","SessionInput.make","Session.Service","State.Service","LLM.run","ContextCodec.decodeMessage","EventList.LLMFailed","EventList.ToolSettled","EventList.TurnEnded","EventList.ToolStarted","EventList.ToolProgress","EventList.TurnStarted","LLMEventPublisher.make","LLM.providerError","LLM.messageFailure","EventList.TurnAborted","SandboxDriver.withSource","layer","Event.Service","SessionInput.make","Session.Service","ContextCodec.encodeMessage","EventList.PromptAdmitted","EventList.Prompted","EventList.LLMStarted","EventList.LLMEnded","EventList.LLMFailed","EventList.ToolSettled","ContextCodec.encodePart","EventList.TurnEnded","layer","SessionProjector.layer","Session.layer","layer","Global.resolve","Global.layerWith","Settings.load","EventRegistry.flatten","Database.locationConfig","Database.layer","Database.resolveDatabaseLocation","SandboxDriverLoader.loadAll","SandboxDriverRegistry.layer","SandboxDriver.withSource","MemorySandboxDriver.make","SqldbSandboxDriver.make","SandboxController.layer","Loop.layer","LLM.make","State.layer","Settings.layer","SessionRuntime.layer","Context.layer","SessionLive.layer","Event.layer","EventRegistry.layer","SandboxDriverRegistry.Registry","create","SandboxController.Controller","SandboxInstance.ID","get","SessionStore.Service","Control.Service","Event.Service","SandboxController.Controller","SessionStore.SessionNotFoundError","create","SessionRuntime.Service","Location.layerMounted","SessionStore.rebaseDirectory","SandboxIO.FileSystem","EventSchema.ID","EventSchema.define","EventSchema.latest","EventList.PublicDefinitions","Sandbox.SandboxInstance.ID","Sandbox.SandboxInstance.Kind","Sandbox.SandboxInstance.Ownership","Sandbox.SandboxInstance.Status","Sandbox.SandboxInstance.Usage","Session.SessionSchema.ID","Sandbox.Selection","SessionStore.SessionNotFoundError","SessionStore.SessionLinkedSpaceNotFoundError","SessionStore.RelinkError","SandboxError.SandboxNotFoundError","SandboxError.SandboxDriverNotRegisteredError","SandboxError.SandboxDriverRegistrationError","SandboxError.SandboxUnsupportedError","SandboxError.SandboxProviderError","SandboxError.SandboxUnavailError","SandboxError.SandboxRemovedError","SandboxError.SandboxTransitionConflictError","SandboxError.SandboxBusyError","Location.DirectoryNotFoundError","Location.NotDirectoryError","PromptSchema.Delivery","Session.SessionMessageSchema.ID","Control.PromptConflictError","Event.SubscriptionOverflowError","Contract.Api","EventList.ExecutionInterrupted","EventList.ExecutionFailed","Envelope.decode","EventList.PromptAdmitted","EventList.Prompted","EventList.ExecutionSucceeded","Runner.ProviderError","Runner.ModelCatalogError","Runner.ModelNotFoundError","Runner.LLMStreamError","SandboxProvider.SandboxProviderError","Plugin.PreparationError","Plugin.InstallError","Settings.SettingsError","SandboxError.SandboxDriverNotRegisteredError","SandboxError.SandboxDriverRegistrationError","Client.ExecutionError"],"sources":["../../../harness/src/schema.ts","../../../harness/src/session/schema.ts","../../../harness/src/host.ts","../../../harness/src/util/home.ts","../../../harness/src/util/posix.ts","../../../harness/src/global.ts","../../../harness/src/db/migrations.ts","../../../harness/src/db/db.ts","../../../harness/src/event/schema.ts","../../../harness/src/repo/schema.ts","../../../harness/src/project/schema.ts","../../../harness/src/sandbox/instance.ts","../../../harness/src/session/prompt/schema.ts","../../../harness/src/space/schema.ts","../../../harness/src/db/schema.sql.ts","../../../harness/src/session/message/schema.ts","../../../harness/src/session/failure.ts","../../../harness/src/event/list.ts","../../../harness/src/event/manifest.ts","../../../harness/src/event/event.ts","../../../harness/src/sandbox/fs/filesystem.ts","../../../harness/src/sandbox/shell/shell.ts","../../../harness/src/sandbox/io.ts","../../../harness/src/util/hash.ts","../../../harness/src/space/space.ts","../../../harness/src/session/session.ts","../../../harness/src/context/errors.ts","../../../harness/src/context/codec.ts","../../../harness/src/context/assemble.ts","../../../harness/src/context/context.ts","../../../harness/src/sandbox/driver.ts","../../../harness/src/sandbox/errors.ts","../../../harness/src/sandbox/utils/process.ts","../../../harness/src/sandbox/fs/vfs.ts","../../../harness/src/sandbox/fs/nodejs.ts","../../../harness/src/sandbox/registry.ts","../../../harness/src/sandbox/shell/host.ts","../../../harness/src/sandbox/store.ts","../../../harness/src/sandbox/control.ts","../../../harness/src/sandbox/utils/seed.ts","../../../harness/src/sandbox/fs/inmemory.ts","../../../harness/src/sandbox/shell/justbash.ts","../../../harness/src/sandbox/virtual.ts","../../../harness/src/sandbox/drivers/memory.ts","../../../harness/src/sandbox/fs/sqldb.ts","../../../harness/src/sandbox/drivers/sqldb.ts","../../../harness/src/sandbox/resource.ts","../../../harness/src/sandboxes/daytona/fs.ts","../../../harness/src/sandboxes/daytona/provider.ts","../../../harness/src/sandboxes/daytona/index.ts","../../../harness/src/sandboxes/vercel/fs.ts","../../../harness/src/sandboxes/vercel/provider.ts","../../../harness/src/sandboxes/vercel/index.ts","../../../harness/src/git/git.ts","../../../harness/src/location/error.ts","../../../harness/src/sandbox/fs/util.ts","../../../harness/src/repo/repo.ts","../../../harness/src/worktree/worktree.ts","../../../harness/src/project/project.ts","../../../harness/src/location/location.ts","../../../harness/src/runner/run.ts","../../../harness/src/runner/execution.ts","../../../harness/src/session/input/schema.ts","../../../harness/src/session/input/input.ts","../../../harness/src/control.ts","../../../harness/src/event/registry.ts","../../../harness/src/settings/merge.ts","../../../harness/src/util/module.ts","../../../../node_modules/.pnpm/lru-cache@11.5.2/node_modules/lru-cache/dist/commonjs/node/index.min.js","../../../../node_modules/.pnpm/hosted-git-info@10.1.1/node_modules/hosted-git-info/lib/hosts.js","../../../../node_modules/.pnpm/hosted-git-info@10.1.1/node_modules/hosted-git-info/lib/parse-url.js","../../../../node_modules/.pnpm/hosted-git-info@10.1.1/node_modules/hosted-git-info/lib/from-url.js","../../../../node_modules/.pnpm/hosted-git-info@10.1.1/node_modules/hosted-git-info/lib/index.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js","../../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js","../../../../node_modules/.pnpm/validate-npm-package-name@8.0.0/node_modules/validate-npm-package-name/lib/builtin-modules.json","../../../../node_modules/.pnpm/validate-npm-package-name@8.0.0/node_modules/validate-npm-package-name/lib/index.js","../../../../node_modules/.pnpm/proc-log@7.0.0/node_modules/proc-log/lib/index.js","../../../../node_modules/.pnpm/npm-package-arg@14.0.0/node_modules/npm-package-arg/lib/npa.js","../../../harness/src/plugin/package.ts","../../../harness/src/plugin/loader.ts","../../../harness/src/plugin/catalog.ts","../../../harness/src/plugin/plugin.ts","../../../harness/src/plugin/builtin/prompt/default.ts","../../../harness/src/tool/truncate.ts","../../../harness/src/tool/accumulator.ts","../../../harness/src/tool/progress.ts","../../../harness/src/tool/shell.ts","../../../harness/src/tool/error.ts","../../../harness/src/tool/tool.ts","../../../harness/src/plugin/builtin/tool/bash.ts","../../../harness/src/plugin/builtin.ts","../../../harness/src/runner/coordinator.ts","../../../harness/src/runner/execute.ts","../../../harness/src/runner/event.ts","../../../harness/src/settings/schema.ts","../../../harness/src/settings/resolve.ts","../../../harness/src/runner/llm.ts","../../../harness/src/plugin/context.ts","../../../harness/src/plugin/tool/schema.ts","../../../harness/src/util/error.ts","../../../harness/src/tool/executor.ts","../../../harness/src/tool/registry.ts","../../../harness/src/plugin/prompt/registry.ts","../../../harness/src/plugin/tool/registry.ts","../../../harness/src/plugin/registry.ts","../../../harness/src/plugin/host.ts","../../../harness/src/session/runtime.ts","../../../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/umd/main.js","../../../harness/src/settings/settings.ts","../../../harness/src/state/state.ts","../../../harness/src/runner/loop.ts","../../../harness/src/sandbox/loader.ts","../../../harness/src/session/projector.ts","../../../harness/src/session/live.ts","../../../harness/src/effect/harness.ts","../../../harness/src/effect/sandbox.ts","../../../harness/src/effect/session.ts","../../src/server/envelope.ts","../../src/server/contract.ts","../../src/server/client.ts","../../src/cli/output.ts","../../src/cli/error.ts"],"sourcesContent":["import { Message } from \"@codeworksh/aikit\";\nimport { DateTime, Option, Schema, SchemaGetter } from \"effect\";\nimport type { Static, TSchema } from \"typebox\";\nimport TypeBoxSchema from \"typebox/schema\";\n\nconst aikitValidators = new WeakMap<TSchema, ReturnType<typeof TypeBoxSchema.Compile>>();\n\nconst aikitValidatorFor = <T extends TSchema>(schema: T): ReturnType<typeof TypeBoxSchema.Compile<T>> => {\n\tconst cached = aikitValidators.get(schema) as ReturnType<typeof TypeBoxSchema.Compile<T>> | undefined;\n\tif (cached !== undefined) return cached;\n\tconst compiled = TypeBoxSchema.Compile(schema);\n\taikitValidators.set(schema, compiled);\n\treturn compiled;\n};\n\nconst aikitErrorPath = (error: {\n\treadonly instancePath?: string;\n\treadonly params?: Record<string, unknown>;\n}): string => {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\tconst required = error.params?.requiredProperties;\n\treturn Array.isArray(required) ? required.join(\", \") : \"root\";\n};\n\nconst validateAikitSchema = <T extends TSchema>(schema: T, value: unknown, label: string): Static<T> => {\n\tconst validator = aikitValidatorFor(schema);\n\tif (validator.Check(value)) return value;\n\n\tconst [, issues] = validator.Errors(value);\n\tconst details = issues.map((issue) => ` - ${aikitErrorPath(issue)}: ${issue.message}`).join(\"\\n\") || \"unknown error\";\n\tthrow new Error(`validation failed for ${label}\\n${details}`);\n};\n\n/** Validate an aikit message without coercing or rewriting durable data. */\nexport const validateAikitMessage = (value: unknown, label: string): Message.Message =>\n\tvalidateAikitSchema(Message.MessageSchema, value, label);\n\nexport const validateAikitUserMessage = (value: unknown, label: string): Message.UserMessage =>\n\tvalidateAikitSchema(Message.UserMessageSchema, value, label);\n\nexport const validateAikitAssistantMessage = (value: unknown, label: string): Message.AssistantMessage =>\n\tvalidateAikitSchema(Message.AssistantMessageSchema, value, label);\n\nexport const validateAikitToolCallTerminalPart = (value: unknown, label: string): Message.ToolCallTerminalPart =>\n\tvalidateAikitSchema(Message.ToolCallTerminalPartSchema, value, label);\n\nexport const isAikitAssistantMessage = (value: unknown): value is Message.AssistantMessage =>\n\taikitValidatorFor(Message.AssistantMessageSchema).Check(value);\n\nexport const isAikitToolCallTerminalPart = (value: unknown): value is Message.ToolCallTerminalPart =>\n\taikitValidatorFor(Message.ToolCallTerminalPartSchema).Check(value);\n\n/**\n * Integer greater than zero.\n */\nexport const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\n\n/**\n * Integer greater than or equal to zero.\n */\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Cost greater than or equal with finite value\n */\nexport const NonNegativeCost = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Absolute file path (e.g., `/home/user/projects/myapp/src/main.ts`).\n */\nexport const AbsolutePath = Schema.String.pipe(Schema.brand(\"AbsolutePath\"));\nexport type AbsolutePath = Schema.Schema.Type<typeof AbsolutePath>;\n\n/**\n * Optional public JSON field that can hold explicit `undefined` on the type\n * side but encodes it as an omitted key, matching legacy `JSON.stringify`.\n */\nexport const optional = <S extends Schema.Top>(schema: S) =>\n\tSchema.optionalKey(schema).pipe(\n\t\tSchema.decodeTo(Schema.optional(Schema.toType(schema)), {\n\t\t\tdecode: SchemaGetter.passthrough({ strict: false }),\n\t\t\tencode: SchemaGetter.transformOptional(Option.filter((value) => value !== undefined)),\n\t\t}),\n\t);\n\n/**\n * Strip `readonly` from a nested type. Stand-in for `effect`'s `Types.DeepMutable`\n * until `effect:core/x228my` (\"Types.DeepMutable widens unknown to `{}`\") lands.\n *\n * The upstream version falls through `unknown` into `{ -readonly [K in keyof T]: ... }`\n * where `keyof unknown = never`, so `unknown` collapses to `{}`. This local\n * version gates the object branch on `extends object` (which `unknown` does\n * not) so `unknown` passes through untouched.\n *\n * Primitive bailout matches upstream — without it, branded strings like\n * `string & Brand<\"SessionID\">` fall into the object branch and get their\n * prototype methods walked.\n *\n * Tuple branch preserves readonly tuples (e.g. `ConfigPlugin.Spec`'s\n * `readonly [string, Options]`); the general array branch would otherwise\n * widen them to unbounded arrays.\n */\nexport type DeepMutable<T> = T extends string | number | boolean | bigint | symbol | Function\n\t? T\n\t: T extends readonly [unknown, ...unknown[]]\n\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t: T extends readonly (infer U)[]\n\t\t\t? DeepMutable<U>[]\n\t\t\t: T extends object\n\t\t\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t\t\t: T;\n\n/**\n * Attach static methods to a schema object. Designed to be used with `.pipe()`:\n *\n * @example\n * export const Foo = fooSchema.pipe(\n * withStatics((schema) => ({\n * zero: schema.make(0),\n * from: Schema.decodeUnknownOption(schema),\n * }))\n * )\n */\nexport const withStatics =\n\t<S extends object, M extends Record<string, unknown>>(methods: (schema: S) => M) =>\n\t(schema: S): S & M =>\n\t\tObject.assign(schema, methods(schema));\n\n/**\n * Nominal wrapper for scalar types. The class itself is a valid schema —\n * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc.\n *\n * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type`\n * of a field using this newtype resolves to `Self` rather than the underlying\n * branded phantom. Without that override, passing a class instance to code\n * typed against `Schema.Schema.Type<FieldSchema>` would require a cast even\n * though the values are structurally equivalent at runtime.\n *\n * @example\n * class QuestionID extends Newtype<QuestionID>()(\"QuestionID\", Schema.String) {\n * static make(id: string): QuestionID {\n * return this.make(id)\n * }\n * }\n *\n * Schema.decodeEffect(QuestionID)(input)\n */\nexport function Newtype<Self>() {\n\treturn <const Tag extends string, S extends Schema.Top>(tag: Tag, schema: S) => {\n\t\tabstract class Base {\n\t\t\tdeclare readonly _newtype: Tag;\n\n\t\t\tstatic make(value: Schema.Schema.Type<S>): Self {\n\t\t\t\treturn value as unknown as Self;\n\t\t\t}\n\t\t}\n\n\t\tObject.setPrototypeOf(Base, schema);\n\n\t\treturn Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & {\n\t\t\treadonly make: (value: Schema.Schema.Type<S>) => Self;\n\t\t} & Omit<Schema.Opaque<Self, S, {}>, \"make\" | \"~type.make\"> & {\n\t\t\t\treadonly \"~type.make\": Self;\n\t\t\t};\n\t};\n}\n\nexport const DateTimeUtcFromMillis = Schema.Finite.pipe(\n\tSchema.decodeTo(Schema.DateTimeUtc, {\n\t\tdecode: SchemaGetter.transform((value) => DateTime.makeUnsafe(value)),\n\t\tencode: SchemaGetter.transform((value) => DateTime.toEpochMillis(value)),\n\t}),\n);\n","import { Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { NonNegativeCost, NonNegativeInt, withStatics } from \"../schema.ts\";\n\n// Session identity. Branded so a session ID is not interchangeable with an\n// entry, part, or workspace ID at the type level — service signatures take\n// `SessionSchema.ID`, never a bare `string`.\n//\n// `create` mints a new one; `ascending` adopts an ID that came from outside\n// (a persisted row, a request payload) and rejects a foreign prefix rather\n// than branding it silently. uuidv7 keeps IDs lexicographically sortable by\n// creation time, so `ORDER BY id` is `ORDER BY created`.\nexport const ID = Schema.String.check(Schema.isStartsWith(\"ses\")).pipe(\n\tSchema.brand(\"Session.ID\"),\n\twithStatics((schema) => ({\n\t\tascending: (id?: string) => {\n\t\t\tif (!id) return schema.make(\"ses_\" + uuidv7());\n\t\t\tif (!id.startsWith(\"ses\")) throw new Error(`ID ${id} does not start with ses`);\n\t\t\treturn schema.make(id);\n\t\t},\n\t\tcreate: () => schema.make(\"ses_\" + uuidv7()),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\nexport const IDFromDb = Schema.String.pipe(Schema.brand(\"Session.ID\"));\n\n/**\n * Why an execution stopped. Supplied by whoever asked for the interruption --\n * a stop the user asked for and a stop the process imposed on shutdown are\n * different facts, and inspecting the cause cannot tell them apart.\n */\nexport const InterruptReason = Schema.Literals([\"user\", \"shutdown\"]);\nexport type InterruptReason = typeof InterruptReason.Type;\n\n// Shared persistence-boundary codecs. Append validates before writing; fork\n// decodes again because legacy/imported rows may predate that validation.\nexport const JsonObject = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));\n\nexport const MessageEnvelopeIdentity = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tmessageId: Schema.String,\n\t}),\n);\n\n// NOTE: modify this if schema changes for compaction\nexport const CompactionData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tsummary: Schema.String,\n\t\t// null explicitly means the summary replaces all preceding history.\n\t\tfirstKeptEntryId: Schema.NullOr(Schema.String),\n\t\ttokensBefore: NonNegativeInt,\n\t}),\n);\nexport type CompactionData = typeof CompactionData.Type;\n\n// Harness-owned shape of the billed usage inside a persisted assistant envelope.\n// This is data-structure integrity only — business validation\n// belongs to the Context Manager, a layer above. Stricter than the wire:\n// counts and costs must be non-negative so bad producer data fails the\n// append instead of poisoning the session aggregates.\nexport const Usage = Schema.Struct({\n\tinput: NonNegativeInt,\n\toutput: NonNegativeInt,\n\tcacheRead: NonNegativeInt,\n\tcacheWrite: NonNegativeInt,\n\ttotalTokens: NonNegativeInt,\n\tcost: Schema.Struct({\n\t\tinput: NonNegativeCost,\n\t\toutput: NonNegativeCost,\n\t\tcacheRead: NonNegativeCost,\n\t\tcacheWrite: NonNegativeCost,\n\t\ttotal: NonNegativeCost,\n\t}),\n});\nexport type Usage = typeof Usage.Type;\n\n// \"JSON string whose object carries a conforming usage\" as one codec;\n// JSON.parse failures land in the same SchemaError channel as shape failures.\nexport const AssistantEnvelopeUsage = Schema.fromJsonString(Schema.Struct({ usage: Usage }));\n\nexport * as SessionSchema from \"./schema.ts\";\n","import { NodeCrypto, NodeFileSystem, NodePath } from \"@effect/platform-node\";\nimport { Crypto, Effect, FileSystem, Path } from \"effect\";\n\n/** Node-backed filesystem for Harness-owned files outside sandbox namespaces. */\nexport const fileSystem = Effect.runSync(FileSystem.FileSystem.pipe(Effect.provide(NodeFileSystem.layer)));\n\n/** Platform-native paths for Harness-owned files outside sandbox namespaces. */\nexport const hostPath = Effect.runSync(Path.Path.pipe(Effect.provide(NodePath.layer)));\n\n/** Node-backed crypto for Harness-owned digests and random identifiers. */\nexport const crypto = Effect.runSync(Crypto.Crypto.pipe(Effect.provide(NodeCrypto.layer)));\n","import { homedir } from \"node:os\";\n\n/**\n * Expand a leading `~`, leaving every other value untouched for the caller to resolve.\n *\n * The path module is the caller's, because the home directory is host-native while some\n * callers spell their paths POSIX-only. Anything beyond the tilde is not this function's\n * business: it never resolves, normalizes, or validates.\n */\nexport const expandTilde = (value: string, path: { readonly join: (...parts: ReadonlyArray<string>) => string }) =>\n\tvalue === \"~\" ? homedir() : value.startsWith(\"~/\") ? path.join(homedir(), value.slice(2)) : value;\n","import { Effect, Path } from \"effect\";\n\n/** Shared POSIX path implementation for sandbox and remote-runtime paths. */\nexport const posix = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));\n","import { Config, Context, Effect, Layer } from \"effect\";\nimport * as os from \"node:os\";\nimport { fileSystem } from \"./host.ts\";\nimport { expandTilde } from \"./util/home.ts\";\nimport { posix } from \"./util/posix.ts\";\n\nexport const appConfigDir = \".codework\";\nexport const app = \"codework\";\n\nconst defaultHome = posix.join(os.homedir(), appConfigDir);\n\nconst expandHome = (value: string) => posix.resolve(expandTilde(value, posix));\n\nexport const homeConfig = Config.String(\"CODEWORK_HOME_DIR\").pipe(\n\tConfig.withDefault(defaultHome),\n\tConfig.map(expandHome),\n);\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/global/Service\") {}\n\nexport interface Interface {\n\treadonly home: string;\n\treadonly cache: string;\n\treadonly data: string;\n\treadonly log: string;\n}\n\nexport function make(input: Partial<Interface> = {}): Interface {\n\tconst home = expandHome(input.home ?? defaultHome);\n\treturn {\n\t\thome,\n\t\tcache: input.cache ?? posix.join(home, \"cache\"),\n\t\tdata: input.data ?? posix.join(home, \"data\"),\n\t\tlog: input.log ?? posix.join(home, \"log\"),\n\t};\n}\n\nexport const resolve = Effect.fn(\"Global.resolve\")(function* (input: Partial<Interface> = {}) {\n\tconst home = input.home === undefined ? yield* homeConfig : expandHome(input.home);\n\treturn make({ ...input, home });\n});\n\nconst build = (input: Partial<Interface>) =>\n\tEffect.gen(function* () {\n\t\tconst paths = yield* resolve(input);\n\t\tyield* Effect.all([\n\t\t\tfileSystem.makeDirectory(paths.cache, { recursive: true }),\n\t\t\tfileSystem.makeDirectory(paths.data, { recursive: true }),\n\t\t\tfileSystem.makeDirectory(paths.log, { recursive: true }),\n\t\t]).pipe(Effect.orDie);\n\t\treturn Service.of(paths);\n\t});\n\nexport const layer = Layer.effect(Service, build({}));\n\nexport const defaultLayer = layer;\n\nexport const layerWith = (input: Partial<Interface>) => Layer.effect(Service, build(input));\n\nexport * as Global from \"./global.ts\";\n","import { Effect } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\n\n// Migrations ship as code (Migrator.fromRecord) rather than .sql files on\n// disk, so they survive bundling and need no runtime path resolution.\n//\n// Keys are \"YYYYMMDD<counter>_<label>\" (4-digit counter, several per day);\n// fromRecord requires the \"_<label>\" suffix and silently drops keys without\n// it. Only the numeric prefix orders migrations, and it must be strictly\n// greater than every id already applied — the migrator runs by high-water\n// mark, so an id dated before an applied one is silently skipped.\nexport const migrations = {\n\t\"202607070001_init\": Effect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\n\t\t// Tracks head of the inbox event sequence for a given aggregate.\n\t\tyield* sql`\n\t\t\tCREATE TABLE event_sequence (\n\t\t\t\taggregate_id TEXT PRIMARY KEY,\n\t\t\t\tseq INTEGER NOT NULL,\n\t\t\t\towner_id TEXT\n\t\t\t)\n\t\t`;\n\n\t\t// A durable inbox event store. An event is then picked and processed.\n\t\t// Stores countigous sequence of events for a given aggregate.\n\t\tyield* sql`\n\t\t\tCREATE TABLE event (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\taggregate_id TEXT NOT NULL\n\t\t\t\t\tREFERENCES event_sequence(aggregate_id) ON DELETE CASCADE,\n\t\t\t\tseq INTEGER NOT NULL,\n\t\t\t\ttype TEXT NOT NULL,\n\t\t\t\tdata TEXT NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\tyield* sql`CREATE UNIQUE INDEX event_aggregate_id_seq_idx ON event (aggregate_id, seq)`;\n\t\tyield* sql`CREATE INDEX event_aggregate_id_type_seq_idx ON event (aggregate_id, type, seq)`;\n\n\t\t// A durable filesystem namespace. Created before space because it\n\t\t// references it. Reference counts are deliberately\n\t\t// absent: they live in control-plane memory, since a persisted count cannot\n\t\t// tell whether the process that took it is still running.\n\t\t//\n\t\t// The host is never a row. `local` is a reserved id that exists at runtime\n\t\t// and never reaches a column; NULL is its only storage form, so nothing has\n\t\t// to be seeded or repaired for a session to exist.\n\t\tyield* sql`\n\t\t\tCREATE TABLE sandbox_instance (\n\t\t\t\tid TEXT PRIMARY KEY CHECK (id <> 'local'),\n\t\t\t\tdriver TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL CHECK (kind IN ('local', 'virtual', 'remote')),\n\t\t\t\tprovider_resource_id TEXT,\n\t\t\t\truntime_config TEXT,\n\t\t\t\townership TEXT NOT NULL CHECK (ownership IN ('managed', 'external')),\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tprovider_status TEXT,\n\t\t\t\tstate_observed_at INTEGER NOT NULL,\n\t\t\t\tmetadata TEXT,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tlast_mounted_at INTEGER,\n\t\t\t\tlast_unmounted_at INTEGER,\n\t\t\t\tlast_used_at INTEGER,\n\t\t\t\tremoved_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\t// One live instance per driver resource: two application identities for\n\t\t// one namespace would alias, which is the thing instance IDs exist to\n\t\t// prevent. Tombstones are excluded so a removed row never blocks a\n\t\t// genuinely new resource that reuses the locator.\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX sandbox_instance_resource_idx\n\t\t\tON sandbox_instance (driver, provider_resource_id)\n\t\t\tWHERE provider_resource_id IS NOT NULL AND status != 'removed'\n\t\t`;\n\n\t\t// A logical codebase, env-independent. Archived rather than deleted once\n\t\t// it has no active space anywhere, so session history stays reachable.\n\t\tyield* sql`\n\t\t\tCREATE TABLE project (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL CHECK (status IN ('active', 'archived')),\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\t// One directory in one env. `id` is Hash.fast([env|'local', location]) —\n\t\t// no project component, so re-pointing a space to another project keeps\n\t\t// every session key intact. `env` NULL = host (same convention as\n\t\t// sandbox_instance_id everywhere else); the FK is skipped on NULL.\n\t\t// RESTRICT on both FKs: a space with sessions is archived, never deleted,\n\t\t// and a destroyed sandbox is tombstoned, not removed.\n\t\tyield* sql`\n\t\t\tCREATE TABLE space (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tproject_id TEXT NOT NULL REFERENCES project(id) ON UPDATE CASCADE ON DELETE RESTRICT,\n\t\t\t\tlocation TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL CHECK (kind IN ('primary', 'linked', 'copy', 'plain')),\n\t\t\t\tenv TEXT\n\t\t\t\t\tREFERENCES sandbox_instance(id) ON UPDATE CASCADE ON DELETE RESTRICT\n\t\t\t\t\tCHECK (env IS NULL OR env <> 'local'),\n\t\t\t\tstatus TEXT NOT NULL CHECK (status IN ('active', 'archived')),\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\t// One place, one row. SQLite treats NULLs as distinct in a unique index,\n\t\t// so (NULL, '/repo') would insert twice; coalescing to the reserved id\n\t\t// makes the index read as what it means.\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX space_location_idx\n\t\t\tON space (COALESCE(env, 'local'), location)\n\t\t`;\n\n\t\t// Exactly one primary per (project, env). Partial: the other kinds are\n\t\t// unbounded. Status is deliberately not part of the predicate — an\n\t\t// archived primary must be demoted before another can be promoted.\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX space_primary_idx\n\t\t\tON space (project_id, COALESCE(env, 'local')) WHERE kind = 'primary'\n\t\t`;\n\n\t\tyield* sql`CREATE INDEX space_project_idx ON space (project_id)`;\n\n\t\t// A session belongs to a space; project and env are derived through it,\n\t\t// never denormalised here. `directory` is the ABSOLUTE realpath of the\n\t\t// session cwd, always equal to or under space.location (which is immutable).\n\t\t// RESTRICT: sessions are history, a referenced space cannot go away.\n\t\tyield* sql`\n\t\t\tCREATE TABLE session (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tspace_id TEXT NOT NULL REFERENCES space(id) ON UPDATE CASCADE ON DELETE RESTRICT,\n\t\t\t\tparent_id TEXT REFERENCES session(id) ON UPDATE CASCADE ON DELETE SET NULL,\n\t\t\t\tslug TEXT NOT NULL,\n\t\t\t\tdirectory TEXT NOT NULL,\n\t\t\t\ttitle TEXT NOT NULL,\n\t\t\t\ttag TEXT,\n\t\t\t\tmetadata TEXT,\n\t\t\t\tcost REAL NOT NULL DEFAULT 0,\n\t\t\t\ttokens_input INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttokens_output INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttokens_cache_read INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttokens_cache_write INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\tyield* sql`CREATE INDEX session_space_idx ON session (space_id)`;\n\t\tyield* sql`CREATE UNIQUE INDEX session_slug_idx ON session (slug)`;\n\t\tyield* sql`CREATE INDEX session_tag_idx ON session (tag)`;\n\n\t\t// The tree edge is a composite FK (session_id, parent_id) so a parent can\n\t\t// never live in another session — cross-session edges would mess up the context\n\t\t// NULL parent_id (roots) skips the FK per SQLite.\n\t\t// In short: FK (session_id, parent_id); makes sure that a child entry via parent_id must belong\n\t\t// to exact same session_id.\n\t\tyield* sql`\n\t\t\tCREATE TABLE session_entry (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tsession_id TEXT NOT NULL REFERENCES session(id) ON UPDATE CASCADE ON DELETE CASCADE,\n\t\t\t\tparent_id TEXT,\n\t\t\t\tseq INTEGER NOT NULL,\n\t\t\t\ttype TEXT NOT NULL,\n\t\t\t\tstate TEXT NOT NULL DEFAULT 'committed'\n\t\t\t\t\tCHECK (state IN ('draft', 'committed', 'aborted')),\n\t\t\t\tdata TEXT NOT NULL,\n\t\t\t\tlabel TEXT,\n\t\t\t\tmetadata TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tFOREIGN KEY (session_id, parent_id) REFERENCES session_entry(session_id, id)\n\t\t\t)\n\t\t`;\n\n\t\t// Parent key for the composite FKs (SQLite requires a UNIQUE covering\n\t\t// the referenced columns).\n\t\tyield* sql`CREATE UNIQUE INDEX session_entry_session_id_idx ON session_entry (session_id, id)`;\n\n\t\tyield* sql`\n\t\t\tCREATE TABLE session_entry_part (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tentry_id TEXT NOT NULL,\n\t\t\t\tsession_id TEXT NOT NULL REFERENCES session(id) ON UPDATE CASCADE ON DELETE CASCADE,\n\t\t\t\tpart_index INTEGER NOT NULL,\n\t\t\t\ttype TEXT NOT NULL,\n\t\t\t\tstatus TEXT,\n\t\t\t\tcall_id TEXT,\n\t\t\t\ttool_name TEXT,\n\t\t\t\tdata TEXT NOT NULL,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tCHECK (type != 'toolCall' OR (status IS NOT NULL AND call_id IS NOT NULL AND tool_name IS NOT NULL)),\n\t\t\t\tCHECK (type = 'toolCall' OR (status IS NULL AND call_id IS NULL AND tool_name IS NULL)),\n\t\t\t\tFOREIGN KEY (session_id, entry_id) REFERENCES session_entry(session_id, id) ON UPDATE CASCADE ON DELETE CASCADE\n\t\t\t)\n\t\t`;\n\n\t\tyield* sql`ALTER TABLE session ADD COLUMN leaf_entry_id TEXT REFERENCES session_entry(id)`;\n\n\t\tyield* sql`CREATE UNIQUE INDEX session_entry_session_seq_idx ON session_entry (session_id, seq)`;\n\t\tyield* sql`CREATE INDEX session_entry_parent_idx ON session_entry (session_id, parent_id)`;\n\t\tyield* sql`CREATE INDEX session_entry_type_idx ON session_entry (session_id, type, seq)`;\n\t\tyield* sql`CREATE INDEX session_entry_state_idx ON session_entry (session_id, state, seq)`;\n\t\tyield* sql`CREATE INDEX session_entry_label_idx ON session_entry (session_id, seq) WHERE label IS NOT NULL`;\n\n\t\tyield* sql`CREATE UNIQUE INDEX session_entry_part_entry_idx ON session_entry_part (entry_id, part_index)`;\n\t\tyield* sql`CREATE INDEX session_entry_part_call_idx ON session_entry_part (session_id, call_id) WHERE call_id IS NOT NULL`;\n\t\tyield* sql`CREATE UNIQUE INDEX session_entry_part_call_uidx ON session_entry_part (entry_id, call_id) WHERE call_id IS NOT NULL`;\n\t\tyield* sql`CREATE INDEX session_entry_part_unsettled_idx ON session_entry_part (session_id, status) WHERE status IN ('pending', 'running')`;\n\t\tyield* sql`CREATE INDEX session_entry_part_session_idx ON session_entry_part (session_id, entry_id, part_index)`;\n\n\t\tyield* sql`\n\t\t\tCREATE TABLE session_input (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tsession_id TEXT NOT NULL REFERENCES session(id) ON UPDATE CASCADE ON DELETE CASCADE,\n\t\t\t\tprompt TEXT NOT NULL,\n\t\t\t\tdelivery TEXT NOT NULL,\n\t\t\t\tadmitted_seq INTEGER NOT NULL,\n\t\t\t\tpromoted_seq INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t)\n\t\t`;\n\n\t\t// Pending lanes are selected by session and delivery, then drained in\n\t\t// admission order. SQLite indexes NULL values, so promoted_seq IS NULL\n\t\t// uses this index for pending-input queries.\n\t\tyield* sql`\n\t\t\tCREATE INDEX session_input_pending_idx\n\t\t\tON session_input (session_id, promoted_seq, delivery, admitted_seq)\n\t\t`;\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX session_input_admitted_seq_idx\n\t\t\tON session_input (session_id, admitted_seq)\n\t\t`;\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX session_input_promoted_seq_idx\n\t\t\tON session_input (session_id, promoted_seq)\n\t\t`;\n\t}),\n};\n","import { SqliteClient, SqliteMigrator } from \"@effect/sql-sqlite-node\";\nimport { Config, Effect, Layer, String as Str } from \"effect\";\nimport { Migrator, SqlClient } from \"effect/unstable/sql\";\nimport { Global } from \"../global.ts\";\nimport { fileSystem } from \"../host.ts\";\nimport { posix } from \"../util/posix.ts\";\nimport { migrations } from \"./migrations.ts\";\n\nexport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\n\n// PRAGMAs and migrations run once during layer construction; the node:sqlite\n// client holds a single connection for the lifetime of the layer, so the settings\n// apply to every query and a `:memory:` database stays intact across\n// transactions — important for serverless deployments and transient sessions\n// where no writable disk is available. WAL is stated explicitly even though the\n// client defaults to it: readers must never block the resolve/refresh writer.\n// A `:memory:` database ignores it and reports `memory`, which is fine.\nconst setup = Effect.gen(function* () {\n\tconst sql = yield* SqlClient.SqlClient;\n\tyield* sql`PRAGMA journal_mode = WAL`;\n\tyield* sql`PRAGMA synchronous = NORMAL`;\n\tyield* sql`PRAGMA busy_timeout = 5000`;\n\tyield* sql`PRAGMA cache_size = -64000`;\n\tyield* sql`PRAGMA foreign_keys = ON`;\n\tyield* SqliteMigrator.run({ loader: Migrator.fromRecord(migrations) });\n});\n\n// Provides `SqlClient` (and `SqliteClient`) for the database at `location`,\n// with column-name transforms so camelCase fields map to snake_case columns.\nexport function layer(location: string) {\n\tconst client = Layer.unwrap(\n\t\tEffect.gen(function* () {\n\t\t\tif (location !== \":memory:\") {\n\t\t\t\tyield* fileSystem.makeDirectory(posix.dirname(location), { recursive: true }).pipe(Effect.orDie);\n\t\t\t}\n\t\t\treturn SqliteClient.layer({\n\t\t\t\tfilename: location,\n\t\t\t\ttransformQueryNames: Str.camelToSnake,\n\t\t\t\ttransformResultNames: Str.snakeToCamel,\n\t\t\t});\n\t\t}),\n\t);\n\treturn client.pipe(\n\t\tLayer.tap((context) => setup.pipe(Effect.provide(context))),\n\t\tLayer.orDie,\n\t);\n}\n\nexport const locationConfig = Config.String(\"CODEWORK_DB\").pipe(Config.withDefault(\"codework.db\"));\n\nexport function resolveDatabaseLocation(configured: string, data: string) {\n\tif (configured === \":memory:\" || posix.isAbsolute(configured)) return configured;\n\treturn posix.join(data, configured);\n}\n\nexport const path = Effect.fn(\"Database.path\")(function* (data?: string) {\n\tconst directory = data ?? (yield* Global.resolve()).data;\n\treturn resolveDatabaseLocation(yield* locationConfig, directory);\n});\n\nexport const defaultLayer = Layer.unwrap(path().pipe(Effect.map(layer)));\n\nexport * as Database from \"./db.ts\";\n","import { Message } from \"@codeworksh/aikit\";\nimport { Effect, Schema, type SchemaAST, SchemaGetter, SchemaIssue } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport {\n\tisAikitAssistantMessage,\n\tisAikitToolCallTerminalPart,\n\toptional,\n\tvalidateAikitAssistantMessage,\n\tvalidateAikitToolCallTerminalPart,\n\twithStatics,\n} from \"../schema.ts\";\n\ntype AikitAssistantPart = Message.AssistantMessage[\"parts\"][number];\n\n/** Undeclared fields used only while aikit is assembling a streamed part. */\nconst aikitTransientFields: Readonly<Record<AikitAssistantPart[\"type\"], ReadonlyArray<string>>> = {\n\ttext: [\"streamId\"],\n\timage: [],\n\tthinking: [\"streamId\"],\n\ttoolCall: [\"partialJson\"],\n};\n\nconst omit = <T extends object>(value: T, keys: ReadonlyArray<string>): T => {\n\tif (!keys.some((key) => key in value)) return value;\n\tconst copy = { ...value } as T & Record<string, unknown>;\n\tfor (const key of keys) delete copy[key];\n\treturn copy;\n};\n\nconst canonicalizeAikitAssistantMessage = (message: Message.AssistantMessage): Message.AssistantMessage => ({\n\t...message,\n\tparts: message.parts.map((part) => omit(part, aikitTransientFields[part.type])),\n});\n\nconst reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\n\nconst decodeAikitAssistantMessage = (value: unknown, options: SchemaAST.ParseOptions) =>\n\tEffect.try({\n\t\ttry: () => canonicalizeAikitAssistantMessage(validateAikitAssistantMessage(value, \"aikit assistant message\")),\n\t\tcatch: (cause) => new SchemaIssue.InvalidValue({ message: reasonOf(cause) }, value, options),\n\t});\n\nconst aikitAssistantMessageDeclared = Schema.declare<Message.AssistantMessage>(isAikitAssistantMessage, {\n\texpected: \"aikit AssistantMessage\",\n});\n\n/**\n * Effect Schema adapter for aikit's TypeBox assistant message. Durable LLM\n * events use it to validate their payload and strip streaming-only fields.\n */\nexport const AikitAssistantMessage = Schema.Unknown.pipe(\n\tSchema.decodeTo(aikitAssistantMessageDeclared, {\n\t\tdecode: SchemaGetter.transformEffect(decodeAikitAssistantMessage),\n\t\tencode: SchemaGetter.transformEffect(decodeAikitAssistantMessage),\n\t}),\n);\nexport type AikitAssistantMessage = typeof AikitAssistantMessage.Type;\n\nconst decodeAikitToolCallTerminalPart = (value: unknown, options: SchemaAST.ParseOptions) =>\n\tEffect.try({\n\t\ttry: () => validateAikitToolCallTerminalPart(value, \"aikit terminal toolcall part\"),\n\t\tcatch: (cause) => new SchemaIssue.InvalidValue({ message: reasonOf(cause) }, value, options),\n\t});\n\nconst aikitToolCallTerminalPartDeclared = Schema.declare<Message.ToolCallTerminalPart>(isAikitToolCallTerminalPart, {\n\texpected: \"aikit terminal toolcall part\",\n});\n\nexport const AikitToolCallTerminalPart = Schema.Unknown.pipe(\n\tSchema.decodeTo(aikitToolCallTerminalPartDeclared, {\n\t\tdecode: SchemaGetter.transformEffect(decodeAikitToolCallTerminalPart),\n\t\tencode: SchemaGetter.transformEffect(decodeAikitToolCallTerminalPart),\n\t}),\n);\nexport type AikitToolCallTerminalPart = typeof AikitToolCallTerminalPart.Type;\n\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"Event.ID\"),\n\twithStatics((schema) => ({\n\t\tcreate: () => schema.make(`evt_${uuidv7()}`),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\nexport type Definition<\n\tType extends string = string,\n\tDataSchema extends Schema.Codec<unknown, unknown> = Schema.Codec<unknown, unknown>,\n> = Schema.Top & {\n\treadonly type: Type;\n\treadonly durable?: {\n\t\treadonly version: number; // event versioning for decoding in later time\n\t\treadonly aggregate: string;\n\t};\n\treadonly data: DataSchema;\n};\n\nexport type Data<D extends Definition> = Schema.Schema.Type<D[\"data\"]>;\n\nexport type Payload<D extends Definition = Definition> = {\n\treadonly id: ID;\n\treadonly type: D[\"type\"];\n\treadonly data: Data<D>;\n\treadonly durable?: {\n\t\treadonly aggregateId: string;\n\t\treadonly seq: number;\n\t\treadonly version: number;\n\t};\n\treadonly metadata?: Record<string, string>;\n};\n\nexport function define<\n\tconst Type extends string,\n\tconst Fields extends Readonly<Record<PropertyKey, Schema.Codec<unknown, unknown>>>,\n>(input: {\n\treadonly type: Type;\n\treadonly durable?: {\n\t\treadonly version: number;\n\t\treadonly aggregate: string;\n\t};\n\treadonly schema: Fields;\n}) {\n\tconst data = Schema.Struct(input.schema);\n\treturn Schema.Struct({\n\t\tid: ID,\n\t\tmetadata: optional(Schema.Record(Schema.String, Schema.String)),\n\t\ttype: Schema.Literal(input.type),\n\t\tdurable: optional(Schema.Struct({ aggregateId: Schema.String, seq: Schema.Int, version: Schema.Int })),\n\t\tdata,\n\t})\n\t\t.annotate({ identifier: input.type })\n\t\t.pipe(\n\t\t\twithStatics(() => ({\n\t\t\t\ttype: input.type,\n\t\t\t\t...(input.durable === undefined ? {} : { durable: input.durable }),\n\t\t\t\tdata,\n\t\t\t})),\n\t\t) satisfies Definition<Type, typeof data>;\n}\n\n// Register all the event definitions.\nexport function inventory<const Definitions extends ReadonlyArray<Definition>>(...definitions: Definitions) {\n\treturn Object.freeze(definitions);\n}\n\nexport function versionedType(type: string, version: number) {\n\treturn `${type}.${version}`;\n}\n\nexport function durable<const Definitions extends ReadonlyArray<Definition>>(definitions: Definitions) {\n\treturn readonlyMap(\n\t\tdefinitions.reduce((result, definition) => {\n\t\t\tif (!definition.durable) return result;\n\t\t\tconst key = versionedType(definition.type, definition.durable.version);\n\t\t\tif (result.has(key)) throw new Error(`duplicate durable event definition for ${key}`);\n\t\t\tresult.set(key, definition);\n\t\t\treturn result;\n\t\t}, new Map<string, Definitions[number]>()),\n\t);\n}\n\nfunction readonlyMap<Key, Value>(map: Map<Key, Value>): ReadonlyMap<Key, Value> {\n\tconst result: ReadonlyMap<Key, Value> = Object.freeze({\n\t\tget size() {\n\t\t\treturn map.size;\n\t\t},\n\t\tentries: () => map.entries(),\n\t\tforEach: (callback: (value: Value, key: Key, map: ReadonlyMap<Key, Value>) => void, thisArg?: unknown) =>\n\t\t\tmap.forEach((value, key) => callback.call(thisArg, value, key, result)),\n\t\tget: (key: Key) => map.get(key),\n\t\thas: (key: Key) => map.has(key),\n\t\tkeys: () => map.keys(),\n\t\tvalues: () => map.values(),\n\t\t[Symbol.iterator]: () => map[Symbol.iterator](),\n\t});\n\treturn result;\n}\n\nexport function latest(definitions: ReadonlyArray<Definition>) {\n\treturn readonlyMap(\n\t\tdefinitions.reduce((result, definition) => {\n\t\t\tconst existing = result.get(definition.type);\n\t\t\tif (!existing) {\n\t\t\t\tresult.set(definition.type, definition);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tif (definition.durable && existing.durable && definition.durable.version !== existing.durable.version) {\n\t\t\t\tif (definition.durable.version > existing.durable.version) result.set(definition.type, definition);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tif (definition !== existing) throw new Error(`duplicate latest event definition for ${definition.type}`);\n\t\t\treturn result;\n\t\t}, new Map<string, Definition>()),\n\t);\n}\n\nexport * as EventSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { AbsolutePath } from \"../schema.ts\";\n\n// Identified vcs type and its shared storage path.\n// Example: `{ type: \"git\", store: \"/app/code/.git\" }`\nexport const Vcs = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"git\"),\n\t\tstore: AbsolutePath,\n\t}),\n]);\nexport type Vcs = typeof Vcs.Type;\n\n// A discovered git repository. Every path is realpath'd.\nexport const Info = Schema.Struct({\n\t/**\n\t * The root directory of the working tree that contains the input path\n\t * (`rev-parse --show-toplevel`).\n\t *\n\t * For `/home/me/app/src/file.ts` in a normal clone, this is `/home/me/app`.\n\t * For `/home/me/app-feature/src/file.ts` in a linked worktree, this is\n\t * `/home/me/app-feature`.\n\t */\n\tdirectory: AbsolutePath,\n\t/**\n\t * This checkout's own git directory (`rev-parse --git-dir`).\n\t *\n\t * For a normal clone at `/home/me/app`, this is `/home/me/app/.git`. For a\n\t * linked worktree it lives under the store, e.g.\n\t * `/home/me/app/.git/worktrees/app-feature`. `gitDir === store` iff this is\n\t * the main checkout.\n\t */\n\tgitDir: AbsolutePath,\n\t/**\n\t * The shared Git storage directory used by this repo and any linked\n\t * worktrees (`rev-parse --git-common-dir`).\n\t *\n\t * For a normal clone at `/home/me/app`, this is usually `/home/me/app/.git`.\n\t * For a linked worktree at `/home/me/app-feature` whose main checkout is\n\t * `/home/me/app`, this is usually `/home/me/app/.git`.\n\t */\n\tstore: AbsolutePath,\n});\nexport type Info = typeof Info.Type;\n\nexport * as RepoSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { RepoSchema } from \"../repo/schema.ts\";\n\n// Env-independent project id: marker ?? remoteHash ?? rootCommit ?? provisional.\nexport const ID = Schema.String.pipe(Schema.brand(\"Project.ID\"));\nexport type ID = typeof ID.Type;\n\n// A project is archived, never deleted, once it has no active space anywhere.\nexport const Status = Schema.Literals([\"active\", \"archived\"]);\nexport type Status = typeof Status.Type;\n\nexport class Info extends Schema.Class<Info>(\"Project.Info\")({\n\tid: ID,\n\tname: Schema.String,\n\tstatus: Status,\n\tvcs: Schema.optional(RepoSchema.Vcs),\n}) {}\n\nexport * as ProjectSchema from \"./schema.ts\";\n","import { Option, Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { withStatics } from \"../schema.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\n\n/**\n * A Sandbox instance is a **durable filesystem namespace** plus whatever compute\n * acts on it — a device in Unix terms, which exists whether or not anything has\n * it mounted. `Sandbox.Controller` is the only thing that creates,\n * stops, or destroys one; this module is just its identity and state model.\n *\n * The application ID is deliberately separate from the driver's own resource\n * locator: callers never parse a Vercel name or a Daytona ID, driver formats may\n * change, and a destroyed resource must stay identifiable in Project/Session\n * history. A missing resource is never recreated under an existing ID — a new\n * resource is a new namespace and therefore a new ID.\n */\n\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"SandboxInstance.ID\"),\n\twithStatics((schema) => ({\n\t\t/**\n\t\t * The host. Reserved, and never written to a column — see {@link toColumn}.\n\t\t * It exists at runtime so nothing has to branch on \"is this the host\": it is\n\t\t * what identity reads, what logs show, and what the transport cache keys on.\n\t\t */\n\t\tlocal: schema.make(\"local\"),\n\t\t/** A fresh identity for a namespace nothing has named yet. */\n\t\tcreate: () => schema.make(`sbx_${uuidv7()}`),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\n/**\n * The storage boundary for namespace references, in one place.\n *\n * The host filesystem exists whether or not a row describes it, so it gets no\n * row and `NULL` is the only spelling of it — the Unix analogue is exact, since\n * `/` has no entry in the mount table you consult to find other mounts. That\n * makes a session or directory writable before any namespace is registered (the\n * foreign key is skipped on NULL), makes `SET sandbox_instance_id = NULL` a\n * meaningful \"revert to the host\", and leaves the host impossible to tombstone,\n * collect, or destroy, because there is nothing to point at.\n *\n * Two SQLite consequences ride on this and break correctness silently if missed:\n * unique indexes treat NULLs as distinct, so every uniqueness constraint\n * spanning a namespace column coalesces to `'local'`; and `= NULL` never\n * matches, so namespace-scoped reads use `IS`.\n */\nexport const toColumn = (id: ID): string | null => (id === ID.local ? null : id);\nexport const fromColumn = (value: string | null): ID => (value === null ? ID.local : ID.make(value));\n\n/**\n * The same mapping for row models, whose optional columns are `Option` rather\n * than `null`. Kept beside {@link toColumn} so the boundary stays one place:\n * `toColumn`/`fromColumn` for SQL parameters, these for `Model.FieldOption`.\n */\nexport const toField = (id: ID): Option.Option<ID> => (id === ID.local ? Option.none() : Option.some(id));\nexport const fromField = (value: Option.Option<ID>): ID => Option.getOrElse(value, () => ID.local);\n\n/**\n * Filesystem-class taxonomy, mirroring Unix: disk, tmpfs/procfs, NFS/CIFS.\n * Stored on the row rather than derived from the registered driver, so reading\n * an instance never depends on the registry — which matters most when a driver\n * is *not* configured and you need to list or clean up its rows.\n */\nexport const Kind = Schema.Literals([\"local\", \"virtual\", \"remote\"]);\nexport type Kind = typeof Kind.Type;\n\nexport const Ownership = Schema.Literals([\"managed\", \"external\"]);\nexport type Ownership = typeof Ownership.Type;\n\n/**\n * Lifecycle state, in ZFS pool vocabulary. This is the **last observed** value,\n * not live driver truth: Daytona auto-stops and auto-archives, Vercel sandboxes\n * expire on their own timeout, so drift is normal. `stateObservedAt` carries the\n * freshness and `Controller.refresh` updates it without waking anything.\n *\n * `removed` and `unavail` are deliberately distinct. `removed` means we deleted\n * it; `unavail` means the driver claims it is gone. A \"not found\" is frequently a\n * misclassification — wrong region, wrong API url, a revoked key answering 404,\n * eventual consistency right after create — so it must never be recorded as if we\n * had destroyed the resource ourselves.\n */\nexport const Status = Schema.Literals([\n\t\"provisioning\",\n\t\"online\",\n\t\"offline\",\n\t\"suspending\",\n\t\"removing\",\n\t\"removed\",\n\t\"unavail\",\n\t\"faulted\",\n]);\nexport type Status = typeof Status.Type;\n\n/**\n * The statuses a `mount` may proceed from. This is the predicate every\n * conditional write depends on, so it is enumerated once here rather than\n * restated as prose at each call site.\n *\n * `offline` qualifies because mounting wakes.\n * `faulted` qualifies because a fault is a *usability* condition, not an identity one — see {@link Status}.\n *\n * There is no `resuming`: it would exist to be observed by nothing, since\n * mounting wakes, `offline` is already mountable, and waking is not destructive\n * so it needs no claim. `suspending` and `removing` stay because they *are*\n * compare-and-set claims, blocking a concurrent mount mid-destruction.\n */\nexport const mountable: ReadonlySet<Status> = new Set<Status>([\"online\", \"offline\", \"faulted\"]);\n\nexport const isMountable = (status: Status): boolean => mountable.has(status);\n\n/**\n * Reference state, derived — never stored. `busy` carries its `umount` meaning:\n * something holds this and destruction must not proceed unforced.\n *\n * `pinned` is the kernel sense of the word: never reclaimable. It short-circuits\n * counting entirely for instances that cannot be stopped or destroyed (the local\n * host), which is what keeps them out of any future collector by construction\n * rather than by an ownership check happening to catch them.\n */\nexport const Usage = Schema.Literals([\"idle\", \"busy\", \"pinned\"]);\nexport type Usage = typeof Usage.Type;\n\n/** Sanitized driver failure. The only error shape allowed to be persisted or logged. */\nexport const PersistedError = Schema.Struct({\n\tname: Schema.String,\n\tmessage: Schema.String,\n\tcode: Schema.optional(Schema.String),\n});\nexport type PersistedError = typeof PersistedError.Type;\n\n/** Durable metadata, safe to return and persist. Assembled by the control plane. */\nexport interface Info {\n\treadonly id: ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: Kind;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly ownership: Ownership;\n\treadonly status: Status;\n\treadonly usage: Usage;\n\t/** References held by *this* control plane. Process-local; see the transport cache. */\n\treadonly refCount: number;\n\treadonly providerStatus: Option.Option<string>;\n\treadonly metadata: Readonly<Record<string, string>>;\n\treadonly lastError: Option.Option<PersistedError>;\n\treadonly createdAt: Date;\n\treadonly updatedAt: Date;\n\treadonly stateObservedAt: Date;\n\treadonly lastMountedAt: Option.Option<Date>;\n\treadonly lastUnmountedAt: Option.Option<Date>;\n\treadonly lastUsedAt: Option.Option<Date>;\n\treadonly removedAt: Option.Option<Date>;\n}\n\nexport * as SandboxInstance from \"./instance.ts\";\n","import { Schema } from \"effect\";\nimport { withStatics } from \"../../schema.ts\";\n\n// TODO: add support for diff input types\n// as supported by packages/aikit\nexport const Prompt = Schema.Struct({\n\ttext: Schema.String,\n})\n\t.annotate({ identifier: \"Prompt\" })\n\t.pipe(\n\t\twithStatics((schema) => ({\n\t\t\tequivalence: Schema.toEquivalence(schema),\n\t\t\tfromUserMessage: (input: Pick<Prompt, \"text\">) =>\n\t\t\t\tschema.make({\n\t\t\t\t\ttext: input.text,\n\t\t\t\t}),\n\t\t})),\n\t);\nexport type Prompt = typeof Prompt.Type;\n\nexport const Delivery = Schema.Literals([\"steer\", \"followUp\"]);\nexport type Delivery = typeof Delivery.Type;\n\nexport * as PromptSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\n\n// hash(env, location) — no project component, so re-pointing a space to\n// another project never rewrites the key sessions reference.\nexport const ID = Schema.String.pipe(Schema.brand(\"Space.ID\"));\nexport type ID = typeof ID.Type;\n\n// primary: the main checkout (one per project+env); linked: a git worktree\n// sharing the primary's store; copy: another clone; plain: a non-git directory.\nexport const Kind = Schema.Literals([\"primary\", \"linked\", \"copy\", \"plain\"]);\nexport type Kind = typeof Kind.Type;\n\nexport const Status = Schema.Literals([\"active\", \"archived\"]);\nexport type Status = typeof Status.Type;\n\n// One directory in one env that belongs to a project; the unit sessions attach to.\nexport class Info extends Schema.Class<Info>(\"Space.Info\")({\n\tid: ID,\n\tprojectId: ProjectSchema.ID,\n\tlocation: AbsolutePath,\n\tkind: Kind,\n\tenv: SandboxInstance.ID,\n\tstatus: Status,\n}) {}\n\nexport * as SpaceSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { Model } from \"effect/unstable/schema\";\nimport { EventSchema } from \"../event/schema.ts\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { AbsolutePath, NonNegativeInt } from \"../schema.ts\";\nimport { Prompt } from \"../session/prompt/schema.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { SpaceSchema } from \"../space/schema.ts\";\n\n// Column names derive from field names via the client's camelToSnake\n\n// DateTime fields encoded as millisecond integers; filled with the current\n// time on insert (createdAt) and on every insert/update (updatedAt).\nexport const Timestamps = {\n\tcreatedAt: Model.DateTimeInsertFromNumber,\n\tupdatedAt: Model.DateTimeUpdateFromNumber,\n};\n\nconst Metadata = Schema.Record(Schema.String, Schema.String);\n\n// Session entry discriminant. Frozen once shipped — values live in persisted\n// rows, so a rename is a data migration. Additions are code-only (the column is unconstrained TEXT).\nexport const entryTypes = [\n\t\"user\",\n\t\"assistant\",\n\t\"synthetic\",\n\t\"compaction\",\n\t\"branchSummary\",\n\t\"custom\",\n\t\"configChange\",\n] as const;\nexport type EntryType = (typeof entryTypes)[number];\n\nexport const messageEntryTypes = [\"user\", \"assistant\", \"synthetic\"] as const;\nexport type MessageEntryType = (typeof messageEntryTypes)[number];\n\n// Conversation visibility for one tree node. Non-assistant entries are born\n// committed; an assistant alone moves draft -> committed | aborted.\nexport const entryStates = [\"draft\", \"committed\", \"aborted\"] as const;\nexport type EntryState = (typeof entryStates)[number];\n\n// Part discriminant: aikit wire literals, verbatim — the column value always\n// equals json_extract(data, '$.type').\nexport const partTypes = [\"text\", \"image\", \"thinking\", \"toolCall\"] as const;\nexport type PartType = (typeof partTypes)[number];\n\n// aikit ToolStatusEnum, verbatim. \"running\" is never persisted in v0 (live-UI only)\n// but stays in the vocabulary so persisting live progress later needs no\n// migration; read-side code treats it like \"pending\" (unsettled).\nexport const toolStatuses = [\"pending\", \"running\", \"completed\", \"error\", \"skipped\", \"aborted\"] as const;\nexport type ToolStatus = (typeof toolStatuses)[number];\n\nexport const inputDeliveries = [\"steer\", \"followUp\"] as const;\nexport type InputDelivery = (typeof inputDeliveries)[number];\n\nconst EventData = Schema.Record(Schema.String, Schema.Unknown);\n\n// Head of the event sequence\nexport class EventSequenceRow extends Model.Class<EventSequenceRow>(\"EventSequenceRow\")({\n\taggregateId: Schema.String,\n\tseq: Schema.Natural,\n\townerId: Model.FieldOption(Schema.String),\n}) {}\n\n// Event with contigous sequence\nexport class EventRow extends Model.Class<EventRow>(\"EventRow\")({\n\tid: EventSchema.ID,\n\taggregateId: Schema.String,\n\tseq: Schema.Natural,\n\ttype: Schema.String,\n\tdata: Model.JsonFromString(EventData),\n}) {}\n\nexport class ProjectRow extends Model.Class<ProjectRow>(\"ProjectRow\")({\n\tid: Schema.String,\n\tname: Schema.String,\n\tstatus: ProjectSchema.Status,\n\t...Timestamps,\n}) {}\n\n/**\n * A durable filesystem namespace. The row is the whole durable model — reference\n * counts live in control-plane memory, never here, because a persisted count\n * cannot tell whether the process that took it is still alive.\n *\n * The host has no row: `local` is reserved and `NULL` is its storage form, so\n * this table only ever holds namespaces something had to provision.\n */\nexport class SandboxInstanceRow extends Model.Class<SandboxInstanceRow>(\"SandboxInstanceRow\")({\n\tid: SandboxInstance.ID,\n\tdriver: Schema.String,\n\tkind: SandboxInstance.Kind,\n\tproviderResourceId: Model.FieldOption(Schema.String),\n\truntimeConfig: Model.FieldOption(Schema.String),\n\townership: SandboxInstance.Ownership,\n\tstatus: SandboxInstance.Status,\n\tproviderStatus: Model.FieldOption(Schema.String),\n\tstateObservedAt: Model.DateTimeFromNumberWithNow,\n\tmetadata: Model.FieldOption(Model.JsonFromString(Metadata)),\n\tlastError: Model.FieldOption(Model.JsonFromString(SandboxInstance.PersistedError)),\n\tlastMountedAt: Model.FieldOption(Schema.DateTimeUtcFromMillis),\n\tlastUnmountedAt: Model.FieldOption(Schema.DateTimeUtcFromMillis),\n\tlastUsedAt: Model.FieldOption(Schema.DateTimeUtcFromMillis),\n\tremovedAt: Model.FieldOption(Schema.DateTimeUtcFromMillis),\n\t...Timestamps,\n}) {}\n\n// One directory in one env that belongs to a project. `id = hash(env, location)`.\nexport class SpaceRow extends Model.Class<SpaceRow>(\"SpaceRow\")({\n\tid: Schema.String,\n\tprojectId: Schema.String,\n\tlocation: AbsolutePath,\n\tkind: SpaceSchema.Kind,\n\t// Nullable: NULL is the host (same convention as sandboxInstanceId\n\t// elsewhere). Service-level code sees a plain ID through\n\t// SandboxInstance.toColumn/fromColumn and never branches on the host.\n\tenv: Model.FieldOption(SandboxInstance.ID),\n\tstatus: SpaceSchema.Status,\n\t...Timestamps,\n}) {}\n\nexport class SessionRow extends Model.Class<SessionRow>(\"SessionRow\")({\n\tid: SessionSchema.IDFromDb,\n\t// Project and env are derived through the space, never denormalised here.\n\tspaceId: Schema.String,\n\tparentId: Model.FieldOption(SessionSchema.IDFromDb),\n\tslug: Schema.String,\n\t// Absolute realpath of the session cwd; always equal to or under `space.location`.\n\tdirectory: AbsolutePath,\n\ttitle: Schema.String,\n\ttag: Model.FieldOption(Schema.String),\n\tmetadata: Model.FieldOption(Model.JsonFromString(Metadata)),\n\t// Durable leaf cursor: read anchor (path walks leaf→root) and append anchor\n\t// (new entries attach here). Moved inside every append/branch transaction.\n\tleafEntryId: Model.FieldOption(Schema.String),\n\t// Session-lifetime billed usage, mirroring aikit Usage. Bumped in the\n\t// assistant-append transaction; a cache — assistant envelopes are truth.\n\tcost: Model.GeneratedByDb(Schema.Finite),\n\ttokensInput: Model.GeneratedByDb(Schema.Int),\n\ttokensOutput: Model.GeneratedByDb(Schema.Int),\n\ttokensCacheRead: Model.GeneratedByDb(Schema.Int),\n\ttokensCacheWrite: Model.GeneratedByDb(Schema.Int),\n\t...Timestamps,\n}) {}\n\n// Durable input-queue record. admittedSeq is arrival order; promotedSeq is\n// nullable until Control delivers the input to the Loop, then records delivery\n// order. Neither sequence is related to session_entry.seq.\nexport class SessionInputRow extends Model.Class<SessionInputRow>(\"SessionInputRow\")({\n\tid: Schema.String,\n\tsessionId: SessionSchema.IDFromDb,\n\tprompt: Model.JsonFromString(Prompt), // normalized Prompt, stored as JSON\n\tdelivery: Schema.Literals(inputDeliveries),\n\tadmittedSeq: Schema.Int,\n\tpromotedSeq: Model.FieldOption(Schema.Int),\n\tcreatedAt: Model.DateTimeInsertFromNumber,\n}) {}\n\n// One timeline/tree node. Identity, tree position, and type are immutable.\n// A draft assistant's `data` and `state` are filled in place by lifecycle\n// projectors; other payloads are immutable. For message types\n// (user/assistant/synthetic), `data` holds the aikit message envelope\n// (everything except `parts`); parts live in SessionEntryPartRow.\nexport class SessionEntryRow extends Model.Class<SessionEntryRow>(\"SessionEntryRow\")({\n\tid: Schema.String,\n\tsessionId: SessionSchema.IDFromDb,\n\tparentId: Model.FieldOption(Schema.String), // tree edge; NULL = root\n\t// Position in the session's durable log: the sequence of the event that\n\t// produced this entry. Sparse — events that append nothing (a prompt\n\t// admission, say) leave gaps. Forked entries carry their source positions,\n\t// which is why the fork seeds the new aggregate above them.\n\tseq: NonNegativeInt,\n\ttype: Schema.Literals(entryTypes),\n\tstate: Schema.Literals(entryStates),\n\tdata: Schema.String, // JSON: full payload, or message envelope\n\tlabel: Model.FieldOption(Schema.String), // annotation: bookmark text\n\tmetadata: Model.FieldOption(Model.JsonFromString(Metadata)), // annotation: engine scratch\n\t...Timestamps,\n}) {}\n\n// One aikit message part. `data` is the verbatim aikit part JSON and is\n// authoritative; `status`/`callId`/`toolName` are promoted copies for indexed\n// queries, written together with `data`. The only mutation is toolCall\n// settlement (data + status), bounded by turn.end.\nexport class SessionEntryPartRow extends Model.Class<SessionEntryPartRow>(\"SessionEntryPartRow\")({\n\tid: Schema.String,\n\tentryId: Schema.String,\n\tsessionId: SessionSchema.IDFromDb, // denormalized for session-scoped queries\n\tpartIndex: Schema.Int, // dense 0..n-1 within the entry; the loop's addressing unit\n\ttype: Schema.Literals(partTypes),\n\tstatus: Model.FieldOption(Schema.Literals(toolStatuses)), // toolCall only\n\tcallId: Model.FieldOption(Schema.String), // toolCall only\n\ttoolName: Model.FieldOption(Schema.String), // toolCall only\n\tdata: Schema.String, // verbatim aikit part JSON\n\t...Timestamps,\n}) {}\n","import { Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { withStatics } from \"../../schema.ts\";\n\n/**\n * A conversation message id.\n *\n * Deliberately unprefixed. aikit mints assistant message ids itself, as bare\n * uuidv7, and `stream()` accepts no id -- so any naming rule of ours would have\n * to be imposed on messages aikit hands us, by rewriting a field of the value we\n * were given. Sharing aikit's format instead means an id means the same thing on\n * both sides of the boundary and never needs translating.\n *\n * The brand carries the meaning; uuidv7 keeps ids time-ordered, so they sort by\n * creation.\n */\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"Message.ID\"),\n\twithStatics((schema) => ({\n\t\tcreate: () => schema.make(uuidv7()),\n\t\t/**\n\t\t * Adopt an id minted elsewhere -- in practice aikit's, which arrives as a\n\t\t * plain string on every stream event and inside every assistant message.\n\t\t *\n\t\t * `make` does the same thing. This exists so the boundary where a foreign\n\t\t * id enters the domain is named and greppable, and so the pairing with\n\t\t * `create` says which side chose the id.\n\t\t */\n\t\tfrom: (id: string) => schema.make(id),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\nexport * as SessionMessageSchema from \"./schema.ts\";\n","import { Predicate, Schema } from \"effect\";\nimport { optional } from \"../schema.ts\";\n\n/**\n * The public description of a failed execution.\n *\n * Open by design: `type` is a namespaced category string, not a closed union.\n * A client older than the server degrades to the message instead of failing to\n * decode, and a new category is an additive change. The typed cause stays\n * server-side -- this is what crosses the wire.\n */\nexport const Error = Schema.Struct({\n\ttype: Schema.String,\n\tmessage: Schema.String,\n\t/** Provider HTTP status, when the failure came from one. */\n\tstatus: optional(Schema.Int),\n});\nexport type Error = typeof Error.Type;\n\nconst providerCategory = (tag: string): string => {\n\tswitch (tag) {\n\t\tcase \"Runner.ProviderAuthenticationError\":\n\t\t\treturn \"provider.auth\";\n\t\tcase \"Runner.ProviderAuthorizationError\":\n\t\t\treturn \"provider.forbidden\";\n\t\tcase \"Runner.ProviderConfigurationError\":\n\t\t\treturn \"provider.config\";\n\t\tcase \"Runner.ProviderModelUnavailableError\":\n\t\t\treturn \"provider.model-unavailable\";\n\t\tcase \"Runner.ProviderRateLimitError\":\n\t\t\treturn \"provider.rate-limit\";\n\t\tcase \"Runner.ProviderQuotaError\":\n\t\t\treturn \"provider.quota\";\n\t\tcase \"Runner.ProviderInvalidRequestError\":\n\t\t\treturn \"provider.invalid-request\";\n\t\tcase \"Runner.ProviderContentPolicyError\":\n\t\t\treturn \"provider.content-filter\";\n\t\tcase \"Runner.ProviderTimeoutError\":\n\t\t\treturn \"provider.timeout\";\n\t\tcase \"Runner.ProviderTransportError\":\n\t\t\treturn \"provider.transport\";\n\t\tcase \"Runner.ProviderUnavailableError\":\n\t\t\treturn \"provider.unavailable\";\n\t\tcase \"Runner.ProviderInvalidResponseError\":\n\t\t\treturn \"provider.invalid-output\";\n\t\tdefault:\n\t\t\treturn \"provider.unknown\";\n\t}\n};\n\nconst category = (tag: string): string => {\n\tswitch (tag) {\n\t\tcase \"Runner.ModelCatalogError\":\n\t\t\treturn \"model.catalog\";\n\t\tcase \"Runner.ModelNotFoundError\":\n\t\t\treturn \"model.not-found\";\n\t\tcase \"Runner.LLMStreamError\":\n\t\t\treturn \"llm.stream\";\n\t\tcase \"ContextDecodeError\":\n\t\t\treturn \"context.decode\";\n\t\tcase \"ContextEncodeError\":\n\t\t\treturn \"context.encode\";\n\t\tcase \"SessionNotFoundError\":\n\t\t\treturn \"session.not-found\";\n\t\tcase \"SessionLinkedSpaceNotFoundError\":\n\t\t\treturn \"session.space-not-found\";\n\t\tcase \"SettingsError\":\n\t\t\treturn \"settings\";\n\t\tcase \"State.SnapshotError\":\n\t\t\treturn \"state.snapshot\";\n\t\tcase \"Runner.SandboxDirectoryNotFoundError\":\n\t\t\treturn \"sandbox.directory-not-found\";\n\t\tcase \"SandboxFileSystemError\":\n\t\t\treturn \"sandbox.filesystem\";\n\t\tcase \"SandboxNotFoundError\":\n\t\tcase \"SandboxDriverNotRegisteredError\":\n\t\tcase \"SandboxUnavailError\":\n\t\tcase \"SandboxRemovedError\":\n\t\tcase \"SandboxProviderError\":\n\t\t\treturn \"sandbox.mount\";\n\t\tdefault:\n\t\t\treturn \"unknown\";\n\t}\n};\n\nconst message = (cause: unknown): string =>\n\tcause instanceof globalThis.Error ? cause.message : typeof cause === \"string\" ? cause : \"Session execution failed\";\n\n/** Projects a typed drain failure onto the category vocabulary clients see. */\nexport const fromCause = (cause: unknown): Error => {\n\tconst tag = Predicate.hasProperty(cause, \"_tag\") && typeof cause._tag === \"string\" ? cause._tag : undefined;\n\tif (tag === undefined) return { type: \"unknown\", message: message(cause) };\n\tif (tag === \"Runner.ProviderError\") {\n\t\tconst reason: unknown = Predicate.hasProperty(cause, \"reason\") ? cause.reason : undefined;\n\t\tconst reasonTag = Predicate.hasProperty(reason, \"_tag\") && typeof reason._tag === \"string\" ? reason._tag : \"\";\n\t\tconst status =\n\t\t\tPredicate.hasProperty(reason, \"status\") && typeof reason.status === \"number\" ? reason.status : undefined;\n\t\treturn {\n\t\t\ttype: providerCategory(reasonTag),\n\t\t\tmessage: message(cause),\n\t\t\t...(status === undefined ? {} : { status }),\n\t\t};\n\t}\n\treturn { type: category(tag), message: message(cause) };\n};\n\nexport * as SessionFailure from \"./failure.ts\";\n","import { Schema } from \"effect\";\nimport { DateTimeUtcFromMillis, NonNegativeInt } from \"../schema.ts\";\nimport { SessionMessageSchema } from \"../session/message/schema.ts\";\nimport { PromptSchema } from \"../session/prompt/schema.ts\";\nimport { SessionFailure } from \"../session/failure.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { EventSchema } from \"./schema.ts\";\n\nconst baseOptions = {\n\ttimestamp: DateTimeUtcFromMillis,\n\tsessionId: SessionSchema.ID,\n};\nconst durableOptions = {\n\tdurable: {\n\t\taggregate: \"sessionId\",\n\t\tversion: 1,\n\t},\n} as const;\n\nconst PromptFields = {\n\t...baseOptions,\n\tmessageId: SessionMessageSchema.ID,\n\tprompt: PromptSchema.Prompt,\n\tdelivery: PromptSchema.Delivery,\n};\n\nexport const PromptAdmitted = EventSchema.define({\n\ttype: \"session.prompt.admitted\",\n\t...durableOptions,\n\tschema: PromptFields,\n});\nexport type PromptAdmitted = typeof PromptAdmitted.Type;\n\nexport const Prompted = EventSchema.define({\n\ttype: \"session.prompt.promoted\",\n\t...durableOptions,\n\tschema: PromptFields,\n});\nexport type Prompted = typeof Prompted.Type;\n\n// export const ConfigChanged = EventSchema.define({\n// \ttype: \"session.config.changed\",\n// \t...durableOptions,\n// \tschema: {\n// \t\t...baseOptions,\n// \t\tmodel: optional(\n// \t\t\tSchema.Struct({\n// \t\t\t\tproviderId: Schema.String,\n// \t\t\t\tmodelId: Schema.String,\n// \t\t\t}),\n// \t\t),\n// \t\tthinkingLevel: optional(Schema.Literals([\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"])),\n// \t},\n// });\n// export type ConfigChanged = typeof ConfigChanged.Type;\n\nconst LLMFields = {\n\t...baseOptions,\n\tmessageId: SessionMessageSchema.ID,\n};\n\nconst LLMPartFields = {\n\t...LLMFields,\n\tpartIndex: NonNegativeInt,\n};\n\nexport const TurnAbortCause = Schema.Union([\n\tSchema.TaggedStruct(\"interrupted\", {}),\n\tSchema.TaggedStruct(\"error\", { message: Schema.String }),\n\tSchema.TaggedStruct(\"deferred\", { message: Schema.String }),\n]);\nexport type TurnAbortCause = typeof TurnAbortCause.Type;\n\nexport const TurnStarted = EventSchema.define({\n\ttype: \"session.turn.started\",\n\tschema: baseOptions,\n});\nexport type TurnStarted = typeof TurnStarted.Type;\n\nexport const TurnEnded = EventSchema.define({\n\ttype: \"session.turn.ended\",\n\t...durableOptions,\n\tschema: LLMFields,\n});\nexport type TurnEnded = typeof TurnEnded.Type;\n\nexport const TurnAborted = EventSchema.define({\n\ttype: \"session.turn.aborted\",\n\tschema: { ...baseOptions, cause: TurnAbortCause },\n});\nexport type TurnAborted = typeof TurnAborted.Type;\n\n/** Durable insertion of the request's draft assistant placeholder. */\nexport const LLMStarted = EventSchema.define({\n\ttype: \"session.llm.started\",\n\t...durableOptions,\n\tschema: { ...LLMFields, message: EventSchema.AikitAssistantMessage },\n});\nexport type LLMStarted = typeof LLMStarted.Type;\n\nexport const LLMTextStart = EventSchema.define({\n\ttype: \"session.llm.text.start\",\n\tschema: LLMPartFields,\n});\nexport type LLMTextStart = typeof LLMTextStart.Type;\n\nexport const LLMTextDelta = EventSchema.define({\n\ttype: \"session.llm.text.delta\",\n\tschema: { ...LLMPartFields, delta: Schema.String },\n});\nexport type LLMTextDelta = typeof LLMTextDelta.Type;\n\nexport const LLMTextEnd = EventSchema.define({\n\ttype: \"session.llm.text.end\",\n\tschema: { ...LLMPartFields, content: Schema.String },\n});\nexport type LLMTextEnd = typeof LLMTextEnd.Type;\n\nexport const LLMThinkingStart = EventSchema.define({\n\ttype: \"session.llm.thinking.start\",\n\tschema: LLMPartFields,\n});\nexport type LLMThinkingStart = typeof LLMThinkingStart.Type;\n\nexport const LLMThinkingDelta = EventSchema.define({\n\ttype: \"session.llm.thinking.delta\",\n\tschema: { ...LLMPartFields, delta: Schema.String },\n});\nexport type LLMThinkingDelta = typeof LLMThinkingDelta.Type;\n\nexport const LLMThinkingEnd = EventSchema.define({\n\ttype: \"session.llm.thinking.end\",\n\tschema: { ...LLMPartFields, content: Schema.String },\n});\nexport type LLMThinkingEnd = typeof LLMThinkingEnd.Type;\n\n/** aikit `done`: replace the LLMStarted payload in place; state stays draft. */\nexport const LLMEnded = EventSchema.define({\n\ttype: \"session.llm.ended\",\n\t...durableOptions,\n\tschema: {\n\t\t...LLMFields,\n\t\treason: Schema.Literals([\"stop\", \"length\", \"toolUse\"]),\n\t\tmessage: EventSchema.AikitAssistantMessage,\n\t},\n});\nexport type LLMEnded = typeof LLMEnded.Type;\n\n/** Abort the whole draft and discard every part. */\nexport const LLMFailed = EventSchema.define({\n\ttype: \"session.llm.failed\",\n\t...durableOptions,\n\tschema: {\n\t\t...LLMFields,\n\t\treason: Schema.Literals([\"aborted\", \"error\"]),\n\t\tmessage: EventSchema.AikitAssistantMessage,\n\t},\n});\nexport type LLMFailed = typeof LLMFailed.Type;\n\nexport const ToolStarted = EventSchema.define({\n\ttype: \"session.tool.started\",\n\tschema: { ...LLMFields, callID: Schema.String, name: Schema.String },\n});\nexport type ToolStarted = typeof ToolStarted.Type;\n\nexport const ToolProgress = EventSchema.define({\n\ttype: \"session.tool.progress\",\n\tschema: { ...LLMFields, callID: Schema.String, partial: Schema.Unknown },\n});\nexport type ToolProgress = typeof ToolProgress.Type;\n\nexport const ToolSettled = EventSchema.define({\n\ttype: \"session.tool.settled\",\n\t...durableOptions,\n\tschema: {\n\t\t...LLMFields,\n\t\tcallID: Schema.String,\n\t\tpart: EventSchema.AikitToolCallTerminalPart,\n\t},\n});\nexport type ToolSettled = typeof ToolSettled.Type;\n\n/**\n * First event in a forked session's log. The aggregate is the *new* session, so\n * this lands at `baseSeq + 1`: the fork seeds the new aggregate's sequence to\n * the fork point, reserving [0..baseSeq] for the copied entries. Recording it\n * makes the seeded range auditable from the log itself, not only from\n * `session.parentId`.\n */\nexport const SessionForked = EventSchema.define({\n\ttype: \"session.next.forked\",\n\t...durableOptions,\n\tschema: {\n\t\t...baseOptions,\n\t\tsourceSessionId: SessionSchema.ID,\n\t\t/** Entry in the source session the copy stops at (its leaf, for a clone). */\n\t\tsourceEntryId: Schema.String,\n\t\t/** Highest sequence carried over; the new log starts above it. */\n\t\tbaseSeq: NonNegativeInt,\n\t},\n});\nexport type SessionForked = typeof SessionForked.Type;\n\n/**\n * Lifecycle of a process-owned busy period. One `started` and exactly one\n * terminal per period, covering every drain the period coalesced. The terminals\n * are separate types rather than one event with a status, so each carries only\n * what its outcome actually has: a failure has an error, an interruption has a\n * reason, and a success has neither.\n */\nexport const ExecutionStarted = EventSchema.define({\n\ttype: \"session.execution.started\",\n\tschema: baseOptions,\n});\nexport type ExecutionStarted = typeof ExecutionStarted.Type;\n\nexport const ExecutionSucceeded = EventSchema.define({\n\ttype: \"session.execution.succeeded\",\n\tschema: baseOptions,\n});\nexport type ExecutionSucceeded = typeof ExecutionSucceeded.Type;\n\nexport const ExecutionFailed = EventSchema.define({\n\ttype: \"session.execution.failed\",\n\tschema: { ...baseOptions, error: SessionFailure.Error },\n});\nexport type ExecutionFailed = typeof ExecutionFailed.Type;\n\nexport const ExecutionInterrupted = EventSchema.define({\n\ttype: \"session.execution.interrupted\",\n\tschema: { ...baseOptions, reason: SessionSchema.InterruptReason },\n});\nexport type ExecutionInterrupted = typeof ExecutionInterrupted.Type;\n\n/**\n * Everything the kernel can publish. `PublicDefinitions` is the narrower set\n * that reaches clients -- adding an event here does not publish it.\n */\nexport const Definitions = EventSchema.inventory(\n\tExecutionStarted,\n\tExecutionSucceeded,\n\tExecutionFailed,\n\tExecutionInterrupted,\n\tPromptAdmitted,\n\tPrompted,\n\tSessionForked,\n\tTurnStarted,\n\tTurnEnded,\n\tTurnAborted,\n\tLLMStarted,\n\tLLMTextStart,\n\tLLMTextDelta,\n\tLLMTextEnd,\n\tLLMThinkingStart,\n\tLLMThinkingDelta,\n\tLLMThinkingEnd,\n\tLLMEnded,\n\tLLMFailed,\n\tToolStarted,\n\tToolProgress,\n\tToolSettled,\n);\n\n/**\n * The wire contract: what a client is allowed to receive. Identical to\n * `Definitions` today, and separate so that adding a kernel event is not by\n * itself a decision to publish it.\n */\nexport const PublicDefinitions = Definitions;\n\nexport const DurableDefinitions = EventSchema.inventory(\n\tPromptAdmitted,\n\tPrompted,\n\tSessionForked,\n\tTurnEnded,\n\tLLMStarted,\n\tLLMEnded,\n\tLLMFailed,\n\tToolSettled,\n);\n\nexport * as EventList from \"./list.ts\";\n","// This shall pull the durable event definition\n// before this we need to have event definition that needs to be registered.\n\nimport { Schema as EffectSchema } from \"effect\";\nimport { EventList } from \"./list.ts\";\nimport { EventSchema } from \"./schema.ts\";\n\nexport const Durable = EventSchema.durable([...EventList.DurableDefinitions]);\nexport const Schema = EffectSchema.Union([...EventList.DurableDefinitions], { mode: \"oneOf\" }).pipe(\n\tEffectSchema.toTaggedUnion(\"type\"),\n);\n\nexport const Manifest = {\n\tdefinitions: Durable,\n\tschema: Schema,\n} as const;\n\nexport * as EventManifest from \"./manifest.ts\";\n","import { Cause, Context, Effect, Layer, Option, PubSub, Queue, Ref, Stream } from \"effect\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { EventRow } from \"../db/schema.sql.ts\";\n// Uncomment with `decodeSerializedEvent` below — the manifest is what it looks\n// stored types up in.\n// import { Durable } from \"./manifest.ts\";\nimport { Schema } from \"effect\";\nimport { EventManifest } from \"./manifest.ts\";\nimport type { Data, Definition, ID, Payload } from \"./schema.ts\";\nimport { EventSchema } from \"./schema.ts\";\n\nexport type SerializedEvent = {\n\treadonly id: ID;\n\treadonly type: string;\n\treadonly seq: number;\n\treadonly aggregateId: string;\n\treadonly data: Record<string, unknown>;\n};\n\nexport type Subscriber<D extends Definition = Definition> = (event: Payload<D>) => Effect.Effect<void>;\nexport type Unsubscribe = Effect.Effect<void>;\n\nexport class InvalidDurableEventError extends Schema.TaggedError<InvalidDurableEventError>()(\n\t\"InvalidDurableEventError\",\n\t{\n\t\ttype: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n// TODO: uncomment when required!\n// const decodeSerializedEvent = (event: SerializedEvent): Payload => {\n// const definition = Durable.get(event.type);\n// if (!definition?.durable) {\n// throw new Error(`unknown durable event type ${event.type}`);\n// }\n// return {\n// id: event.id,\n// type: definition.type,\n// durable: {\n// aggregateId: event.aggregateId,\n// seq: event.seq,\n// version: definition.durable.version,\n// },\n// data: Schema.decodeUnknownSync(definition.data)(event.data),\n// };\n// };\n\n/**\n * A durable read manifest: the definitions whose stored rows are in scope, keyed\n * by versioned type, plus the decoder those rows are decoded through. `schema`\n * is the tagged union of the same definitions, so it validates the whole\n * envelope (id/type/durable/data), not just the payload.\n */\nexport type Manifest<A> = {\n\treadonly definitions: ReadonlyMap<string, Definition>;\n\treadonly schema: Schema.Decoder<A, never>;\n};\n\nexport type ReadAggregateInput<A> = {\n\treadonly aggregateId: string;\n\t/** Exclusive lower bound. Omitted reads from the first stored sequence (0). */\n\treadonly after?: number;\n\treadonly limit: number;\n\treadonly manifest: Manifest<A>;\n};\n\nexport type ReadAggregateResult<A> = {\n\treadonly events: ReadonlyArray<A>;\n\treadonly hasMore: boolean;\n};\n\n/**\n * Marks completion of the initial journal read through the captured sequence.\n * Emitted once per `log` stream; omitted `seq` means the head was -1.\n * This is a replay boundary, not an acknowledgment of consumer processing.\n */\nexport type Synced = {\n\treadonly type: \"log.synced\";\n\treadonly aggregateId: string;\n\treadonly seq?: number;\n};\n\n/** Either a stored event or the watermark marker that ends `log`'s catch-up. */\nexport type LogItem = Payload | Synced;\n\nexport const isSynced = (item: LogItem): item is Synced => item.type === \"log.synced\";\n\nexport type LogInput = {\n\treadonly aggregateId: string;\n\t/** Exclusive lower bound. Omitted reads from the first stored sequence (0). */\n\treadonly after?: number;\n\t/** Keep the stream open past the marker, appending events as they commit. */\n\treadonly follow?: boolean;\n\t/**\n\t * Which stored types this read understands, keyed by versioned type -- build it\n\t * with `EventSchema.durable([...definitions])`. Rows of any other type are\n\t * skipped, exactly as an unknown type from a newer build is. Defaults to the\n\t * application manifest, so a kernel reader passes nothing.\n\t *\n\t * A caller owning durable definitions outside `EventList` supplies them here,\n\t * including the older versions it still decodes; the default does not know them\n\t * and would filter every row.\n\t *\n\t * Only the definitions are needed, not a decoder: `log` decodes each row's\n\t * `data` with its own definition and builds the envelope itself, so what it\n\t * emits is always a well-formed {@link Payload}.\n\t */\n\treadonly definitions?: ReadonlyMap<string, Definition>;\n};\n\nexport interface PublishOptions {\n\t/** Caller-supplied event ID. Publishing the same ID twice is a defect, not an upsert. */\n\treadonly id?: ID;\n\t/**\n\t * Publish-time context — correlation, tracing — carried to projectors on the\n\t * in-memory payload and deliberately not stored in the event row. A projector\n\t * persists it into its own projection if it means something there; the log\n\t * records what happened, not who asked. It therefore does not survive a\n\t * durable reread or a rebuild, which `event.test.ts` pins explicitly.\n\t */\n\treadonly metadata?: Record<string, string>;\n}\n\nexport class SubscriptionOverflowError extends Schema.TaggedError<SubscriptionOverflowError>()(\n\t\"SubscriptionOverflowError\",\n\t{ capacity: Schema.Int },\n) {}\n\nexport interface SubscribeOptions {\n\t/** Maximum queued events per consumer. Defaults to 4096; must be a positive integer. */\n\treadonly capacity?: number;\n}\n\nexport interface Subscribe {\n\t(options?: SubscribeOptions): Stream.Stream<Payload, SubscriptionOverflowError>;\n\t<D extends Definition>(\n\t\tdefinition: D,\n\t\toptions?: SubscribeOptions,\n\t): Stream.Stream<Payload<D>, SubscriptionOverflowError>;\n}\n\nexport interface Interface {\n\t/** Current sequence head, or -1 if absent. A version position, not a row count. */\n\treadonly latestSequence: (aggregateId: string) => Effect.Effect<number>;\n\t/**\n\t * Reads one page of stored events in sequence order, filtered and decoded by\n\t * the supplied manifest. `after` is exclusive; `hasMore` indicates another\n\t * matching page. Does not follow new commits or emit a sync marker.\n\t */\n\treadonly readAggregate: <A>(input: ReadAggregateInput<A>) => Effect.Effect<ReadAggregateResult<A>>;\n\t/**\n\t * Reads one aggregate's stored events after the exclusive `after` cursor in\n\t * sequence order, decoded through `input.definitions` -- the application\n\t * manifest unless the caller owns durable types outside `EventList`. Types the\n\t * definitions do not name are skipped. Emits a {@link Synced} marker after reading\n\t * through the captured head.\n\t *\n\t * Completes after the marker unless `follow` is true. Following rereads storage\n\t * when this service instance commits an event; writes through other instances\n\t * do not wake it. Ephemeral events are never included.\n\t */\n\treadonly log: (input: LogInput) => Stream.Stream<LogItem>;\n\t/**\n\t * Publishes one event and returns its payload. Durable events receive an\n\t * aggregate sequence and commit with their projector changes in one transaction,\n\t * then wake log followers before notifying live consumers. Ephemeral events\n\t * only notify live consumers and have no stored row or durable sequence.\n\t */\n\treadonly publish: <D extends Definition>(\n\t\tdefinition: D,\n\t\tdata: Data<D>,\n\t\toptions?: PublishOptions,\n\t) => Effect.Effect<Payload<D>>;\n\t/**\n\t * Registers a callback for future durable commits of one type. Runs inside\n\t * the transaction, so failure rolls back the event and transactional changes.\n\t * Does not replay history. Registering an ephemeral type never invokes it.\n\t */\n\treadonly project: <D extends Definition>(definition: D, projector: Subscriber<D>) => Effect.Effect<void>;\n\t/**\n\t * Future durable and ephemeral events from this instance, optionally filtered\n\t * by definition. Each consumer has a bounded queue; overflow fails only that\n\t * subscription without blocking publishers. Subscribes when consumed, with no\n\t * replay. Concurrent notification order may differ from durable sequence order;\n\t * use `log` for ordered recovery. Missed ephemeral events cannot be recovered.\n\t */\n\treadonly subscribe: Subscribe;\n\t/**\n\t * Registers a live callback across types and aggregates; returns an effect to\n\t * remove it. Publishers await callbacks before notifying stream subscribers.\n\t * Keep callbacks short, such as nonblocking queue insertion; perform network IO\n\t * and slow processing in a separate consumer.\n\t * Durable callbacks run after commit: non-interruption failures are logged,\n\t * while interruption propagates. Ephemeral callback failures propagate.\n\t */\n\treadonly listen: (listener: Subscriber) => Effect.Effect<Unsubscribe>;\n\t/**\n\t * Moves the sequence head to at least `seq` without inserting an event, running\n\t * projectors, or waking followers. Used to reserve an inherited prefix on a\n\t * fork. The next durable event receives a higher sequence; never rewinds.\n\t */\n\treadonly advance: (aggregateId: string, seq: number) => Effect.Effect<void>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/event/event/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\n\t\tconst pubsub = {\n\t\t\t// Per-aggregate doorbells for `log`. A wake carries no payload -- the\n\t\t\t// follower rereads the table -- so sliding(1) is enough: a coalesced\n\t\t\t// wake loses nothing, and a slow follower never holds up a publish.\n\t\t\tdurable: new Map<string, Set<PubSub.PubSub<void>>>(),\n\t\t};\n\t\tconst subscriptions = new Set<{\n\t\t\treadonly type: string | undefined;\n\t\t\treadonly capacity: number;\n\t\t\treadonly queue: Queue.Queue<Payload, SubscriptionOverflowError>;\n\t\t}>();\n\t\tconst projectors = new Map<string, Subscriber[]>();\n\t\tconst listeners = new Array<Subscriber>();\n\n\t\t// Subscribers block on their pubsub, so releasing the layer without\n\t\t// shutting them down strands whoever is reading a stream from it.\n\t\tyield* Effect.addFinalizer(() =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tyield* Effect.forEach(subscriptions, (subscriber) => Queue.shutdown(subscriber.queue), { discard: true });\n\t\t\t\tsubscriptions.clear();\n\t\t\t\tyield* Effect.forEach(\n\t\t\t\t\tArray.from(pubsub.durable.values(), (wakes) => Array.from(wakes)).flat(),\n\t\t\t\t\tPubSub.shutdown,\n\t\t\t\t\t{ discard: true },\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\n\t\tconst observe = (event: Payload, observer: (event: Payload) => Effect.Effect<void>) =>\n\t\t\tEffect.suspend(() => observer(event)).pipe(\n\t\t\t\tEffect.catchCauseIf(\n\t\t\t\t\t(cause) => !Cause.hasInterrupts(cause),\n\t\t\t\t\t(cause) => Effect.logError(\"Event listener failed\", { eventID: event.id, eventType: event.type, cause }),\n\t\t\t\t),\n\t\t\t);\n\n\t\t// Snapshotted: a follower's scope can close on another fiber while this\n\t\t// iterates, and publishing into a shut-down wake it already left is a no-op.\n\t\tconst wakeFollowers = (aggregateId: string) =>\n\t\t\tEffect.forEach(Array.from(pubsub.durable.get(aggregateId) ?? []), (wake) => PubSub.publish(wake, undefined), {\n\t\t\t\tdiscard: true,\n\t\t\t});\n\n\t\tfunction notify(event: Payload, isolateListeners: boolean) {\n\t\t\treturn Effect.gen(function* () {\n\t\t\t\tyield* Effect.forEach(\n\t\t\t\t\tlisteners,\n\t\t\t\t\t(listener) => (isolateListeners ? observe(event, listener) : listener(event)),\n\t\t\t\t\t{ discard: true },\n\t\t\t\t);\n\t\t\t\tyield* Effect.sync(() => {\n\t\t\t\t\tfor (const subscriber of subscriptions) {\n\t\t\t\t\t\tif (subscriber.type !== undefined && subscriber.type !== event.type) continue;\n\t\t\t\t\t\tif (Queue.offerUnsafe(subscriber.queue, event)) continue;\n\t\t\t\t\t\tsubscriptions.delete(subscriber);\n\t\t\t\t\t\tQueue.failCauseUnsafe(\n\t\t\t\t\t\t\tsubscriber.queue,\n\t\t\t\t\t\t\tCause.fail(new SubscriptionOverflowError({ capacity: subscriber.capacity })),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\t// aggregate_id is the primary key, so the first row is the only row.\n\t\tconst findLatestSequence = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: Schema.Struct({ seq: Schema.Int }),\n\t\t\texecute: (aggregateId) => sql`SELECT seq FROM event_sequence WHERE aggregate_id = ${aggregateId}`,\n\t\t});\n\n\t\t// -1 for an aggregate that has never been written, so that the first\n\t\t// sequence a publisher assigns (`latest + 1`) is 0.\n\t\tconst latestSequence = Effect.fn(\"Event.latestSequence\")(function* (aggregateId: string) {\n\t\t\treturn yield* findLatestSequence(aggregateId).pipe(\n\t\t\t\tEffect.map(Option.match({ onNone: () => -1, onSome: (row) => row.seq })),\n\t\t\t\tEffect.orDie,\n\t\t\t);\n\t\t});\n\n\t\t// Type is filtered against the manifest so a row written by a build that\n\t\t// knew more event types is skipped rather than failing the whole page.\n\t\tconst selectAggregateEvents = SqlSchema.findAll({\n\t\t\tRequest: Schema.Struct({\n\t\t\t\taggregateId: Schema.String,\n\t\t\t\tafter: Schema.Int,\n\t\t\t\tthrough: Schema.Int,\n\t\t\t\ttypes: Schema.Array(Schema.String),\n\t\t\t\tlimit: Schema.Int,\n\t\t\t}),\n\t\t\tResult: EventRow,\n\t\t\texecute: ({ aggregateId, after, through, types, limit }) =>\n\t\t\t\tsql`\n SELECT * FROM event\n WHERE aggregate_id = ${aggregateId} AND seq > ${after} AND seq <= ${through} AND ${sql.in(\"type\", types)}\n ORDER BY seq ASC\n LIMIT ${limit}\n `,\n\t\t});\n\n\t\t// The `type` column stores the versioned type; the envelope carries the\n\t\t// bare type, so it is mapped back through the definition. A row that no\n\t\t// longer decodes is a broken store, not a recoverable read.\n\t\tconst decodeRows = <A>(rows: ReadonlyArray<EventRow>, manifest: Manifest<A>) => {\n\t\t\tconst decode = Schema.decodeUnknownEffect(manifest.schema);\n\t\t\treturn Effect.forEach(rows, (row) => {\n\t\t\t\tconst definition = manifest.definitions.get(row.type);\n\t\t\t\treturn decode({\n\t\t\t\t\tid: row.id,\n\t\t\t\t\ttype: definition?.type ?? row.type,\n\t\t\t\t\tdurable: {\n\t\t\t\t\t\taggregateId: row.aggregateId,\n\t\t\t\t\t\tseq: row.seq,\n\t\t\t\t\t\tversion: definition?.durable?.version,\n\t\t\t\t\t},\n\t\t\t\t\tdata: row.data,\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\t// An unbounded read: `seq` is a signed 32-bit column, so this is above any\n\t\t// sequence the store can hold.\n\t\tconst UNBOUNDED = Number.MAX_SAFE_INTEGER;\n\t\t// Rows per page while walking an aggregate. Large enough that a long session\n\t\t// replays in a handful of queries, small enough to stay off the heap.\n\t\tconst PAGE_SIZE = 128;\n\n\t\t// Reads one page of an aggregate's durable history. One row past the page is\n\t\t// fetched so `hasMore` needs no second query; the extra row is dropped.\n\t\tconst readAggregate = Effect.fn(\"Event.readAggregate\")(function* <A>(input: ReadAggregateInput<A>) {\n\t\t\tconst rows = yield* selectAggregateEvents({\n\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\tafter: input.after ?? -1,\n\t\t\t\tthrough: UNBOUNDED,\n\t\t\t\ttypes: Array.from(input.manifest.definitions.keys()),\n\t\t\t\tlimit: input.limit + 1,\n\t\t\t});\n\t\t\tconst page = rows.slice(0, input.limit);\n\t\t\tconst events = yield* decodeRows(page, input.manifest);\n\t\t\treturn { events, hasMore: rows.length > input.limit };\n\t\t}, Effect.orDie);\n\n\t\t/**\n\t\t * One stored row to a payload, decoding `data` with its own definition and\n\t\t * building the envelope from the row. Deliberately not a decode of the whole\n\t\t * envelope through a union: `log` promises {@link Payload}, so `id`, `type`\n\t\t * and `durable` are the kernel's to construct, never a caller-supplied\n\t\t * decoder's to reshape or drop.\n\t\t */\n\t\tconst decodeLogRow = Effect.fn(\"Event.decodeLogRow\")(function* (\n\t\t\trow: EventRow,\n\t\t\tdefinitions: ReadonlyMap<string, Definition>,\n\t\t) {\n\t\t\t// The SQL filter is built from these same keys, so a row here always matches.\n\t\t\tconst definition = definitions.get(row.type)!;\n\t\t\t// The envelope's version is the stored row's, read back off its definition; a default\n\t\t\t// would label the row with a version nothing wrote. Callers filter non-durable\n\t\t\t// definitions out before this, so the guard is a backstop, not a code path.\n\t\t\tif (definition.durable === undefined)\n\t\t\t\treturn yield* Effect.die(\n\t\t\t\t\tnew InvalidDurableEventError({\n\t\t\t\t\t\ttype: definition.type,\n\t\t\t\t\t\tmessage: `Unknown durable event type ${definition.type}`,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\tconst data = yield* Schema.decodeEffect(definition.data as Schema.Codec<unknown, unknown>)(row.data);\n\t\t\treturn {\n\t\t\t\tid: row.id,\n\t\t\t\ttype: definition.type,\n\t\t\t\tdurable: { aggregateId: row.aggregateId, seq: row.seq, version: definition.durable.version },\n\t\t\t\tdata,\n\t\t\t} as Payload;\n\t\t});\n\n\t\t// The same read as `readAggregate`, bounded above and paged for `log`. The\n\t\t// manifest is a parameter rather than the process-wide one: a reader owning\n\t\t// durable types outside `EventList` supplies its own, and the filter would\n\t\t// otherwise drop every one of its rows.\n\t\tconst readPage = Effect.fn(\"Event.readPage\")(function* (input: {\n\t\t\treadonly aggregateId: string;\n\t\t\treadonly after: number;\n\t\t\treadonly through: number;\n\t\t\treadonly definitions: ReadonlyMap<string, Definition>;\n\t\t}) {\n\t\t\tconst rows = yield* selectAggregateEvents({\n\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\tafter: input.after,\n\t\t\t\tthrough: input.through,\n\t\t\t\ttypes: Array.from(input.definitions.keys()),\n\t\t\t\tlimit: PAGE_SIZE + 1,\n\t\t\t});\n\t\t\tconst page = rows.slice(0, PAGE_SIZE);\n\t\t\t// Skip a type the manifest does not carry as durable rather than failing the read: the\n\t\t\t// aggregate may hold rows this process cannot decode. `seq` below comes off the raw\n\t\t\t// tail, so cursors advance across the gap.\n\t\t\tconst decodable = page.filter((row) => input.definitions.get(row.type)?.durable !== undefined);\n\t\t\tconst events = yield* Effect.forEach(decodable, (row) => decodeLogRow(row, input.definitions));\n\t\t\t// `seq` is the stored row's, not one read back off a decoded value: the\n\t\t\t// window advances on what the table actually holds.\n\t\t\treturn { events, hasMore: rows.length > PAGE_SIZE, seq: page.at(-1)?.seq };\n\t\t}, Effect.orDie);\n\n\t\t/** One catch-up pass over (`from`, `through`], paged, oldest first. */\n\t\tconst readAggregateStream = (input: {\n\t\t\treadonly aggregateId: string;\n\t\t\treadonly from: number;\n\t\t\treadonly through: number;\n\t\t\treadonly definitions: ReadonlyMap<string, Definition>;\n\t\t}): Stream.Stream<Payload> =>\n\t\t\tStream.paginate(\n\t\t\t\tinput.from,\n\t\t\t\tEffect.fn(\"Event.readAggregateStream.page\")(function* (after: number) {\n\t\t\t\t\tconst page = yield* readPage({\n\t\t\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\t\t\tafter,\n\t\t\t\t\t\tthrough: input.through,\n\t\t\t\t\t\tdefinitions: input.definitions,\n\t\t\t\t\t});\n\t\t\t\t\tconst next = page.hasMore && page.seq !== undefined ? Option.some(page.seq) : Option.none<number>();\n\t\t\t\t\treturn [page.events, next] as const;\n\t\t\t\t}),\n\t\t\t);\n\n\t\t// Allocates an aggregate's next sequence in one statement: the row is\n\t\t// created at 0 or bumped by one, and the new value comes back. Deliberately\n\t\t// not a SELECT followed by an INSERT -- `SqlClient` begins DEFERRED, and a\n\t\t// read-then-write transaction can fail the lock upgrade with\n\t\t// SQLITE_BUSY_SNAPSHOT under WAL (see sandbox/store.ts). Writing first takes\n\t\t// the write lock on the transaction's first statement instead.\n\t\tconst bumpSequence = SqlSchema.findOne({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: Schema.Struct({ seq: Schema.Int }),\n\t\t\texecute: (aggregateId) => sql`\n INSERT INTO event_sequence (aggregate_id, seq) VALUES (${aggregateId}, 0)\n ON CONFLICT(aggregate_id) DO UPDATE SET seq = event_sequence.seq + 1\n RETURNING seq\n `,\n\t\t});\n\n\t\tconst findEventById = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: Schema.Struct({ aggregateId: Schema.String, seq: Schema.Int }),\n\t\t\texecute: (id) => sql`SELECT aggregate_id, seq FROM event WHERE id = ${id}`,\n\t\t});\n\n\t\tconst insertEvent = SqlSchema.void({\n\t\t\tRequest: EventRow.insert,\n\t\t\texecute: (row) => sql`INSERT INTO event ${sql.insert(row)}`,\n\t\t});\n\n\t\t/**\n\t\t * Assigns the sequence, runs the projectors, and stores the row as one unit.\n\t\t * Projecting inside the transaction is the point: a projector that rejects\n\t\t * the event (a lifecycle conflict, say) takes the event down with it, so the\n\t\t * log and its views can never disagree.\n\t\t */\n\t\tconst commitDurableEvent = Effect.fn(\"Event.commitDurableEvent\")(\n\t\t\tfunction* <D extends Definition>(definition: D, event: Payload<D>) {\n\t\t\t\tconst durable = definition.durable;\n\t\t\t\tif (!durable) return undefined;\n\t\t\t\tconst aggregateId = (event.data as Record<string, unknown>)[durable.aggregate];\n\t\t\t\tif (typeof aggregateId !== \"string\")\n\t\t\t\t\treturn yield* Effect.die(\n\t\t\t\t\t\tnew InvalidDurableEventError({\n\t\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\t\tmessage: `Expected string aggregate field ${durable.aggregate}`,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\tconst encoded = (yield* Schema.encodeUnknownEffect(definition.data)(event.data)) as Record<string, unknown>;\n\t\t\t\tconst committed = yield* sql.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { seq } = yield* bumpSequence(aggregateId);\n\t\t\t\t\t\tconst existing = yield* findEventById(event.id);\n\t\t\t\t\t\tif (Option.isSome(existing))\n\t\t\t\t\t\t\treturn yield* Effect.die(\n\t\t\t\t\t\t\t\tnew InvalidDurableEventError({\n\t\t\t\t\t\t\t\t\ttype: event.type,\n\t\t\t\t\t\t\t\t\tmessage: `Event ${event.id} already exists at aggregate ${existing.value.aggregateId} sequence ${existing.value.seq}`,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst payload = {\n\t\t\t\t\t\t\t...event,\n\t\t\t\t\t\t\tdurable: { aggregateId, seq, version: durable.version },\n\t\t\t\t\t\t} as Payload<D>;\n\t\t\t\t\t\tfor (const projector of projectors.get(event.type) ?? []) yield* projector(payload as Payload);\n\t\t\t\t\t\t// The stored type carries the version; the in-memory payload does not.\n\t\t\t\t\t\tyield* insertEvent({\n\t\t\t\t\t\t\tid: event.id,\n\t\t\t\t\t\t\taggregateId,\n\t\t\t\t\t\t\tseq,\n\t\t\t\t\t\t\ttype: EventSchema.versionedType(definition.type, durable.version),\n\t\t\t\t\t\t\tdata: encoded,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn payload;\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Keep the post-commit wake uninterruptible too: cancellation must not\n\t\t\t\t// strand a stored row while followers wait for their next notification.\n\t\t\t\tyield* wakeFollowers(aggregateId);\n\t\t\t\treturn committed;\n\t\t\t},\n\t\t\tEffect.orDie,\n\t\t\tEffect.uninterruptible,\n\t\t);\n\n\t\tconst publishEvent = Effect.fn(\"Event.publishEvent\")(function* <D extends Definition>(\n\t\t\tdefinition: D,\n\t\t\tevent: Payload<D>,\n\t\t) {\n\t\t\tif (definition.durable) {\n\t\t\t\tconst committed = yield* commitDurableEvent(definition, event);\n\t\t\t\t// Durable listeners are isolated: the event is already committed, so a\n\t\t\t\t// throwing listener must not surface as a failed publish.\n\t\t\t\tif (committed) {\n\t\t\t\t\tyield* notify(committed as Payload, true);\n\t\t\t\t\treturn committed;\n\t\t\t\t}\n\t\t\t}\n\t\t\tyield* notify(event as Payload, false);\n\t\t\treturn event;\n\t\t});\n\n\t\tconst publish = Effect.fn(\"Event.publish\")(function* <D extends Definition>(\n\t\t\tdefinition: D,\n\t\t\tdata: Data<D>,\n\t\t\toptions?: PublishOptions,\n\t\t) {\n\t\t\treturn yield* publishEvent(definition, {\n\t\t\t\tid: options?.id ?? EventSchema.ID.create(),\n\t\t\t\t...(options?.metadata ? { metadata: options.metadata } : {}),\n\t\t\t\ttype: definition.type,\n\t\t\t\tdata,\n\t\t\t} as Payload<D>);\n\t\t});\n\n\t\t// MAX, so this only ever moves the head forward. Lowering it would hand out\n\t\t// sequences that already exist.\n\t\tconst advanceSequence = SqlSchema.void({\n\t\t\tRequest: Schema.Struct({ aggregateId: Schema.String, seq: Schema.Int }),\n\t\t\texecute: ({ aggregateId, seq }) => sql`\n INSERT INTO event_sequence (aggregate_id, seq) VALUES (${aggregateId}, ${seq})\n ON CONFLICT(aggregate_id) DO UPDATE SET seq = MAX(event_sequence.seq, excluded.seq)\n `,\n\t\t});\n\n\t\tconst advance = Effect.fn(\"Event.advance\")(function* (aggregateId: string, seq: number) {\n\t\t\tyield* advanceSequence({ aggregateId, seq });\n\t\t}, Effect.orDie);\n\n\t\tconst project = <D extends Definition>(definition: D, projector: Subscriber<D>): Effect.Effect<void> =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst list = projectors.get(definition.type) ?? [];\n\t\t\t\tlist.push((event) => projector(event as Payload<D>));\n\t\t\t\tprojectors.set(definition.type, list);\n\t\t\t});\n\n\t\tfunction subscribe(options?: SubscribeOptions): Stream.Stream<Payload, SubscriptionOverflowError>;\n\t\tfunction subscribe<D extends Definition>(\n\t\t\tdefinition: D,\n\t\t\toptions?: SubscribeOptions,\n\t\t): Stream.Stream<Payload<D>, SubscriptionOverflowError>;\n\t\tfunction subscribe(\n\t\t\tinput?: Definition | SubscribeOptions,\n\t\t\toptions?: SubscribeOptions,\n\t\t): Stream.Stream<Payload, SubscriptionOverflowError> {\n\t\t\tconst definition = input && \"type\" in input ? input : undefined;\n\t\t\tconst capacity = (definition ? options : (input as SubscribeOptions | undefined))?.capacity ?? 4096;\n\t\t\treturn Stream.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tif (!Number.isSafeInteger(capacity) || capacity <= 0)\n\t\t\t\t\t\treturn yield* Effect.die(new RangeError(\"Subscription capacity must be a positive integer\"));\n\t\t\t\t\tconst queue = yield* Queue.dropping<Payload, SubscriptionOverflowError>(capacity);\n\t\t\t\t\tconst subscriber = { type: definition?.type, capacity, queue };\n\t\t\t\t\tyield* Effect.acquireRelease(\n\t\t\t\t\t\tEffect.sync(() => subscriptions.add(subscriber)),\n\t\t\t\t\t\t() => Effect.sync(() => subscriptions.delete(subscriber)).pipe(Effect.andThen(Queue.shutdown(queue))),\n\t\t\t\t\t);\n\t\t\t\t\treturn Stream.fromQueue(queue);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\t/**\n\t\t * Registers a doorbell for one aggregate, removed with the caller's scope.\n\t\t * Subscribing before publishing it means the follower cannot miss a wake it\n\t\t * is registered for.\n\t\t */\n\t\tconst subscribeWake = (aggregateId: string) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst wake = yield* PubSub.sliding<void>(1);\n\t\t\t\tconst subscription = yield* PubSub.subscribe(wake);\n\t\t\t\tyield* Effect.acquireRelease(\n\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\tconst wakes = pubsub.durable.get(aggregateId) ?? new Set<PubSub.PubSub<void>>();\n\t\t\t\t\t\twakes.add(wake);\n\t\t\t\t\t\tpubsub.durable.set(aggregateId, wakes);\n\t\t\t\t\t}),\n\t\t\t\t\t() =>\n\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\tconst wakes = pubsub.durable.get(aggregateId);\n\t\t\t\t\t\t\twakes?.delete(wake);\n\t\t\t\t\t\t\tif (wakes?.size === 0) pubsub.durable.delete(aggregateId);\n\t\t\t\t\t\t}).pipe(Effect.andThen(PubSub.shutdown(wake))),\n\t\t\t\t);\n\t\t\t\treturn subscription;\n\t\t\t});\n\n\t\tconst log = (input: LogInput): Stream.Stream<LogItem> =>\n\t\t\tStream.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst definitions = input.definitions ?? EventManifest.Manifest.definitions;\n\t\t\t\t\t// The cursor outlives a single catch-up: each wake resumes from the\n\t\t\t\t\t// last sequence actually emitted, not from where the pass began.\n\t\t\t\t\tconst cursor = yield* Ref.make(input.after ?? -1);\n\t\t\t\t\tconst catchUp = (through: number): Stream.Stream<Payload> =>\n\t\t\t\t\t\tStream.unwrap(\n\t\t\t\t\t\t\tRef.get(cursor).pipe(\n\t\t\t\t\t\t\t\tEffect.map((from) =>\n\t\t\t\t\t\t\t\t\treadAggregateStream({ aggregateId: input.aggregateId, from, through, definitions }),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t).pipe(\n\t\t\t\t\t\t\t// `durable` is built by `decodeLogRow`, never by a caller's decoder,\n\t\t\t\t\t\t\t// so the sequence here is always the stored one.\n\t\t\t\t\t\t\tStream.tap((event) =>\n\t\t\t\t\t\t\t\tevent.durable === undefined ? Effect.void : Ref.set(cursor, event.durable.seq),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t// A finished pass read the whole window, so the cursor belongs at\n\t\t\t\t\t\t\t// its bound rather than at the last row that happened to be in it.\n\t\t\t\t\t\t\t// Without this, a head standing above the rows -- `advance` on a\n\t\t\t\t\t\t\t// fork, or types this build cannot decode -- would leave the live\n\t\t\t\t\t\t\t// filter permanently open and reread nothing on every wake. Only\n\t\t\t\t\t\t\t// on completion: a pass cut short mid-window must resume from the\n\t\t\t\t\t\t\t// last event actually emitted.\n\t\t\t\t\t\t\tStream.onEnd(Ref.update(cursor, (seq) => Math.max(seq, through))),\n\t\t\t\t\t\t);\n\t\t\t\t\t// Registering the doorbell before reading the head is what closes the\n\t\t\t\t\t// gap: a commit landing during catch-up is either inside the window\n\t\t\t\t\t// pinned below or waiting as a wake once the marker is out.\n\t\t\t\t\tconst wakes = input.follow ? yield* subscribeWake(input.aggregateId) : undefined;\n\t\t\t\t\t// Reading the head, and every reread below, can never land inside a\n\t\t\t\t\t// publisher's open transaction: the client holds one connection behind\n\t\t\t\t\t// a Semaphore(1), and `withTransaction` keeps that permit until it\n\t\t\t\t\t// commits. So a follower never sees a bumped sequence whose row is not\n\t\t\t\t\t// there yet, and never emits an event a failing projector rolls back.\n\t\t\t\t\t// A connection pool would take that guarantee away and need its own\n\t\t\t\t\t// per-aggregate lock.\n\t\t\t\t\tconst head = yield* latestSequence(input.aggregateId);\n\t\t\t\t\tconst marker: Synced = {\n\t\t\t\t\t\ttype: \"log.synced\",\n\t\t\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\t\t\t...(head >= 0 ? { seq: head } : {}),\n\t\t\t\t\t};\n\t\t\t\t\tconst replay = catchUp(head).pipe(Stream.concat(Stream.make(marker)));\n\t\t\t\t\tif (!wakes) return replay;\n\t\t\t\t\tconst live = Stream.fromSubscription(wakes).pipe(\n\t\t\t\t\t\tStream.mapEffect(() => latestSequence(input.aggregateId)),\n\t\t\t\t\t\t// A wake coalesced with one already drained, or one for rows this\n\t\t\t\t\t\t// build cannot decode, leaves the head where the cursor is.\n\t\t\t\t\t\tStream.filterEffect((target) => Ref.get(cursor).pipe(Effect.map((seq) => target > seq))),\n\t\t\t\t\t\tStream.flatMap((target) => catchUp(target)),\n\t\t\t\t\t);\n\t\t\t\t\treturn replay.pipe(Stream.concat(live));\n\t\t\t\t}),\n\t\t\t);\n\n\t\tconst listen = (listener: Subscriber): Effect.Effect<Unsubscribe> =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tlisteners.push(listener);\n\t\t\t\treturn Effect.sync(() => {\n\t\t\t\t\tconst index = listeners.indexOf(listener);\n\t\t\t\t\tif (index >= 0) listeners.splice(index, 1);\n\t\t\t\t});\n\t\t\t});\n\n\t\treturn Service.of({\n\t\t\tlatestSequence,\n\t\t\treadAggregate,\n\t\t\tlog,\n\t\t\tpublish,\n\t\t\tsubscribe,\n\t\t\tlisten,\n\t\t\tproject,\n\t\t\tadvance,\n\t\t});\n\t}),\n);\n\nexport * as Event from \"./event.ts\";\n","import { Context, Effect, Schema } from \"effect\";\nimport { posix } from \"../../util/posix.ts\";\n\n/**\n * The runtime filesystem contract, independent of any backend.\n *\n * Two surfaces, deliberately:\n * - {@link Provider} is what a backend implements — plain promises that reject,\n * matching every SDK we wrap.\n * - {@link Interface} is what the harness consumes — Effect with a typed error\n * channel and tracing spans. {@link fromProvider} bridges the two exactly\n * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.\n *\n * Implementations:\n * - Local:\n * implement it over a VFS (`./local`);\n * local filesystem use OS primitives; hence have broader filesytem capabilities.\n *\n * - Remote:\n * implement it over a provider (`./remote`).\n * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.\n *\n * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the\n * backend cannot report them — never fabricated.\n *\n * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`\n * separators on both the host and inside a sandbox — Windows is not supported,\n * so no translation layer exists. Consumers must use the shared Effect POSIX\n * path implementation, never the platform default, or a host running the harness would\n * impose its own flavour on a remote sandbox's paths. Relative paths resolve\n * against the backend's configured `cwd`.\n */\n\nexport class OperationUnsupportedError extends Schema.TaggedError<OperationUnsupportedError>()(\n\t\"OperationUnsupportedError\",\n\t{\n\t\toperation: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n/** A backend operation failed. `cause` carries the provider's own rejection. */\nexport class FileSystemError extends Schema.TaggedError<FileSystemError>()(\"SandboxFileSystemError\", {\n\tmethod: Schema.String,\n\tpath: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface FileStat {\n\treadonly isFile: boolean;\n\treadonly isDirectory: boolean;\n\treadonly isSymbolicLink?: boolean;\n\treadonly size?: number;\n\treadonly mtime?: Date;\n}\n\nexport interface RmOptions {\n\treadonly recursive?: boolean;\n\treadonly force?: boolean;\n}\n\n/** Whether a provider failure means the path itself is definitively absent. */\nexport const isNotFoundError = (cause: unknown) => {\n\tconst code = (cause as NodeJS.ErrnoException | undefined)?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n};\n\n/**\n * Shell forms of `realpath` for backends that only expose a process API.\n * `pwd -P` is the portable primitive: directories resolve directly, anything\n * else resolves its parent and keeps the final name as given. Run as\n * `sh -c <script> _ <path>`; try the first, fall back to the second.\n */\nexport const realpathScripts = [\n\t'cd -- \"$1\" && pwd -P',\n\t'cd -- \"$(dirname -- \"$1\")\" && printf \\'%s/%s\\' \"$(pwd -P)\" \"$(basename -- \"$1\")\"',\n] as const;\n\n/**\n * The backend-facing contract. Backends author plain promises and let them\n * reject; {@link fromProvider} turns rejections into typed failures.\n */\nexport interface Provider {\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly readFileBuffer: (path: string) => Promise<Uint8Array>;\n\t/**\n\t * Write the file. Parents may be missing — do not create them here;\n\t * {@link fromProvider} owns that guarantee for every backend.\n\t */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Promise<void>;\n\treadonly stat: (path: string) => Promise<FileStat>;\n\treadonly readdir: (path: string) => Promise<string[]>;\n\treadonly exists: (path: string) => Promise<boolean>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n\treadonly rm: (path: string, options?: RmOptions) => Promise<void>;\n\t/** Canonical absolute path with symlinks resolved; rejects when the path does not exist. */\n\treadonly realpath: (path: string) => Promise<string>;\n\t/**\n\t * Metadata for the directory entry itself rather than a symlink's target.\n\t * Optional: a backend whose `stat` has mixed symlink semantics implements it\n\t * so symlink identity is asked for explicitly, never inferred.\n\t */\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\n/**\n * The consumer-facing contract. `exists` distinguishes \"absent\" from \"could not\n * tell\": a backend failure is a typed failure, not `false`, so a caller acting\n * on absence never acts on a network blip. Use `SandboxFs.existsOrFalse` where\n * a best-effort answer really is wanted.\n */\nexport interface Interface {\n\treadonly readFile: (path: string) => Effect.Effect<string, FileSystemError>;\n\treadonly readFileBuffer: (path: string) => Effect.Effect<Uint8Array, FileSystemError>;\n\t/** Creates missing parent directories, on every backend. */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Effect.Effect<void, FileSystemError>;\n\treadonly stat: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n\treadonly readdir: (path: string) => Effect.Effect<string[], FileSystemError>;\n\treadonly exists: (path: string) => Effect.Effect<boolean, FileSystemError>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Effect.Effect<void, FileSystemError>;\n\treadonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;\n\t/** Canonical absolute path with symlinks resolved; fails when the path does not exist. */\n\treadonly realpath: (path: string) => Effect.Effect<string, FileSystemError>;\n\t// `lstat` is present only when the backend supports it; check before calling.\n\treadonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n}\n\n/** The runtime filesystem service — the live {@link Interface} for the active sandbox. */\nexport class Service extends Context.Service<Service, Interface>()(\n\t\"@codeworksh/harness/sandbox/fs/filesystem/Service\",\n) {}\n\n/**\n * Reject `rm` options a provider does not implement, before any mutation. Only\n * `recursive` and `force` are part of the contract; anything else is refused\n * loudly rather than silently ignored.\n */\nexport const validateRmOptions = (\n\toptions: RmOptions | undefined,\n\toperation = \"rm\",\n): Effect.Effect<void, OperationUnsupportedError> =>\n\tEffect.suspend(() => {\n\t\tfor (const option of Object.keys((options ?? {}) as Record<string, unknown>)) {\n\t\t\tif (option === \"recursive\" || option === \"force\") continue;\n\t\t\treturn Effect.fail(new OperationUnsupportedError({ operation, message: `Unsupported rm option: ${option}` }));\n\t\t}\n\t\treturn Effect.void;\n\t});\n\n/**\n * Lift a {@link Provider} into the runtime {@link Interface}: one place that\n * converts rejections into {@link FileSystemError}, validates `rm` options,\n * creates missing parents on write, and names a tracing span per operation.\n */\nexport const fromProvider = (provider: Provider): Interface => {\n\tconst attempt = <A>(method: string, path: string, run: () => Promise<A>) =>\n\t\tEffect.tryPromise({ try: run, catch: (cause) => new FileSystemError({ method, path, cause }) });\n\n\t// The parent-creation guarantee, installed once for every backend instead of\n\t// re-implemented per provider: anything that reaches `Interface` reaches it\n\t// through here, so a backend cannot forget it.\n\t//\n\t// Lazy by design — try the write first, so the happy path stays a single call\n\t// and no remote backend pays a round-trip per write. A failure is usually a\n\t// missing parent, so create it and retry once. The mkdir's own error is\n\t// dropped on purpose: when the write failed for some other reason (EACCES,\n\t// EROFS, a dropped connection), the retry reproduces it, and *that* is the\n\t// failure the caller must see rather than a misleading mkdir error standing\n\t// in for it.\n\tconst writeCreatingParents = (path: string, content: string | Uint8Array) => {\n\t\tconst write = attempt(\"writeFile\", path, () => provider.writeFile(path, content));\n\t\tconst parent = posix.dirname(path);\n\t\treturn write.pipe(\n\t\t\tEffect.catch(() =>\n\t\t\t\tattempt(\"mkdir\", parent, () => provider.mkdir(parent, { recursive: true })).pipe(\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.andThen(write),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\treturn {\n\t\treadFile: Effect.fn(\"SandboxFileSystem.readFile\")((path: string) =>\n\t\t\tattempt(\"readFile\", path, () => provider.readFile(path)),\n\t\t),\n\t\treadFileBuffer: Effect.fn(\"SandboxFileSystem.readFileBuffer\")((path: string) =>\n\t\t\tattempt(\"readFileBuffer\", path, () => provider.readFileBuffer(path)),\n\t\t),\n\t\twriteFile: Effect.fn(\"SandboxFileSystem.writeFile\")(writeCreatingParents),\n\t\tstat: Effect.fn(\"SandboxFileSystem.stat\")((path: string) => attempt(\"stat\", path, () => provider.stat(path))),\n\t\t// carried through only when the backend actually implements it\n\t\t...(provider.lstat === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlstat: Effect.fn(\"SandboxFileSystem.lstat\")((path: string) =>\n\t\t\t\t\t\tattempt(\"lstat\", path, () => provider.lstat!(path)),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treaddir: Effect.fn(\"SandboxFileSystem.readdir\")((path: string) =>\n\t\t\tattempt(\"readdir\", path, () => provider.readdir(path)),\n\t\t),\n\t\t// A backend that cannot answer fails; it does not report \"absent\". A\n\t\t// caller acting on absence — deleting a record, say — must not be told\n\t\t// the path is gone because a token expired or a request timed out.\n\t\texists: Effect.fn(\"SandboxFileSystem.exists\")((path: string) =>\n\t\t\tattempt(\"exists\", path, () => provider.exists(path)),\n\t\t),\n\t\tmkdir: Effect.fn(\"SandboxFileSystem.mkdir\")((path: string, options?: { recursive?: boolean }) =>\n\t\t\tattempt(\"mkdir\", path, () => provider.mkdir(path, options)),\n\t\t),\n\t\trm: Effect.fn(\"SandboxFileSystem.rm\")((path: string, options?: RmOptions) =>\n\t\t\tvalidateRmOptions(options).pipe(Effect.andThen(attempt(\"rm\", path, () => provider.rm(path, options)))),\n\t\t),\n\t\trealpath: Effect.fn(\"SandboxFileSystem.realpath\")((path: string) =>\n\t\t\tattempt(\"realpath\", path, () => provider.realpath(path)),\n\t\t),\n\t};\n};\n\n/**\n * Bind a cwd-neutral filesystem to one mount's working directory.\n *\n * The counterpart of `Shell.withCwd`, and the reason relative paths mean the\n * same thing to both: a shared transport stays rooted at the namespace root, so\n * resolution happens here, per mount, rather than inside a VFS whose `chdir` is\n * global state two mounts would fight over.\n */\nexport const withCwd = (fs: Interface, cwd: string): Interface => {\n\tconst at = (path: string) => posix.resolve(cwd, path);\n\treturn {\n\t\treadFile: (path) => fs.readFile(at(path)),\n\t\treadFileBuffer: (path) => fs.readFileBuffer(at(path)),\n\t\twriteFile: (path, content) => fs.writeFile(at(path), content),\n\t\tstat: (path) => fs.stat(at(path)),\n\t\treaddir: (path) => fs.readdir(at(path)),\n\t\texists: (path) => fs.exists(at(path)),\n\t\tmkdir: (path, options) => fs.mkdir(at(path), options),\n\t\trm: (path, options) => fs.rm(at(path), options),\n\t\trealpath: (path) => fs.realpath(at(path)),\n\t\t// carried through only when the backend implements it, so a caller can\n\t\t// still detect absence by checking the property\n\t\t...(fs.lstat === undefined ? {} : { lstat: (path: string) => fs.lstat!(at(path)) }),\n\t};\n};\n\nexport * as SandboxFileSystem from \"./filesystem.ts\";\n","import { Context, type Effect, Schema, type Stream } from \"effect\";\nimport { posix as path } from \"../../util/posix.ts\";\n\n/**\n * The pluggable execution contract. Local sandboxes usually get a Shell through\n * just-bash over the local `Local.Vfs`; remote sandboxes provide their own\n * native Shell. Either way the rest of the harness depends only on this service\n * tag.\n */\n\nexport class ShellError extends Schema.TaggedError<ShellError>()(\"ShellError\", {\n\tcommand: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface ExecResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number;\n}\n\n/**\n * One options shape for every entry point. `cwd` is the operation-level\n * override: it wins over the mount's working directory, and a relative value\n * resolves against it. Neither mutates shared state, so concurrent commands in\n * one mount can run in different directories.\n */\nexport interface ShellOptions {\n\treadonly env?: Record<string, string>;\n\treadonly cwd?: string;\n}\n\n/**\n * A streamed chunk of command output, terminated by a single `exit` carrying the\n * exit code. (A backend-level mirror of the tool layer's event; kept here so\n * `sandbox/` does not depend on `tool/`.)\n */\nexport type ExecChunk =\n\t| { readonly _tag: \"stdout\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"stderr\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"exit\"; readonly exitCode: number };\n\n/**\n * The command-execution capability a sandbox exposes. For an in-process\n * backend this is just-bash; for a remote backend it is the sandbox's own\n * shell. The {@link Shell} service tag carries this interface.\n */\nexport interface ISandboxExe {\n\treadonly exec: (command: string, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Run a program with an explicit argument vector, bypassing shell word\n\t * splitting. Callers that build commands from untrusted values — branch\n\t * names, file paths — must use this instead of interpolating into\n\t * {@link exec}, where a space or `$(…)` would change what runs.\n\t *\n\t * Backends whose transport only accepts a string quote the vector with\n\t * {@link quote}; backends that spawn directly pass it through untouched.\n\t */\n\treadonly execArgv: (argv: ReadonlyArray<string>, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Optional streaming output: stdout/stderr chunks then a terminal `exit`.\n\t * Backends that can stream (e.g. Vercel) implement it; `ToolShell.fromSandboxShell`\n\t * bridges it to `ToolShell.stream` so the bash tool streams over them too.\n\t */\n\treadonly stream?: (command: string, options?: ShellOptions) => Stream.Stream<ExecChunk, ShellError>;\n}\n\ntype MountFactory = (cwd: string) => ISandboxExe;\n\n/**\n * Mount-local shell factories are attached out-of-band so the public Shell\n * contract stays about command execution only.\n *\n * Most transports are safely shared and need only the cwd wrapper below.\n * Stateful in-process interpreters use this hook to construct one interpreter\n * per mount while retaining the underlying filesystem transport. This tag must\n * remain on the outermost wrapper consumed by {@link withCwd}; wrapper helpers\n * such as {@link fromExec} must propagate it when they return a new object.\n */\nconst mountFactories = new WeakMap<object, MountFactory>();\n\nexport const perMount = (transport: ISandboxExe, make: MountFactory): ISandboxExe => {\n\tmountFactories.set(transport, make);\n\treturn transport;\n};\n\n/**\n * POSIX single-quote escaping: wrap in `'…'` and rewrite each embedded quote as\n * `'\\''`. Everything inside single quotes is literal to the shell, so this is\n * safe for arbitrary bytes.\n */\nexport const quote = (value: string) => `'${value.replace(/'/g, `'\\\\''`)}'`;\n\n/** Render an argument vector as one shell-safe command string. */\nexport const quoteArgv = (argv: ReadonlyArray<string>) => argv.map(quote).join(\" \");\n\n/**\n * Resolve a per-command cwd against the sandbox cwd. Passing a relative cwd\n * straight to a host or remote process API would otherwise resolve it against\n * that API's own default, which need not be the filesystem's configured cwd.\n */\nexport const resolveCwd = (base: string | undefined, cwd: string | undefined) => {\n\tif (cwd === undefined || path.isAbsolute(cwd) || base === undefined) return cwd ?? base;\n\treturn path.resolve(base, cwd);\n};\n\n/**\n * Complete a string-only backend: `execArgv` quotes the vector and runs it\n * through `exec`. Backends that spawn a real argument vector (Vercel) implement\n * `execArgv` themselves instead, so the args never meet a shell parser at all.\n *\n * `cwd` rides the options rather than a `cd <dir> && …` prefix. Every backend\n * we wrap takes a working directory natively, and the prefix form cannot tell a\n * failed `cd` from a failed command — both arrive as one exit code.\n */\nexport const fromExec = (backend: Omit<ISandboxExe, \"execArgv\">): ISandboxExe => {\n\tconst wrapped: ISandboxExe = {\n\t\t...backend,\n\t\texecArgv: (argv, options) => backend.exec(quoteArgv(argv), options),\n\t};\n\tconst mountFactory = mountFactories.get(backend);\n\treturn mountFactory === undefined ? wrapped : perMount(wrapped, (cwd) => fromExec(mountFactory(cwd)));\n};\n\n/**\n * Bind a cwd-neutral backend to one mount's working directory.\n *\n * The transport is shared between mounts and must stay rooted at the namespace\n * root, so the directory cannot live inside it: two mounts at different\n * directories would otherwise see each other's. This wrapper is per mount, and\n * an operation-level `cwd` still wins — resolved against the mount's, so a\n * relative one means what it reads like.\n */\nexport const withCwd = (backend: ISandboxExe, cwd: string): ISandboxExe => {\n\tconst mounted = mountFactories.get(backend)?.(cwd) ?? backend;\n\tconst at = (options?: ShellOptions): ShellOptions => {\n\t\tconst resolvedCwd = resolveCwd(cwd, options?.cwd);\n\t\treturn { ...options, ...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }) };\n\t};\n\tconst stream = mounted.stream;\n\treturn {\n\t\texec: (command, options) => mounted.exec(command, at(options)),\n\t\texecArgv: (argv, options) => mounted.execArgv(argv, at(options)),\n\t\t...(stream === undefined ? {} : { stream: (command, options) => stream(command, at(options)) }),\n\t};\n};\n\n/** Execution service — the live {@link ISandboxExe} for the active sandbox. */\nexport class Shell extends Context.Service<Shell, ISandboxExe>()(\"@codeworksh/harness/sandbox/shell/shell\") {}\n","import { Context, Effect, Layer as EffectLayer } from \"effect\";\nimport { posix } from \"../util/posix.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\nimport { SandboxFileSystem } from \"./fs/filesystem.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { type ISandboxExe, Shell as ShellTag, withCwd as shellWithCwd } from \"./shell/shell.ts\";\n\n/**\n * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and\n * working directory they act on.\n *\n * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and\n * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and\n * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so\n * a host directory, an in-memory VFS, and a remote microVM are interchangeable\n * behind one contract.\n *\n * The mount neither creates nor destroys infrastructure. `SandboxInstance` is\n * the durable namespace it acts on — a device, which exists whether or not\n * anything has it mounted — and `Sandbox.Controller` is the only path that\n * creates, stops, or destroys one.\n */\n\n/**\n * The filesystem tag. Re-exported here so consumers import one namespace —\n * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for\n * the module that happens to define it. Code *inside* `sandbox/` keeps importing\n * the tag directly, since `io.ts` is built on top of it.\n */\nexport const FileSystem = SandboxFileSystem.Service;\nexport type FileSystem = SandboxFileSystem.Service;\n\n/** The shell tag. Re-exported here so consumers import one namespace. */\nexport const Shell = ShellTag;\nexport type Shell = ShellTag;\n\n/**\n * What a mount sees: immutable identity, plus the working directory resolved for\n * *this* mount.\n *\n * Nothing mutable belongs here. `status`, `usage`, and reference counts all\n * change while a mount is open, so a mount-time snapshot of them would be wrong\n * by construction — runtime code that needs live management state asks the\n * control plane. The driver's own resource locator is likewise absent: consumers\n * never parse a Vercel name or a Daytona id.\n */\nexport interface Identity {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: SandboxInstance.Kind;\n\t/** Absolute, and always a path in *this* namespace. */\n\treadonly cwd: string;\n}\n\n/** Identity and working directory of the current mount. */\nexport class Current extends Context.Service<Current, Identity>()(\"@codeworksh/harness/sandbox/io/Current\") {}\n\n/** Everything a mount provides. */\nexport type Provides = Current | SandboxFileSystem.Service | ShellTag;\n\n/** A built mount. */\nexport type Layer<E = never, RIn = never> = EffectLayer.Layer<Provides, E, RIn>;\n\n/**\n * Resolve a mount's cwd without consulting ambient process state.\n *\n * The default is supplied by the namespace adapter:\n * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.\n * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The\n * result is therefore always the one concrete absolute path `Current` requires.\n *\n * A non-absolute default throws rather than failing typed. It is the one\n * defect-level guard in this module, and deliberately so:\n * Adapters reading a value from a provider call this inside their own error channel,\n * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).\n */\nexport const resolveMountCwd = (defaultCwd: string, cwd?: string): string => {\n\tif (!posix.isAbsolute(defaultCwd)) {\n\t\tthrow new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);\n\t}\n\t// `resolve`, not `normalize`: normalize keeps a trailing slash, and `cwd` is\n\t// persisted — `space.location` and its id hash would read\n\t// `/workspace/` and `/workspace` as two directories and keep a row for each.\n\t//\n\t// A provider-reported default (`getWorkDir()`) or a config value is free to\n\t// carry one, so it is stripped here rather than at every reader.\n\tif (cwd === undefined) return posix.resolve(defaultCwd);\n\treturn posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);\n};\n\n/**\n * Bind a cwd-neutral transport to one mount.\n *\n * The transport underneath is shared between\n * mounts and stays rooted at the namespace root, and everything directory-shaped\n * happens here, once per mount. Two mounts of one namespace at different working\n * directories therefore coexist without seeing or moving each other's.\n *\n * It consumes the same two tags it provides — the transport is supplied by the\n * layer this is composed over, not by itself.\n */\nexport const mount = (identity: Identity): EffectLayer.Layer<Provides, never, SandboxFileSystem.Service | ShellTag> =>\n\tEffectLayer.mergeAll(\n\t\tEffectLayer.succeed(Current, identity),\n\t\tEffectLayer.effect(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tEffect.map(SandboxFileSystem.Service, (fs) => SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t),\n\t\tEffectLayer.effect(\n\t\t\tShellTag,\n\t\t\tEffect.map(ShellTag, (shell: ISandboxExe) => shellWithCwd(shell, identity.cwd)),\n\t\t),\n\t);\n\n/**\n * Just the identity tag, with no filesystem or shell beneath it. For consumers\n * assembled from stubs — a test that runs `Project` over a fake filesystem still\n * needs to know which namespace it is in.\n */\nexport const identityLayer = (identity: Identity) => EffectLayer.succeed(Current, identity);\n\n/** The host identity alone. See {@link identityLayer}. */\nexport const hostLayer = (cwd?: string) => identityLayer(host(cwd));\n\n/**\n * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working\n * directory selects where relative paths resolve, it does not make a second host\n * namespace — two mounts rooted at different directories still agree on absolute\n * paths.\n *\n * The host adapter defaults to `process.cwd()`, matching the OS process it wraps.\n * This is the one namespace where that coordinate is intrinsically valid; remote\n * and virtual adapters must never inherit it.\n */\nexport const host = (cwd?: string): Identity => ({\n\tid: SandboxInstance.ID.local,\n\tdriver: \"local\" as SandboxDriver.Name,\n\tkind: \"local\",\n\tcwd: resolveMountCwd(process.cwd(), cwd),\n});\n\n/**\n * A VFS-backed namespace. The id is minted per call unless one is named, because\n * building one of these builds a fresh VFS: N unnamed calls are N distinct\n * namespaces, none of which outlives the process. A file-backed store is the\n * exception — its file is the state, so whoever knows the file supplies the id\n * it was registered under.\n */\nexport const virtual = (input: {\n\treadonly driver: string;\n\treadonly id?: SandboxInstance.ID;\n\treadonly defaultCwd?: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id ?? SandboxInstance.ID.create(),\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"virtual\",\n\tcwd: resolveMountCwd(input.defaultCwd ?? \"/\", input.cwd),\n});\n\n/**\n * A provider-hosted namespace. The id is always supplied: a remote resource's\n * durable identity is minted and recorded by whoever provisioned it, never\n * derived here from the provider's own locator.\n */\nexport const remote = (input: {\n\treadonly driver: string;\n\treadonly id: SandboxInstance.ID;\n\t/** Namespace-intrinsic default supplied or discovered by the driver. */\n\treadonly defaultCwd: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id,\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"remote\",\n\tcwd: resolveMountCwd(input.defaultCwd, input.cwd),\n});\n\nexport * as SandboxIO from \"./io.ts\";\n","import { Effect, Encoding } from \"effect\";\nimport { crypto } from \"../host.ts\";\n\nconst encoder = new TextEncoder();\n\nexport function fast(input: string | Uint8Array): string {\n\tconst data = typeof input === \"string\" ? encoder.encode(input) : input;\n\treturn Encoding.encodeHex(Effect.runSync(crypto.digest(\"SHA-1\", data)));\n}\n\nexport function sha256(input: string | Uint8Array): string {\n\tconst data = typeof input === \"string\" ? encoder.encode(input) : input;\n\treturn Encoding.encodeHex(Effect.runSync(crypto.digest(\"SHA-256\", data)));\n}\nexport * as Hash from \"./hash.ts\";\n","import { Clock, Context, Effect, Layer, Option, Schema } from \"effect\";\nimport { SqlClient, SqlError, SqlSchema } from \"effect/unstable/sql\";\nimport { SpaceRow } from \"../db/schema.sql.ts\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport type { Sandbox } from \"../sandbox/sandbox.ts\";\nimport type { AbsolutePath } from \"../schema.ts\";\nimport { Hash } from \"../util/hash.ts\";\nimport { SpaceSchema } from \"./schema.ts\";\n\n/** `hash(env, location)` — no project component (D-SPACEID). */\nexport const id = (env: SandboxInstance.ID, location: string): SpaceSchema.ID =>\n\tSpaceSchema.ID.make(Hash.fast(JSON.stringify([SandboxInstance.toColumn(env) ?? \"local\", location])));\n\nexport interface RehomeInput {\n\treadonly id: SpaceSchema.ID;\n\treadonly projectId: ProjectSchema.ID;\n\treadonly location: AbsolutePath;\n\treadonly kind: SpaceSchema.Kind;\n\treadonly env: SandboxInstance.ID;\n}\n\nexport interface AbsorbInput {\n\treadonly strayId: SpaceSchema.ID;\n\treadonly into: SpaceSchema.ID;\n}\n\nexport interface Interface {\n\treadonly get: (id: SpaceSchema.ID) => Effect.Effect<Option.Option<SpaceSchema.Info>>;\n\t/** Active spaces of the project in this env, sorted by location. */\n\treadonly list: (projectId: ProjectSchema.ID) => Effect.Effect<SpaceSchema.Info[]>;\n\t/** Probe every space of the project in this env, archive/re-activate/promote (§5.4), then `list`. */\n\treadonly refresh: (projectId: ProjectSchema.ID) => Effect.Effect<SpaceSchema.Info[]>;\n\t/** Archive every space of an env; archive projects left without an active space (§5.5). */\n\treadonly archiveEnv: (env: SandboxInstance.ID) => Effect.Effect<void>;\n\t/** Upsert (§5.2). The only way resolve writes a space row. */\n\treadonly rehome: (input: RehomeInput) => Effect.Effect<void>;\n\t/** Re-point a stray subdirectory space's sessions at its parent, then delete it (§5.3). `session.directory` is absolute and stays put. */\n\treadonly absorb: (input: AbsorbInput) => Effect.Effect<void>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/space/space/Service\") {}\n\n/** Row → public shape. Shared with `Session.space`, which reads the same row through a join. */\nexport const fromRow = (row: SpaceRow): SpaceSchema.Info =>\n\tnew SpaceSchema.Info({\n\t\tid: SpaceSchema.ID.make(row.id),\n\t\tprojectId: ProjectSchema.ID.make(row.projectId),\n\t\tlocation: row.location,\n\t\tkind: row.kind,\n\t\tenv: SandboxInstance.fromField(row.env),\n\t\tstatus: row.status,\n\t});\n\n/**\n * Archive every space of an env, then every touched project left without an\n * active space in any env (§5.5). Requires only `SqlClient` so the sandbox\n * controller can run it inside its destroy tombstone transaction (D-ENV).\n * Write-first so a DEFERRED transaction takes the write lock immediately.\n */\nexport const archiveEnv = Effect.fn(\"Space.archiveEnv\")(function* (env: SandboxInstance.ID) {\n\tconst sql = yield* SqlClient.SqlClient;\n\tconst column = SandboxInstance.toColumn(env);\n\tconst now = yield* Clock.currentTimeMillis;\n\tyield* sql\n\t\t.withTransaction(\n\t\t\tEffect.gen(function* () {\n\t\t\t\tyield* sql`UPDATE space SET status = 'archived', updated_at = ${now} WHERE env IS ${column}`;\n\t\t\t\tyield* sql`\n\t\t\t\t\tUPDATE project SET status = 'archived', updated_at = ${now}\n\t\t\t\t\tWHERE id IN (SELECT project_id FROM space WHERE env IS ${column})\n\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM space WHERE space.project_id = project.id AND status = 'active')\n\t\t\t\t`;\n\t\t\t}),\n\t\t)\n\t\t.pipe(Effect.orDie);\n});\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\tconst { id: env } = yield* SandboxIO.Current;\n\t\t// NULL for the host; compared with `IS`, never `=`.\n\t\tconst envColumn = SandboxInstance.toColumn(env);\n\n\t\tconst findOne = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SpaceRow,\n\t\t\texecute: (id) => sql`SELECT * FROM space WHERE id = ${id}`,\n\t\t});\n\n\t\tconst findByProject = SqlSchema.findAll({\n\t\t\tRequest: Schema.Struct({ projectId: Schema.String, env: Schema.NullOr(Schema.String) }),\n\t\t\tResult: SpaceRow,\n\t\t\texecute: ({ projectId, env }) => sql`SELECT * FROM space WHERE project_id = ${projectId} AND env IS ${env}`,\n\t\t});\n\n\t\tconst insertSpace = SqlSchema.void({\n\t\t\tRequest: SpaceRow.insert,\n\t\t\texecute: (row) => sql`\n\t\t\t\tINSERT INTO space ${sql.insert(row)}\n\t\t\t\tON CONFLICT(id) DO UPDATE SET\n\t\t\t\t\tproject_id = excluded.project_id,\n\t\t\t\t\tkind = excluded.kind,\n\t\t\t\t\tstatus = 'active',\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t`,\n\t\t});\n\n\t\t// Projects with no active space in any env are archived, never deleted.\n\t\tconst archiveOrphanProjects = (projectIds: ReadonlyArray<string>, now: number) =>\n\t\t\tEffect.forEach(\n\t\t\t\tprojectIds,\n\t\t\t\t(projectId) => sql`\n\t\t\t\t\tUPDATE project SET status = 'archived', updated_at = ${now}\n\t\t\t\t\tWHERE id = ${projectId}\n\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM space WHERE project_id = ${projectId} AND status = 'active')\n\t\t\t\t`,\n\t\t\t\t{ discard: true },\n\t\t\t);\n\n\t\tconst get = Effect.fn(\"Space.get\")(function* (id: SpaceSchema.ID) {\n\t\t\treturn Option.map(yield* findOne(id).pipe(Effect.orDie), fromRow);\n\t\t});\n\n\t\tconst list = Effect.fn(\"Space.list\")(function* (projectId: ProjectSchema.ID) {\n\t\t\tconst rows = yield* findByProject({ projectId, env: envColumn }).pipe(Effect.orDie);\n\t\t\treturn rows\n\t\t\t\t.filter((row) => row.status === \"active\")\n\t\t\t\t.toSorted((a, b) => a.location.localeCompare(b.location))\n\t\t\t\t.map(fromRow);\n\t\t});\n\n\t\tconst refresh = Effect.fn(\"Space.refresh\")(function* (projectId: ProjectSchema.ID) {\n\t\t\tconst rows = yield* findByProject({ projectId, env: envColumn }).pipe(Effect.orDie);\n\n\t\t\t// Three-way: keep, gone, or unknown. Only a definitive \"absent\" archives;\n\t\t\t// a backend that could not answer leaves the row alone.\n\t\t\tconst probed = yield* Effect.forEach(\n\t\t\t\trows,\n\t\t\t\t(row) =>\n\t\t\t\t\tfs.exists(row.location).pipe(\n\t\t\t\t\t\tEffect.map((exists) => ({ row, gone: !exists })),\n\t\t\t\t\t\tEffect.orElseSucceed(() => ({ row, gone: false })),\n\t\t\t\t\t),\n\t\t\t\t{ concurrency: \"unbounded\" },\n\t\t\t);\n\t\t\tconst gone = probed.filter((entry) => entry.gone).map((entry) => entry.row.id);\n\t\t\tconst returned = probed\n\t\t\t\t.filter((entry) => !entry.gone && entry.row.status === \"archived\")\n\t\t\t\t.map((entry) => entry.row.id);\n\n\t\t\tconst now = yield* Clock.currentTimeMillis;\n\t\t\tyield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tif (gone.length > 0) {\n\t\t\t\t\t\t\tyield* sql`UPDATE space SET status = 'archived', updated_at = ${now} WHERE ${sql.in(\"id\", gone)}`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (returned.length > 0) {\n\t\t\t\t\t\t\tyield* sql`UPDATE space SET status = 'active', updated_at = ${now} WHERE ${sql.in(\"id\", returned)}`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst primary = yield* sql`\n\t\t\t\t\t\t\tSELECT id FROM space\n\t\t\t\t\t\t\tWHERE project_id = ${projectId} AND env IS ${envColumn} AND kind = 'primary' AND status = 'active'\n\t\t\t\t\t\t`;\n\t\t\t\t\t\tif (primary.length === 0) {\n\t\t\t\t\t\t\t// The unique index ignores status: demote the archived primary\n\t\t\t\t\t\t\t// before promoting. Only a copy qualifies — a linked worktree's\n\t\t\t\t\t\t\t// store died with the primary, and plain never needs one.\n\t\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\t\tUPDATE space SET kind = 'copy', updated_at = ${now}\n\t\t\t\t\t\t\t\tWHERE project_id = ${projectId} AND env IS ${envColumn} AND kind = 'primary'\n\t\t\t\t\t\t\t`;\n\t\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\t\tUPDATE space SET kind = 'primary', updated_at = ${now}\n\t\t\t\t\t\t\t\tWHERE id = (\n\t\t\t\t\t\t\t\t\tSELECT id FROM space\n\t\t\t\t\t\t\t\t\tWHERE project_id = ${projectId} AND env IS ${envColumn} AND status = 'active' AND kind = 'copy'\n\t\t\t\t\t\t\t\t\tORDER BY created_at ASC LIMIT 1\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tyield* archiveOrphanProjects([projectId], now);\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\treturn yield* list(projectId);\n\t\t});\n\n\t\tconst rehome = Effect.fn(\"Space.rehome\")(function* (input: RehomeInput) {\n\t\t\tconst write = (kind: SpaceSchema.Kind) =>\n\t\t\t\tSpaceRow.insert\n\t\t\t\t\t.makeEffect({\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tprojectId: input.projectId,\n\t\t\t\t\t\tlocation: input.location,\n\t\t\t\t\t\tkind,\n\t\t\t\t\t\tenv: SandboxInstance.toField(input.env),\n\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t})\n\t\t\t\t\t.pipe(Effect.flatMap(insertSpace));\n\n\t\t\t// A concurrent primary claim cannot happen under the resolve lock, but\n\t\t\t// the guard is cheap: the loser becomes a copy.\n\t\t\tyield* write(input.kind).pipe(\n\t\t\t\tEffect.catchIf(\n\t\t\t\t\t(error) =>\n\t\t\t\t\t\tinput.kind === \"primary\" &&\n\t\t\t\t\t\tSqlError.isSqlError(error) &&\n\t\t\t\t\t\terror.reason._tag === \"UniqueViolation\" &&\n\t\t\t\t\t\terror.reason.constraint.includes(\"space_primary_idx\"),\n\t\t\t\t\t() => write(\"copy\"),\n\t\t\t\t),\n\t\t\t\tEffect.orDie,\n\t\t\t);\n\t\t});\n\n\t\tconst absorb = Effect.fn(\"Space.absorb\")(function* (input: AbsorbInput) {\n\t\t\tyield* sql`UPDATE session SET space_id = ${input.into} WHERE space_id = ${input.strayId}`;\n\t\t\tyield* sql`DELETE FROM space WHERE id = ${input.strayId}`;\n\t\t}, Effect.orDie);\n\n\t\treturn Service.of({\n\t\t\tget,\n\t\t\tlist,\n\t\t\trefresh,\n\t\t\tarchiveEnv: (target) => archiveEnv(target).pipe(Effect.provideService(SqlClient.SqlClient, sql)),\n\t\t\trehome,\n\t\t\tabsorb,\n\t\t});\n\t}),\n);\n\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) => layer.pipe(Layer.provide(sandbox));\n\nexport * as Space from \"./space.ts\";\n","import { Context, DateTime, Effect, Layer, Option, Result, Schema } from \"effect\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { uuidv7 } from \"uuidv7\";\nimport { Database } from \"../db/db.ts\";\nimport {\n\ttype EntryState,\n\tentryStates,\n\ttype EntryType,\n\tentryTypes,\n\ttype MessageEntryType,\n\tmessageEntryTypes,\n\ttype PartType,\n\tpartTypes,\n\tSessionEntryPartRow,\n\tSessionEntryRow,\n\tSessionRow,\n\tSpaceRow,\n\ttype ToolStatus,\n\ttoolStatuses,\n} from \"../db/schema.sql.ts\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\nimport { SpaceSchema } from \"../space/schema.ts\";\nimport { Space } from \"../space/space.ts\";\nimport { posix } from \"../util/posix.ts\";\nimport { SessionSchema } from \"./schema.ts\";\n\nexport {\n\tentryStates,\n\tentryTypes,\n\tmessageEntryTypes,\n\tpartTypes,\n\tSessionEntryPartRow,\n\tSessionEntryRow,\n\tSessionRow,\n\ttoolStatuses,\n\ttype EntryState,\n\ttype EntryType,\n\ttype MessageEntryType,\n\ttype PartType,\n\ttype ToolStatus,\n};\n\nexport class SessionNotFoundError extends Schema.TaggedError<SessionNotFoundError>()(\"SessionNotFoundError\", {\n\tsessionId: Schema.String,\n}) {}\n\n// The session's space row is gone — unreachable while the FK holds, but typed\n// so a run surfaces it as a failure a UI can offer `relink` to repair.\nexport class SessionLinkedSpaceNotFoundError extends Schema.TaggedError<SessionLinkedSpaceNotFoundError>()(\n\t\"SessionLinkedSpaceNotFoundError\",\n\t{ sessionId: Schema.String },\n) {}\n\nexport class EntryNotFoundError extends Schema.TaggedError<EntryNotFoundError>()(\"EntryNotFoundError\", {\n\tsessionId: Schema.String,\n\tentryId: Schema.String,\n}) {}\n\nexport class ToolCallNotFoundError extends Schema.TaggedError<ToolCallNotFoundError>()(\"ToolCallNotFoundError\", {\n\tentryId: Schema.String,\n\tcallId: Schema.String,\n}) {}\n\n// Structural rejection — the data-structure layer's \"index out of bounds\".\nexport class InvalidEntryDataError extends Schema.TaggedError<InvalidEntryDataError>()(\"InvalidEntryDataError\", {\n\tentryId: Schema.String,\n\ttype: Schema.String,\n\treason: Schema.String,\n}) {}\n\n// Relink rejections: the target is not a live space, the session would cross\n// projects, or an explicit directory would break the containment invariant.\nexport class RelinkError extends Schema.TaggedError<RelinkError>()(\"RelinkError\", {\n\tsessionId: Schema.String,\n\tspaceId: Schema.String,\n\treason: Schema.Literals([\n\t\t\"space_not_found\",\n\t\t\"space_is_archived\",\n\t\t\"project_scope_mismatch\",\n\t\t\"directory_outside_space\",\n\t]),\n}) {}\nexport type RelinkReason = RelinkError[\"reason\"];\n\n// I6: a session's directory is its space's location or sits underneath it.\nconst directoryWithin = (location: AbsolutePath, directory: AbsolutePath) =>\n\tdirectory === location || directory.startsWith(`${location}/`);\n\n/**\n * Re-root a session directory onto another space of the same project: the\n * position relative to the old root is kept, so `dir = /old/app/pkg/x` under\n * `from = /old/app` lands on `/new/app/pkg/x` under `to = /new/app`. A\n * directory not under the old root — a broken invariant — lands on the new\n * root instead.\n */\nexport const rebaseDirectory = (from: AbsolutePath, to: AbsolutePath, directory: AbsolutePath): AbsolutePath => {\n\tif (!directoryWithin(from, directory)) return to;\n\tconst relative = posix.relative(from, directory);\n\treturn AbsolutePath.make(relative === \"\" ? to : posix.join(to, relative));\n};\n\nexport interface CreateSession {\n\treadonly id?: SessionSchema.ID;\n\t/** The space (one directory in one env) this session attaches to; must exist. */\n\treadonly spaceId: SpaceSchema.ID;\n\treadonly parentId?: SessionSchema.ID; // session hierarchy (subagents) or fork lineage\n\treadonly slug: string;\n\t/** Absolute realpath of the cwd; equal to or under `space.location`. */\n\treadonly directory: AbsolutePath;\n\treadonly title: string;\n\treadonly tag?: string;\n\treadonly metadata?: Readonly<Record<string, string>>;\n}\n\n/** Sessions of every space of a project, or of one space. */\nexport type ListInput = { readonly projectId: ProjectSchema.ID } | { readonly spaceId: SpaceSchema.ID };\n\nexport interface AppendPart {\n\treadonly id?: string; // uuidv7; generated when omitted\n\treadonly type: PartType;\n\treadonly status?: ToolStatus; // toolCall parts only\n\treadonly callId?: string; // toolCall parts only\n\treadonly toolName?: string; // toolCall parts only\n\treadonly data: string; // verbatim aikit part JSON\n}\n\nexport interface AppendEntry {\n\treadonly id: string; // uuidv7; == aikit messageId for message types\n\treadonly sessionId: SessionSchema.ID;\n\t/**\n\t * Position in the session's durable log — the sequence of the event that\n\t * produced this entry. Must exceed every existing entry's seq, which the\n\t * event log guarantees since sequences only ever advance.\n\t */\n\treadonly seq: number;\n\treadonly type: EntryType;\n\t/** Defaults to committed. Only LLMStarted inserts a draft. */\n\treadonly state?: EntryState;\n\treadonly data: string; // JSON: full payload, or message envelope\n\treadonly parts?: ReadonlyArray<AppendPart>; // order = partIndex; message types only\n\treadonly parentId?: string; // explicit branch appends only; default = current leaf\n\t/**\n\t * Publish-time context from the event that produced this entry. The log does\n\t * not store event metadata, so if it is to survive at all it survives here.\n\t */\n\treadonly metadata?: Readonly<Record<string, string>>;\n}\n\nexport interface SettleToolCall {\n\treadonly entryId: string; // owning assistant entry\n\treadonly callId: string; // from the loop's tool.execution.end\n\treadonly status: Exclude<ToolStatus, \"pending\" | \"running\">;\n\treadonly data: string; // settled aikit part JSON, verbatim\n}\n\nexport interface ReplaceAssistant {\n\treadonly id: string;\n\treadonly sessionId: SessionSchema.ID;\n\treadonly data: string;\n\treadonly parts: ReadonlyArray<AppendPart>;\n}\n\nexport interface SetEntryState {\n\treadonly id: string;\n\treadonly sessionId: SessionSchema.ID;\n\treadonly state: \"committed\";\n}\n\nexport interface AbortAssistant {\n\treadonly id: string;\n\treadonly sessionId: SessionSchema.ID;\n\t/** Encoded assistant stub. Parts are always deleted by the transition. */\n\treadonly data: string;\n}\n\n// Fork copies ONE path (root → fork point) into a new session — never sibling\n// or abandoned branches.\n// clone = fork at the current leaf.\nexport interface ForkInput {\n\treadonly sessionId: SessionSchema.ID; // source session\n\treadonly entryId?: string; // fork point; default = current leaf (clone)\n\treadonly mode?: \"at\" | \"before\"; // default \"at\"; \"before\" valid only for user entries\n\treadonly id?: SessionSchema.ID; // new session id; generated when omitted\n\treadonly slug: string; // required — slugs are unique\n\treadonly title?: string; // default: source title\n\treadonly tag?: string; // default: source tag\n}\n\n// The env move: point a session at another space of the same project (remote\n// env died, repo cloned locally, worktree consolidated). Transcript entries\n// are keyed by session id and are untouched.\nexport interface RelinkInput {\n\treadonly sessionId: SessionSchema.ID;\n\t/** Target space; must be active and belong to the session's project. */\n\treadonly spaceId: SpaceSchema.ID;\n\t/**\n\t * Landing directory; must equal or sit under the target space's location.\n\t * Default: `rebaseDirectory` of the current directory onto the new root.\n\t */\n\treadonly directory?: AbsolutePath;\n}\n\n// Entry row + its part rows, zipped. Message decode happens above this layer.\nexport interface HydratedEntry {\n\treadonly entry: SessionEntryRow;\n\treadonly parts: ReadonlyArray<SessionEntryPartRow>;\n}\n\nexport interface Interface {\n\treadonly create: (input: CreateSession) => Effect.Effect<SessionRow>;\n\treadonly get: (sessionId: SessionSchema.ID) => Effect.Effect<Option.Option<SessionRow>>;\n\t/** The space a session attaches to — its env and absolute location. None when the session is unknown. */\n\treadonly space: (sessionId: SessionSchema.ID) => Effect.Effect<Option.Option<SpaceSchema.Info>>;\n\t/** Sessions newest first, across the whole database when no scope is given. */\n\treadonly list: (input?: ListInput) => Effect.Effect<SessionRow[]>;\n\treadonly entry: (entryId: string) => Effect.Effect<Option.Option<HydratedEntry>>;\n\t/** Active root→leaf path with parts attached. */\n\treadonly path: (sessionId: SessionSchema.ID) => Effect.Effect<HydratedEntry[]>;\n\t/** All branches, newest-first, paged by entry seq. */\n\treadonly timeline: (input: {\n\t\tsessionId: SessionSchema.ID;\n\t\tcursorSeq?: number;\n\t\tlimit?: number;\n\t}) => Effect.Effect<HydratedEntry[]>;\n\t/** Unsettled toolCall parts (crash recovery / live status). */\n\treadonly unsettled: (sessionId: SessionSchema.ID) => Effect.Effect<SessionEntryPartRow[]>;\n\treadonly append: (\n\t\tinput: AppendEntry,\n\t) => Effect.Effect<SessionEntryRow, SessionNotFoundError | EntryNotFoundError | InvalidEntryDataError>;\n\t/** Projector-only: replace the payload of an existing draft assistant in place. */\n\treadonly replaceAssistant: (input: ReplaceAssistant) => Effect.Effect<void>;\n\t/** Projector-only: settle one pending/running tool part on a draft assistant. */\n\treadonly settleToolCall: (input: SettleToolCall) => Effect.Effect<void>;\n\t/** Projector-only: commit a draft after every tool part is terminal. */\n\treadonly setEntryState: (input: SetEntryState) => Effect.Effect<void>;\n\t/** Projector-only: turn a draft into a partless aborted tombstone. */\n\treadonly abortAssistant: (input: AbortAssistant) => Effect.Effect<void>;\n\t/** Copy root→fork-point into a new session (`parentId` = source). Clone = fork at leaf. */\n\treadonly fork: (\n\t\tinput: ForkInput,\n\t) => Effect.Effect<SessionRow, SessionNotFoundError | EntryNotFoundError | InvalidEntryDataError>;\n\t/**\n\t * Move the session to another space of the same project. Without an explicit\n\t * `directory` the cwd keeps its position relative to the old root; either way\n\t * the result satisfies I6 (directory at or under the space's location).\n\t */\n\treadonly relink: (input: RelinkInput) => Effect.Effect<SessionRow, SessionNotFoundError | RelinkError>;\n\t/** Move the leaf cursor; the next append forks a sibling branch. */\n\treadonly branch: (input: {\n\t\tsessionId: SessionSchema.ID;\n\t\tentryId: string;\n\t}) => Effect.Effect<void, EntryNotFoundError>;\n\t/** Set or clear (null) the bookmark label on an entry. */\n\treadonly setLabel: (input: {\n\t\tsessionId: SessionSchema.ID;\n\t\tentryId: string;\n\t\tlabel: string | null;\n\t}) => Effect.Effect<void, EntryNotFoundError>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/session/session/Service\") {}\n\nconst messageTypes: ReadonlySet<string> = new Set(messageEntryTypes);\n\n// Structural decode of the persisted envelope's usage; failures surface as\n// InvalidEntryDataError, never a defect — callers (Context Manager, UI) can act.\nconst decodeEnvelopeUsage = Schema.decodeUnknownEffect(SessionSchema.AssistantEnvelopeUsage);\nconst decodeMessageEnvelopeIdentity = Schema.decodeUnknownEffect(SessionSchema.MessageEnvelopeIdentity);\nconst decodeCompactionData = Schema.decodeUnknownEffect(SessionSchema.CompactionData);\nconst decodeJsonObject = Schema.decodeUnknownEffect(SessionSchema.JsonObject);\nconst encodeJsonObject = Schema.encodeEffect(SessionSchema.JsonObject);\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\t\tconst events = yield* Event.Service;\n\t\tconst findSession = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionRow,\n\t\t\texecute: (id) => sql`SELECT * FROM session WHERE id = ${id}`,\n\t\t});\n\n\t\tconst findSpace = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SpaceRow,\n\t\t\texecute: (sessionId) => sql`\n\t\t\t\tSELECT p.* FROM space p JOIN session s ON s.space_id = p.id WHERE s.id = ${sessionId}\n\t\t\t`,\n\t\t});\n\n\t\tconst findSpaceById = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SpaceRow,\n\t\t\texecute: (id) => sql`SELECT * FROM space WHERE id = ${id}`,\n\t\t});\n\n\t\tconst selectByProject = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionRow,\n\t\t\texecute: (projectId) => sql`\n\t\t\t\tSELECT s.* FROM session s\n\t\t\t\tJOIN space p ON p.id = s.space_id\n\t\t\t\tWHERE p.project_id = ${projectId}\n\t\t\t\tORDER BY s.updated_at DESC\n\t\t\t`,\n\t\t});\n\n\t\tconst selectBySpace = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionRow,\n\t\t\texecute: (spaceId) => sql`SELECT * FROM session WHERE space_id = ${spaceId} ORDER BY updated_at DESC`,\n\t\t});\n\n\t\tconst selectAll = SqlSchema.findAll({\n\t\t\tRequest: Schema.Void,\n\t\t\tResult: SessionRow,\n\t\t\texecute: () => sql`SELECT * FROM session ORDER BY updated_at DESC`,\n\t\t});\n\n\t\tconst insertSession = SqlSchema.void({\n\t\t\tRequest: SessionRow.insert,\n\t\t\texecute: (row) => sql`INSERT INTO session ${sql.insert(row)}`,\n\t\t});\n\n\t\tconst findEntry = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionEntryRow,\n\t\t\texecute: (id) => sql`SELECT * FROM session_entry WHERE id = ${id}`,\n\t\t});\n\n\t\t// seq is supplied by the caller, not computed here: it is the sequence of\n\t\t// the event that produced the entry, so the durable log and the tree share\n\t\t// one position space.\n\t\t//\n\t\t// The WHERE NOT EXISTS keeps positions strictly advancing. `max(seq) + 1`\n\t\t// used to make that structural; sourcing seq from outside would otherwise\n\t\t// downgrade it to an unchecked contract, and a stale position fails\n\t\t// silently — `selectPath` orders by seq, so a child would sort above its\n\t\t// own parent. Inserting zero rows is the signal, checked by the callers.\n\t\tconst insertEntry = SqlSchema.findAll({\n\t\t\tRequest: SessionEntryRow.insert,\n\t\t\tResult: Schema.Struct({ id: Schema.String }),\n\t\t\texecute: (row) => sql`\n\t\t\t\tINSERT INTO session_entry (id, session_id, parent_id, seq, type, state, data, label, metadata, created_at, updated_at)\n\t\t\t\tSELECT\n\t\t\t\t\t${row.id}, ${row.sessionId}, ${row.parentId ?? null}, ${row.seq},\n\t\t\t\t\t${row.type}, ${row.state}, ${row.data}, ${row.label ?? null}, ${row.metadata ?? null},\n\t\t\t\t\t${row.createdAt}, ${row.updatedAt}\n\t\t\t\tWHERE NOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM session_entry WHERE session_id = ${row.sessionId} AND seq >= ${row.seq}\n\t\t\t\t)\n\t\t\t\tRETURNING id\n\t\t\t`,\n\t\t});\n\n\t\t// Single-row insert: toolCall and non-tool parts have different encoded\n\t\t// key sets (FieldOption omits absent keys), so multi-row sql.insert would\n\t\t// mix shapes. Parts per message are few; sequential inserts inside the\n\t\t// append transaction are fine.\n\t\tconst insertPart = SqlSchema.void({\n\t\t\tRequest: SessionEntryPartRow.insert,\n\t\t\texecute: (row) => sql`INSERT INTO session_entry_part ${sql.insert(row)}`,\n\t\t});\n\n\t\t// Root→leaf in one query: a parent always exists before its child, so a\n\t\t// parent's seq is always smaller and ORDER BY seq returns root-first.\n\t\tconst selectPath = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionEntryRow,\n\t\t\texecute: (leafEntryId) => sql`\n\t\t\t\tWITH RECURSIVE path AS (\n\t\t\t\t\tSELECT * FROM session_entry WHERE id = ${leafEntryId}\n\t\t\t\t\tUNION ALL\n\t\t\t\t\tSELECT e.* FROM session_entry e\n\t\t\t\t\tJOIN path p ON e.id = p.parent_id AND e.session_id = p.session_id\n\t\t\t\t)\n\t\t\t\tSELECT * FROM path ORDER BY seq\n\t\t\t`,\n\t\t});\n\n\t\t// Recovery/import fallback when session.leaf_entry_id is NULL (§4.1).\n\t\tconst selectLatestEntry = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionEntryRow,\n\t\t\texecute: (sessionId) => sql`\n\t\t\t\tSELECT * FROM session_entry WHERE session_id = ${sessionId} ORDER BY seq DESC LIMIT 1\n\t\t\t`,\n\t\t});\n\n\t\tconst selectTimelinePage = SqlSchema.findAll({\n\t\t\tRequest: Schema.Struct({\n\t\t\t\tsessionId: Schema.String,\n\t\t\t\tcursorSeq: Schema.NullOr(Schema.Int),\n\t\t\t\tlimit: Schema.Int,\n\t\t\t}),\n\t\t\tResult: SessionEntryRow,\n\t\t\texecute: (r) => sql`\n\t\t\t\tSELECT * FROM session_entry\n\t\t\t\tWHERE session_id = ${r.sessionId} AND (${r.cursorSeq} IS NULL OR seq < ${r.cursorSeq})\n\t\t\t\tORDER BY seq DESC LIMIT ${r.limit}\n\t\t\t`,\n\t\t});\n\n\t\tconst selectPartsForEntries = SqlSchema.findAll({\n\t\t\tRequest: Schema.Array(Schema.String),\n\t\t\tResult: SessionEntryPartRow,\n\t\t\texecute: (entryIds) => sql`\n\t\t\t\tSELECT * FROM session_entry_part\n\t\t\t\tWHERE ${sql.in(\"entry_id\", entryIds)}\n\t\t\t\tORDER BY entry_id, part_index\n\t\t\t`,\n\t\t});\n\n\t\tconst selectUnsettled = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionEntryPartRow,\n\t\t\texecute: (sessionId) => sql`\n\t\t\t\tSELECT * FROM session_entry_part\n\t\t\t\tWHERE session_id = ${sessionId} AND status IN ('pending', 'running')\n\t\t\t\tORDER BY entry_id, part_index\n\t\t\t`,\n\t\t});\n\n\t\tconst epochNow = Effect.map(DateTime.now, DateTime.toEpochMillis);\n\n\t\t// Zip rule (§7.2): group parts by entry id, attach while walking entries.\n\t\t// entry.type says whether parts are expected; a mismatch is corruption,\n\t\t// not an edge case (§10.4).\n\t\tconst hydrate = (\n\t\t\tentries: ReadonlyArray<SessionEntryRow>,\n\t\t\tparts: ReadonlyArray<SessionEntryPartRow>,\n\t\t): HydratedEntry[] => {\n\t\t\tconst byEntry = new Map<string, SessionEntryPartRow[]>();\n\t\t\tfor (const part of parts) {\n\t\t\t\tconst bucket = byEntry.get(part.entryId);\n\t\t\t\tif (bucket) bucket.push(part);\n\t\t\t\telse byEntry.set(part.entryId, [part]);\n\t\t\t}\n\t\t\treturn entries.map((entry) => ({ entry, parts: byEntry.get(entry.id) ?? [] }));\n\t\t};\n\n\t\tconst partsFor = Effect.fnUntraced(function* (entries: ReadonlyArray<SessionEntryRow>) {\n\t\t\tconst ids = entries.filter((entry) => messageTypes.has(entry.type)).map((entry) => entry.id);\n\t\t\tif (ids.length === 0) return [];\n\t\t\treturn yield* selectPartsForEntries(ids).pipe(Effect.orDie);\n\t\t});\n\n\t\t// TODO(sanchitrk): auto generate slug not from input\n\t\tconst create = Effect.fn(\"Session.create\")(function* (input: CreateSession) {\n\t\t\tconst id = input.id ?? SessionSchema.ID.create();\n\t\t\tconst row = yield* SessionRow.insert\n\t\t\t\t.makeEffect({\n\t\t\t\t\tid,\n\t\t\t\t\tspaceId: input.spaceId,\n\t\t\t\t\tparentId: Option.fromUndefinedOr(input.parentId),\n\t\t\t\t\tslug: input.slug,\n\t\t\t\t\tdirectory: input.directory,\n\t\t\t\t\ttitle: input.title,\n\t\t\t\t\ttag: Option.fromUndefinedOr(input.tag),\n\t\t\t\t\tmetadata: Option.fromUndefinedOr(input.metadata as Record<string, string> | undefined),\n\t\t\t\t\tleafEntryId: Option.none(),\n\t\t\t\t})\n\t\t\t\t.pipe(Effect.orDie);\n\t\t\tyield* insertSession(row).pipe(Effect.orDie);\n\t\t\tconst created = yield* findSession(id).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(created)) {\n\t\t\t\treturn yield* Effect.die(new Error(\"session insert did not persist\"));\n\t\t\t}\n\t\t\treturn created.value;\n\t\t});\n\n\t\tconst get = Effect.fn(\"Session.get\")(function* (sessionId: string) {\n\t\t\treturn yield* findSession(sessionId).pipe(Effect.orDie);\n\t\t});\n\n\t\tconst space = Effect.fn(\"Session.space\")(function* (sessionId: string) {\n\t\t\treturn Option.map(yield* findSpace(sessionId).pipe(Effect.orDie), Space.fromRow);\n\t\t});\n\n\t\tconst list = Effect.fn(\"Session.list\")(function* (input?: ListInput) {\n\t\t\tconst rows =\n\t\t\t\tinput === undefined\n\t\t\t\t\t? selectAll()\n\t\t\t\t\t: \"spaceId\" in input\n\t\t\t\t\t\t? selectBySpace(input.spaceId)\n\t\t\t\t\t\t: selectByProject(input.projectId);\n\t\t\treturn yield* rows.pipe(Effect.orDie);\n\t\t});\n\n\t\tconst entry = Effect.fn(\"Session.entry\")(function* (entryId: string) {\n\t\t\tconst found = yield* findEntry(entryId).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(found)) return Option.none<HydratedEntry>();\n\t\t\tconst parts = yield* partsFor([found.value]);\n\t\t\treturn Option.some(hydrate([found.value], parts)[0]!);\n\t\t});\n\n\t\tconst resolveLeaf = Effect.fnUntraced(function* (session: SessionRow) {\n\t\t\tif (Option.isSome(session.leafEntryId)) return session.leafEntryId;\n\t\t\tconst latest = yield* selectLatestEntry(session.id).pipe(Effect.orDie);\n\t\t\treturn Option.map(latest, (row) => row.id);\n\t\t});\n\n\t\tconst path = Effect.fn(\"Session.path\")(function* (sessionId: string) {\n\t\t\tconst session = yield* findSession(sessionId).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(session)) return [];\n\t\t\tconst leaf = yield* resolveLeaf(session.value);\n\t\t\tif (Option.isNone(leaf)) return [];\n\t\t\tconst entries = yield* selectPath(leaf.value).pipe(Effect.orDie);\n\t\t\tconst parts = yield* partsFor(entries);\n\t\t\treturn hydrate(entries, parts);\n\t\t});\n\n\t\tconst timeline = Effect.fn(\"Session.timeline\")(function* (input: {\n\t\t\tsessionId: string;\n\t\t\tcursorSeq?: number;\n\t\t\tlimit?: number;\n\t\t}) {\n\t\t\tconst entries = yield* selectTimelinePage({\n\t\t\t\tsessionId: input.sessionId,\n\t\t\t\tcursorSeq: input.cursorSeq ?? null,\n\t\t\t\tlimit: input.limit ?? 50,\n\t\t\t}).pipe(Effect.orDie);\n\t\t\tconst parts = yield* partsFor(entries);\n\t\t\treturn hydrate(entries, parts);\n\t\t});\n\n\t\tconst unsettled = Effect.fn(\"Session.unsettled\")(function* (sessionId: string) {\n\t\t\treturn yield* selectUnsettled(sessionId).pipe(Effect.orDie);\n\t\t});\n\n\t\ttype AppendTxResult =\n\t\t\t| { readonly _tag: \"sessionNotFound\" }\n\t\t\t| { readonly _tag: \"parentNotFound\" }\n\t\t\t| { readonly _tag: \"invalidData\"; readonly reason: string }\n\t\t\t| { readonly _tag: \"inserted\"; readonly entry: SessionEntryRow };\n\n\t\tconst append = Effect.fn(\"Session.append\")(function* (input: AppendEntry) {\n\t\t\tconst parts = input.parts ?? [];\n\t\t\tconst state = input.state ?? \"committed\";\n\t\t\tif (state === \"aborted\" || (input.type !== \"assistant\" && state !== \"committed\")) {\n\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\tentryId: input.id,\n\t\t\t\t\ttype: input.type,\n\t\t\t\t\treason:\n\t\t\t\t\t\tstate === \"aborted\"\n\t\t\t\t\t\t\t? \"an aborted assistant must be produced by abortAssistant\"\n\t\t\t\t\t\t\t: `entry type \"${input.type}\" must be committed`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (parts.length > 0 && !messageTypes.has(input.type)) {\n\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\tentryId: input.id,\n\t\t\t\t\ttype: input.type,\n\t\t\t\t\treason: `entry type \"${input.type}\" must not carry parts`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Part data is documented as verbatim aikit JSON and every reader parses\n\t\t\t// it as such, so it is validated here for the same reason the envelope\n\t\t\t// is: an unparseable part is only discovered by whoever reads it back,\n\t\t\t// long after the write that could have rejected it.\n\t\t\tfor (const [index, part] of parts.entries()) {\n\t\t\t\tyield* decodeJsonObject(part.data).pipe(\n\t\t\t\t\tEffect.mapError(\n\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\tnew InvalidEntryDataError({\n\t\t\t\t\t\t\t\tentryId: input.id,\n\t\t\t\t\t\t\t\ttype: input.type,\n\t\t\t\t\t\t\t\treason: `part ${index} (\"${part.type}\") is not a JSON object: ${error.message}`,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst envelopeIdentity = messageTypes.has(input.type)\n\t\t\t\t? yield* decodeMessageEnvelopeIdentity(input.data).pipe(\n\t\t\t\t\t\tEffect.mapError(\n\t\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\t\tnew InvalidEntryDataError({ entryId: input.id, type: input.type, reason: error.message }),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tif (envelopeIdentity !== undefined && envelopeIdentity.messageId !== input.id) {\n\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\tentryId: input.id,\n\t\t\t\t\ttype: input.type,\n\t\t\t\t\treason: `messageId \"${envelopeIdentity.messageId}\" does not match entry id`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst compaction =\n\t\t\t\tinput.type === \"compaction\"\n\t\t\t\t\t? yield* decodeCompactionData(input.data).pipe(\n\t\t\t\t\t\t\tEffect.mapError(\n\t\t\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\t\t\tnew InvalidEntryDataError({ entryId: input.id, type: input.type, reason: error.message }),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\n\t\t\t// The envelope is authoritative; aggregate deltas are never accepted\n\t\t\t// independently of the data persisted by this transaction.\n\t\t\tconst usage =\n\t\t\t\tinput.type === \"assistant\"\n\t\t\t\t\t? yield* decodeEnvelopeUsage(input.data).pipe(\n\t\t\t\t\t\t\tEffect.map((envelope) => envelope.usage),\n\t\t\t\t\t\t\tEffect.mapError(\n\t\t\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\t\t\tnew InvalidEntryDataError({ entryId: input.id, type: input.type, reason: error.message }),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\n\t\t\tconst result: AppendTxResult = yield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst session = yield* findSession(input.sessionId);\n\t\t\t\t\t\tif (Option.isNone(session)) return { _tag: \"sessionNotFound\" } as const;\n\t\t\t\t\t\tconst currentLeaf = yield* resolveLeaf(session.value);\n\n\t\t\t\t\t\t// Append anchor: explicit branch target\n\t\t\t\t\t\t// (validated same-session; the composite FK is the schema backstop),\n\t\t\t\t\t\t// else the current leaf resolved with the same fallback reads use (§4.1).\n\t\t\t\t\t\tlet parentId: Option.Option<string>;\n\t\t\t\t\t\tif (input.parentId !== undefined) {\n\t\t\t\t\t\t\tconst rows = yield* sql`\n\t\t\t\t\t\t\t\tSELECT id FROM session_entry\n\t\t\t\t\t\t\t\tWHERE id = ${input.parentId} AND session_id = ${input.sessionId}\n\t\t\t\t\t\t\t`;\n\t\t\t\t\t\t\tif (rows.length === 0) return { _tag: \"parentNotFound\" } as const;\n\t\t\t\t\t\t\tparentId = Option.some(input.parentId);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tparentId = currentLeaf;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (compaction !== undefined && compaction.firstKeptEntryId !== null) {\n\t\t\t\t\t\t\tif (Option.isNone(parentId)) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t_tag: \"invalidData\",\n\t\t\t\t\t\t\t\t\treason: `firstKeptEntryId \"${compaction.firstKeptEntryId}\" is not on the compaction path`,\n\t\t\t\t\t\t\t\t} as const;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst compactionPath = yield* selectPath(parentId.value);\n\t\t\t\t\t\t\tif (!compactionPath.some((entry) => entry.id === compaction.firstKeptEntryId)) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t_tag: \"invalidData\",\n\t\t\t\t\t\t\t\t\treason: `firstKeptEntryId \"${compaction.firstKeptEntryId}\" is not on the compaction path`,\n\t\t\t\t\t\t\t\t} as const;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entryRow = yield* SessionEntryRow.insert.makeEffect({\n\t\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\t\tsessionId: input.sessionId,\n\t\t\t\t\t\t\tparentId,\n\t\t\t\t\t\t\tseq: input.seq,\n\t\t\t\t\t\t\ttype: input.type,\n\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\tdata: input.data,\n\t\t\t\t\t\t\tlabel: Option.none(),\n\t\t\t\t\t\t\tmetadata: Option.fromUndefinedOr(input.metadata),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst inserted = yield* insertEntry(entryRow);\n\t\t\t\t\t\t// Keep the aggregate head above what was just written. An entry\n\t\t\t\t\t\t// that arrived without an event still occupies its position, and\n\t\t\t\t\t\t// the next event must land above it or hit the guard below\n\t\t\t\t\t\t// forever.\n\t\t\t\t\t\tyield* events.advance(input.sessionId, input.seq);\n\t\t\t\t\t\tif (inserted.length === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t_tag: \"invalidData\",\n\t\t\t\t\t\t\t\treason: `seq ${input.seq} does not advance past the session's latest entry`,\n\t\t\t\t\t\t\t} as const;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const [partIndex, part] of parts.entries()) {\n\t\t\t\t\t\t\tconst partRow = yield* SessionEntryPartRow.insert.makeEffect({\n\t\t\t\t\t\t\t\tid: part.id ?? uuidv7(),\n\t\t\t\t\t\t\t\tentryId: input.id,\n\t\t\t\t\t\t\t\tsessionId: input.sessionId,\n\t\t\t\t\t\t\t\tpartIndex,\n\t\t\t\t\t\t\t\ttype: part.type,\n\t\t\t\t\t\t\t\tstatus: Option.fromUndefinedOr(part.status),\n\t\t\t\t\t\t\t\tcallId: Option.fromUndefinedOr(part.callId),\n\t\t\t\t\t\t\t\ttoolName: Option.fromUndefinedOr(part.toolName),\n\t\t\t\t\t\t\t\tdata: part.data,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tyield* insertPart(partRow);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Advance the cursor and account for the envelope currently stored.\n\t\t\t\t\t\t// Draft assistants are adjusted by replace/abort when their terminal\n\t\t\t\t\t\t// envelope arrives.\n\t\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session SET\n\t\t\t\t\t\t\t\tleaf_entry_id = ${input.id},\n\t\t\t\t\t\t\t\tupdated_at = ${now},\n\t\t\t\t\t\t\t\tcost = cost + ${usage?.cost.total ?? 0},\n\t\t\t\t\t\t\t\ttokens_input = tokens_input + ${usage?.input ?? 0},\n\t\t\t\t\t\t\t\ttokens_output = tokens_output + ${usage?.output ?? 0},\n\t\t\t\t\t\t\t\ttokens_cache_read = tokens_cache_read + ${usage?.cacheRead ?? 0},\n\t\t\t\t\t\t\t\ttokens_cache_write = tokens_cache_write + ${usage?.cacheWrite ?? 0}\n\t\t\t\t\t\t\tWHERE id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\n\t\t\t\t\t\tconst entry = yield* findEntry(input.id);\n\t\t\t\t\t\tif (Option.isNone(entry)) {\n\t\t\t\t\t\t\treturn yield* Effect.die(new Error(\"session append: inserted entry did not persist\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { _tag: \"inserted\", entry: entry.value } as const;\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\tswitch (result._tag) {\n\t\t\t\tcase \"sessionNotFound\":\n\t\t\t\t\treturn yield* new SessionNotFoundError({ sessionId: input.sessionId });\n\t\t\t\tcase \"parentNotFound\":\n\t\t\t\t\treturn yield* new EntryNotFoundError({ sessionId: input.sessionId, entryId: input.parentId ?? \"\" });\n\t\t\t\tcase \"invalidData\":\n\t\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\t\tentryId: input.id,\n\t\t\t\t\t\ttype: input.type,\n\t\t\t\t\t\treason: result.reason,\n\t\t\t\t\t});\n\t\t\t\tcase \"inserted\":\n\t\t\t\t\treturn result.entry;\n\t\t\t}\n\t\t});\n\n\t\tconst replaceAssistant = Effect.fn(\"Session.replaceAssistant\")(function* (input: ReplaceAssistant) {\n\t\t\tconst nextEnvelope = yield* decodeEnvelopeUsage(input.data);\n\t\t\tyield* sql.withTransaction(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst current = yield* findEntry(input.id);\n\t\t\t\t\tif (\n\t\t\t\t\t\tOption.isNone(current) ||\n\t\t\t\t\t\tcurrent.value.sessionId !== input.sessionId ||\n\t\t\t\t\t\tcurrent.value.type !== \"assistant\" ||\n\t\t\t\t\t\tcurrent.value.state !== \"draft\"\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn yield* Effect.die(`replaceAssistant requires draft assistant ${input.id}`);\n\t\t\t\t\t}\n\t\t\t\t\tconst previousEnvelope = yield* decodeEnvelopeUsage(current.value.data);\n\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\tyield* sql`DELETE FROM session_entry_part WHERE entry_id = ${input.id}`;\n\t\t\t\t\tfor (const [partIndex, part] of input.parts.entries()) {\n\t\t\t\t\t\tconst partRow = yield* SessionEntryPartRow.insert.makeEffect({\n\t\t\t\t\t\t\tid: part.id ?? uuidv7(),\n\t\t\t\t\t\t\tentryId: input.id,\n\t\t\t\t\t\t\tsessionId: input.sessionId,\n\t\t\t\t\t\t\tpartIndex,\n\t\t\t\t\t\t\ttype: part.type,\n\t\t\t\t\t\t\tstatus: Option.fromUndefinedOr(part.status),\n\t\t\t\t\t\t\tcallId: Option.fromUndefinedOr(part.callId),\n\t\t\t\t\t\t\ttoolName: Option.fromUndefinedOr(part.toolName),\n\t\t\t\t\t\t\tdata: part.data,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tyield* insertPart(partRow);\n\t\t\t\t\t}\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session_entry SET data = ${input.data}, updated_at = ${now}\n\t\t\t\t\t\t\tWHERE id = ${input.id} AND session_id = ${input.sessionId} AND state = 'draft'\n\t\t\t\t\t\t`;\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session SET\n\t\t\t\t\t\t\t\tupdated_at = ${now},\n\t\t\t\t\t\t\t\tcost = cost + ${nextEnvelope.usage.cost.total - previousEnvelope.usage.cost.total},\n\t\t\t\t\t\t\t\ttokens_input = tokens_input + ${nextEnvelope.usage.input - previousEnvelope.usage.input},\n\t\t\t\t\t\t\t\ttokens_output = tokens_output + ${nextEnvelope.usage.output - previousEnvelope.usage.output},\n\t\t\t\t\t\t\t\ttokens_cache_read = tokens_cache_read + ${nextEnvelope.usage.cacheRead - previousEnvelope.usage.cacheRead},\n\t\t\t\t\t\t\t\ttokens_cache_write = tokens_cache_write + ${nextEnvelope.usage.cacheWrite - previousEnvelope.usage.cacheWrite}\n\t\t\t\t\t\t\tWHERE id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\t\t\t\t}),\n\t\t\t);\n\t\t}, Effect.orDie);\n\n\t\tconst settleToolCall = Effect.fn(\"Session.settleToolCall\")(function* (input: SettleToolCall) {\n\t\t\tconst data = yield* decodeJsonObject(input.data).pipe(Effect.orDie);\n\t\t\tif (data[\"type\"] !== \"toolCall\" || data[\"callID\"] !== input.callId || data[\"status\"] !== input.status) {\n\t\t\t\treturn yield* Effect.die(`settled tool payload does not match call ${input.callId}`);\n\t\t\t}\n\t\t\tconst now = yield* epochNow;\n\t\t\tconst rows = yield* sql`\n\t\t\t\tUPDATE session_entry_part\n\t\t\t\tSET data = ${input.data}, status = ${input.status}, updated_at = ${now}\n\t\t\t\tWHERE entry_id = ${input.entryId}\n\t\t\t\t\tAND call_id = ${input.callId}\n\t\t\t\t\tAND type = 'toolCall'\n\t\t\t\t\tAND status IN ('pending', 'running')\n\t\t\t\t\tAND EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM session_entry\n\t\t\t\t\t\tWHERE id = ${input.entryId} AND state = 'draft'\n\t\t\t\t\t)\n\t\t\t\tRETURNING id\n\t\t\t`;\n\t\t\tif (rows.length !== 1) {\n\t\t\t\treturn yield* Effect.die(`settleToolCall requires one unsettled call ${input.entryId}/${input.callId}`);\n\t\t\t}\n\t\t}, Effect.orDie);\n\n\t\tconst setEntryState = Effect.fn(\"Session.setEntryState\")(function* (input: SetEntryState) {\n\t\t\tconst now = yield* epochNow;\n\t\t\tconst rows = yield* sql`\n\t\t\t\tUPDATE session_entry SET state = ${input.state}, updated_at = ${now}\n\t\t\t\tWHERE id = ${input.id}\n\t\t\t\t\tAND session_id = ${input.sessionId}\n\t\t\t\t\tAND type = 'assistant'\n\t\t\t\t\tAND state = 'draft'\n\t\t\t\t\tAND NOT EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM session_entry_part\n\t\t\t\t\t\tWHERE entry_id = ${input.id} AND status IN ('pending', 'running')\n\t\t\t\t\t)\n\t\t\t\tRETURNING id\n\t\t\t`;\n\t\t\tif (rows.length !== 1) return yield* Effect.die(`setEntryState requires a fully-settled draft ${input.id}`);\n\t\t}, Effect.orDie);\n\n\t\tconst abortAssistant = Effect.fn(\"Session.abortAssistant\")(function* (input: AbortAssistant) {\n\t\t\tconst nextEnvelope = yield* decodeEnvelopeUsage(input.data);\n\t\t\tyield* sql.withTransaction(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst current = yield* findEntry(input.id);\n\t\t\t\t\tif (\n\t\t\t\t\t\tOption.isNone(current) ||\n\t\t\t\t\t\tcurrent.value.sessionId !== input.sessionId ||\n\t\t\t\t\t\tcurrent.value.type !== \"assistant\" ||\n\t\t\t\t\t\tcurrent.value.state !== \"draft\"\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn yield* Effect.die(`abortAssistant requires draft assistant ${input.id}`);\n\t\t\t\t\t}\n\t\t\t\t\tconst previousEnvelope = yield* decodeEnvelopeUsage(current.value.data);\n\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\tyield* sql`DELETE FROM session_entry_part WHERE entry_id = ${input.id}`;\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session_entry\n\t\t\t\t\t\t\tSET state = 'aborted', data = ${input.data}, updated_at = ${now}\n\t\t\t\t\t\t\tWHERE id = ${input.id} AND session_id = ${input.sessionId} AND state = 'draft'\n\t\t\t\t\t\t`;\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session SET\n\t\t\t\t\t\t\t\tupdated_at = ${now},\n\t\t\t\t\t\t\t\tcost = cost + ${nextEnvelope.usage.cost.total - previousEnvelope.usage.cost.total},\n\t\t\t\t\t\t\t\ttokens_input = tokens_input + ${nextEnvelope.usage.input - previousEnvelope.usage.input},\n\t\t\t\t\t\t\t\ttokens_output = tokens_output + ${nextEnvelope.usage.output - previousEnvelope.usage.output},\n\t\t\t\t\t\t\t\ttokens_cache_read = tokens_cache_read + ${nextEnvelope.usage.cacheRead - previousEnvelope.usage.cacheRead},\n\t\t\t\t\t\t\t\ttokens_cache_write = tokens_cache_write + ${nextEnvelope.usage.cacheWrite - previousEnvelope.usage.cacheWrite}\n\t\t\t\t\t\t\tWHERE id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\t\t\t\t}),\n\t\t\t);\n\t\t}, Effect.orDie);\n\n\t\ttype ForkTxResult =\n\t\t\t| { readonly _tag: \"sessionNotFound\" }\n\t\t\t| { readonly _tag: \"entryNotFound\"; readonly entryId: string }\n\t\t\t| { readonly _tag: \"invalidMode\"; readonly entryId: string; readonly type: string }\n\t\t\t| { readonly _tag: \"invalidData\"; readonly entryId: string; readonly type: string; readonly reason: string }\n\t\t\t| { readonly _tag: \"forked\"; readonly session: SessionRow };\n\n\t\t// Copied entries get NEW ids (ours are globally unique),\n\t\t// so every entry-id reference on the path is remapped:\n\t\t// parent edges, message envelopes' messageId, and compaction's\n\t\t// `firstKeptEntryId` (when non-null, always on the copied path and mappable).\n\t\t// branchSummary.fromEntryId is NOT remapped — it points at an abandoned\n\t\t// leaf that is deliberately not copied;\n\t\tconst rewriteForkedData = Effect.fnUntraced(function* (\n\t\t\tentry: SessionEntryRow,\n\t\t\tnewId: string,\n\t\t\tidMap: ReadonlyMap<string, string>,\n\t\t) {\n\t\t\tif (!messageTypes.has(entry.type) && entry.type !== \"compaction\") return entry.data;\n\t\t\tconst invalidData = (reason: string) =>\n\t\t\t\tnew InvalidEntryDataError({ entryId: entry.id, type: entry.type, reason });\n\t\t\tconst payload: Record<string, unknown> = {\n\t\t\t\t...(yield* decodeJsonObject(entry.data).pipe(Effect.mapError((error) => invalidData(error.message)))),\n\t\t\t};\n\t\t\tif (messageTypes.has(entry.type)) {\n\t\t\t\tconst identity = yield* decodeMessageEnvelopeIdentity(entry.data).pipe(\n\t\t\t\t\tEffect.mapError((error) => invalidData(error.message)),\n\t\t\t\t);\n\t\t\t\tif (identity.messageId !== entry.id) {\n\t\t\t\t\treturn yield* invalidData(`messageId \"${identity.messageId}\" does not match entry id`);\n\t\t\t\t}\n\t\t\t\tpayload[\"messageId\"] = newId;\n\t\t\t}\n\t\t\tif (entry.type === \"compaction\") {\n\t\t\t\tconst compaction = yield* decodeCompactionData(entry.data).pipe(\n\t\t\t\t\tEffect.mapError((error) => invalidData(error.message)),\n\t\t\t\t);\n\t\t\t\tif (compaction.firstKeptEntryId !== null) {\n\t\t\t\t\tconst mapped = idMap.get(compaction.firstKeptEntryId);\n\t\t\t\t\tif (mapped === undefined) {\n\t\t\t\t\t\treturn yield* invalidData(\n\t\t\t\t\t\t\t`firstKeptEntryId \"${compaction.firstKeptEntryId}\" is not on the copied path`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tpayload[\"firstKeptEntryId\"] = mapped;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn yield* encodeJsonObject(payload).pipe(Effect.mapError((error) => invalidData(error.message)));\n\t\t});\n\n\t\tconst fork = Effect.fn(\"Session.fork\")(function* (input: ForkInput) {\n\t\t\tconst mode = input.mode ?? \"at\";\n\t\t\tconst newSessionId = input.id ?? SessionSchema.ID.create();\n\n\t\t\tconst result: ForkTxResult = yield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst source = yield* findSession(input.sessionId);\n\t\t\t\t\t\tif (Option.isNone(source)) return { _tag: \"sessionNotFound\" } as const;\n\n\t\t\t\t\t\t// Resolve the fork-point entry: explicit (validated in-session)\n\t\t\t\t\t\t// or the current leaf (clone). None = empty source.\n\t\t\t\t\t\tlet targetEntry: Option.Option<SessionEntryRow>;\n\t\t\t\t\t\tif (input.entryId !== undefined) {\n\t\t\t\t\t\t\tconst found = yield* findEntry(input.entryId);\n\t\t\t\t\t\t\tif (Option.isNone(found) || found.value.sessionId !== input.sessionId) {\n\t\t\t\t\t\t\t\treturn { _tag: \"entryNotFound\", entryId: input.entryId } as const;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttargetEntry = found;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst leaf = yield* resolveLeaf(source.value);\n\t\t\t\t\t\t\ttargetEntry = Option.isNone(leaf) ? Option.none() : yield* findEntry(leaf.value);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// mode \"before\": land just above a user prompt so the caller can\n\t\t\t\t\t\t// re-edit and resubmit it in the fork. Parent may be none (root prompt) — that yields an empty fork.\n\t\t\t\t\t\tlet targetId: Option.Option<string>;\n\t\t\t\t\t\tif (Option.isSome(targetEntry) && mode === \"before\") {\n\t\t\t\t\t\t\tif (targetEntry.value.type !== \"user\") {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t_tag: \"invalidMode\",\n\t\t\t\t\t\t\t\t\tentryId: targetEntry.value.id,\n\t\t\t\t\t\t\t\t\ttype: targetEntry.value.type,\n\t\t\t\t\t\t\t\t} as const;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttargetId = targetEntry.value.parentId;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttargetId = Option.map(targetEntry, (entry) => entry.id);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst pathEntries = Option.isSome(targetId) ? yield* selectPath(targetId.value) : [];\n\t\t\t\t\t\tconst idMap = new Map(pathEntries.map((entry) => [entry.id, uuidv7()]));\n\n\t\t\t\t\t\t// Prepare the complete copy before the first write. Returning a tagged\n\t\t\t\t\t\t// validation error after an insert would otherwise commit a partial fork.\n\t\t\t\t\t\tconst prepared = yield* Effect.result(\n\t\t\t\t\t\t\tEffect.forEach(pathEntries, (entry) => {\n\t\t\t\t\t\t\t\tconst id = idMap.get(entry.id)!;\n\t\t\t\t\t\t\t\treturn rewriteForkedData(entry, id, idMap).pipe(\n\t\t\t\t\t\t\t\t\tEffect.map((data) => ({ source: entry, id, data })),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (Result.isFailure(prepared)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t_tag: \"invalidData\",\n\t\t\t\t\t\t\t\tentryId: prepared.failure.entryId,\n\t\t\t\t\t\t\t\ttype: prepared.failure.type,\n\t\t\t\t\t\t\t\treason: prepared.failure.reason,\n\t\t\t\t\t\t\t} as const;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst preparedEntries = prepared.success;\n\n\t\t\t\t\t\t// New session first (prepared entries FK it); leaf set after the copy.\n\t\t\t\t\t\t// Aggregates start at 0 — spend stays recorded in the source.\n\t\t\t\t\t\tconst sessionRow = yield* SessionRow.insert.makeEffect({\n\t\t\t\t\t\t\tid: newSessionId,\n\t\t\t\t\t\t\t// Same space and directory as the source, so the same env and cwd.\n\t\t\t\t\t\t\tspaceId: source.value.spaceId,\n\t\t\t\t\t\t\tparentId: Option.some(source.value.id), // fork lineage\n\t\t\t\t\t\t\tslug: input.slug,\n\t\t\t\t\t\t\tdirectory: source.value.directory,\n\t\t\t\t\t\t\ttitle: input.title ?? source.value.title,\n\t\t\t\t\t\t\ttag: input.tag === undefined ? source.value.tag : Option.some(input.tag),\n\t\t\t\t\t\t\tmetadata: source.value.metadata,\n\t\t\t\t\t\t\tleafEntryId: Option.none(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tyield* insertSession(sessionRow);\n\n\t\t\t\t\t\t// Positions are carried over verbatim, not renumbered: they are log\n\t\t\t\t\t\t// positions, and preserving them keeps the copy ordered exactly as\n\t\t\t\t\t\t// the source. The new aggregate is then seeded above the highest of\n\t\t\t\t\t\t// them so post-fork events never land underneath.\n\t\t\t\t\t\tfor (const prepared of preparedEntries) {\n\t\t\t\t\t\t\tconst entryRow = yield* SessionEntryRow.insert.makeEffect({\n\t\t\t\t\t\t\t\tid: prepared.id,\n\t\t\t\t\t\t\t\tsessionId: newSessionId,\n\t\t\t\t\t\t\t\tparentId: Option.map(prepared.source.parentId, (parent) => idMap.get(parent)!),\n\t\t\t\t\t\t\t\tseq: prepared.source.seq,\n\t\t\t\t\t\t\t\ttype: prepared.source.type,\n\t\t\t\t\t\t\t\tstate: prepared.source.state,\n\t\t\t\t\t\t\t\tdata: prepared.data,\n\t\t\t\t\t\t\t\tlabel: prepared.source.label, // annotations ride the copy (§10.12)\n\t\t\t\t\t\t\t\tmetadata: prepared.source.metadata,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t// Path order means source positions already ascend, so a\n\t\t\t\t\t\t\t// rejection here would mean the source tree violated its own\n\t\t\t\t\t\t\t// ordering invariant rather than anything about this copy.\n\t\t\t\t\t\t\tconst copied = yield* insertEntry(entryRow);\n\t\t\t\t\t\t\tif (copied.length === 0) {\n\t\t\t\t\t\t\t\treturn yield* Effect.die(\n\t\t\t\t\t\t\t\t\t`fork: copied entry ${prepared.id} at seq ${prepared.source.seq} does not advance`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Parts: new ids, re-keyed entry/session, everything else verbatim —\n\t\t\t\t\t\t// including pending toolCalls (the fork inherits crash recovery).\n\t\t\t\t\t\tconst messageEntryIds = pathEntries\n\t\t\t\t\t\t\t.filter((entry) => messageTypes.has(entry.type))\n\t\t\t\t\t\t\t.map((entry) => entry.id);\n\t\t\t\t\t\tif (messageEntryIds.length > 0) {\n\t\t\t\t\t\t\tconst parts = yield* selectPartsForEntries(messageEntryIds);\n\t\t\t\t\t\t\tfor (const part of parts) {\n\t\t\t\t\t\t\t\tconst partRow = yield* SessionEntryPartRow.insert.makeEffect({\n\t\t\t\t\t\t\t\t\tid: uuidv7(),\n\t\t\t\t\t\t\t\t\tentryId: idMap.get(part.entryId)!,\n\t\t\t\t\t\t\t\t\tsessionId: newSessionId,\n\t\t\t\t\t\t\t\t\tpartIndex: part.partIndex,\n\t\t\t\t\t\t\t\t\ttype: part.type,\n\t\t\t\t\t\t\t\t\tstatus: part.status,\n\t\t\t\t\t\t\t\t\tcallId: part.callId,\n\t\t\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\t\t\tdata: part.data,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tyield* insertPart(partRow);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (Option.isSome(targetId)) {\n\t\t\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\t\tUPDATE session SET leaf_entry_id = ${idMap.get(targetId.value)!}, updated_at = ${now}\n\t\t\t\t\t\t\t\tWHERE id = ${newSessionId}\n\t\t\t\t\t\t\t`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// The copied entries hold positions from the source's log, so the\n\t\t\t\t\t\t// new aggregate starts above the highest of them. Without this its\n\t\t\t\t\t\t// first event would land at 0, underneath the copy, and\n\t\t\t\t\t\t// `parent.seq < child.seq` — which `selectPath` orders by — would\n\t\t\t\t\t\t// invert. An empty fork copies nothing and starts at 0 normally.\n\t\t\t\t\t\tif (preparedEntries.length > 0 && Option.isSome(targetId)) {\n\t\t\t\t\t\t\tconst baseSeq = preparedEntries.reduce(\n\t\t\t\t\t\t\t\t(highest, prepared) => Math.max(highest, prepared.source.seq),\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tyield* events.advance(newSessionId, baseSeq);\n\t\t\t\t\t\t\t// Lands at baseSeq + 1, so the seeded range is recorded by the\n\t\t\t\t\t\t\t// log itself rather than inferable only from `parentId`.\n\t\t\t\t\t\t\tyield* events.publish(EventList.SessionForked, {\n\t\t\t\t\t\t\t\tsessionId: newSessionId,\n\t\t\t\t\t\t\t\tsourceSessionId: input.sessionId,\n\t\t\t\t\t\t\t\tsourceEntryId: targetId.value,\n\t\t\t\t\t\t\t\tbaseSeq,\n\t\t\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst created = yield* findSession(newSessionId);\n\t\t\t\t\t\tif (Option.isNone(created)) {\n\t\t\t\t\t\t\treturn yield* Effect.die(new Error(\"session fork: created session did not persist\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { _tag: \"forked\", session: created.value } as const;\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\tswitch (result._tag) {\n\t\t\t\tcase \"sessionNotFound\":\n\t\t\t\t\treturn yield* new SessionNotFoundError({ sessionId: input.sessionId });\n\t\t\t\tcase \"entryNotFound\":\n\t\t\t\t\treturn yield* new EntryNotFoundError({ sessionId: input.sessionId, entryId: result.entryId });\n\t\t\t\tcase \"invalidMode\":\n\t\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\t\tentryId: result.entryId,\n\t\t\t\t\t\ttype: result.type,\n\t\t\t\t\t\treason: `fork mode \"before\" requires a user entry`,\n\t\t\t\t\t});\n\t\t\t\tcase \"invalidData\":\n\t\t\t\t\treturn yield* new InvalidEntryDataError({\n\t\t\t\t\t\tentryId: result.entryId,\n\t\t\t\t\t\ttype: result.type,\n\t\t\t\t\t\treason: result.reason,\n\t\t\t\t\t});\n\t\t\t\tcase \"forked\":\n\t\t\t\t\treturn result.session;\n\t\t\t}\n\t\t});\n\n\t\tconst relink = Effect.fn(\"Session.relink\")(function* (input: RelinkInput) {\n\t\t\tconst reject = (reason: RelinkReason) =>\n\t\t\t\tnew RelinkError({ sessionId: input.sessionId, spaceId: input.spaceId, reason });\n\t\t\tconst session = yield* findSession(input.sessionId).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(session)) return yield* new SessionNotFoundError({ sessionId: input.sessionId });\n\t\t\tconst target = yield* findSpaceById(input.spaceId).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(target)) return yield* reject(\"space_not_found\");\n\t\t\tif (target.value.status !== \"active\") return yield* reject(\"space_is_archived\");\n\t\t\t// Same-project guard. A missing current space means the FK invariant is\n\t\t\t// already broken; there is nothing to compare, so the move is allowed.\n\t\t\tconst current = yield* findSpace(input.sessionId).pipe(Effect.orDie);\n\t\t\tif (Option.isSome(current) && current.value.projectId !== target.value.projectId) {\n\t\t\t\treturn yield* reject(\"project_scope_mismatch\");\n\t\t\t}\n\t\t\tconst directory =\n\t\t\t\tinput.directory ??\n\t\t\t\t(Option.isSome(current)\n\t\t\t\t\t? rebaseDirectory(current.value.location, target.value.location, session.value.directory)\n\t\t\t\t\t: target.value.location);\n\t\t\tif (!directoryWithin(target.value.location, directory)) return yield* reject(\"directory_outside_space\");\n\t\t\tconst now = yield* epochNow;\n\t\t\tyield* sql`\n\t\t\t\tUPDATE session SET space_id = ${input.spaceId}, directory = ${directory}, updated_at = ${now}\n\t\t\t\tWHERE id = ${input.sessionId}\n\t\t\t`.pipe(Effect.orDie);\n\t\t\tconst updated = yield* findSession(input.sessionId).pipe(Effect.orDie);\n\t\t\tif (Option.isNone(updated)) return yield* Effect.die(new Error(\"session relink did not persist\"));\n\t\t\treturn updated.value;\n\t\t});\n\n\t\tconst branch = Effect.fn(\"Session.branch\")(function* (input: { sessionId: string; entryId: string }) {\n\t\t\tconst moved = yield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst rows = yield* sql`\n\t\t\t\t\t\t\tSELECT id FROM session_entry WHERE id = ${input.entryId} AND session_id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\t\t\t\t\t\tif (rows.length === 0) return false;\n\t\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session SET leaf_entry_id = ${input.entryId}, updated_at = ${now}\n\t\t\t\t\t\t\tWHERE id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\tif (!moved) {\n\t\t\t\treturn yield* new EntryNotFoundError({ sessionId: input.sessionId, entryId: input.entryId });\n\t\t\t}\n\t\t});\n\n\t\tconst setLabel = Effect.fn(\"Session.setLabel\")(function* (input: {\n\t\t\tsessionId: string;\n\t\t\tentryId: string;\n\t\t\tlabel: string | null;\n\t\t}) {\n\t\t\tconst labeled = yield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst rows = yield* sql`\n\t\t\t\t\t\t\tSELECT id FROM session_entry WHERE id = ${input.entryId} AND session_id = ${input.sessionId}\n\t\t\t\t\t\t`;\n\t\t\t\t\t\tif (rows.length === 0) return false;\n\t\t\t\t\t\tconst now = yield* epochNow;\n\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\tUPDATE session_entry SET label = ${input.label}, updated_at = ${now}\n\t\t\t\t\t\t\tWHERE id = ${input.entryId}\n\t\t\t\t\t\t`;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\tif (!labeled) {\n\t\t\t\treturn yield* new EntryNotFoundError({ sessionId: input.sessionId, entryId: input.entryId });\n\t\t\t}\n\t\t});\n\n\t\treturn Service.of({\n\t\t\tcreate,\n\t\t\tget,\n\t\t\tspace,\n\t\t\tlist,\n\t\t\tentry,\n\t\t\tpath,\n\t\t\ttimeline,\n\t\t\tunsettled,\n\t\t\tappend,\n\t\t\treplaceAssistant,\n\t\t\tsettleToolCall,\n\t\t\tsetEntryState,\n\t\t\tabortAssistant,\n\t\t\tfork,\n\t\t\trelink,\n\t\t\tbranch,\n\t\t\tsetLabel,\n\t\t});\n\t}),\n);\n\n// Sessions foreign-key to sandbox_instance, so the host row has to exist before\n// a session can record which namespace it runs in.\n// Plain database: the host has no row and the namespace foreign key is skipped\n// on NULL, so a session needs no sandbox setup to exist.\nexport const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer));\n\nexport * as Session from \"./session.ts\";\n","import { Schema } from \"effect\";\n\nexport class ContextDecodeError extends Schema.TaggedError<ContextDecodeError>()(\"ContextDecodeError\", {\n\tentryId: Schema.String,\n\ttype: Schema.String,\n\treason: Schema.String,\n}) {}\n\nexport class ContextEncodeError extends Schema.TaggedError<ContextEncodeError>()(\"ContextEncodeError\", {\n\tmessageId: Schema.String,\n\trole: Schema.String,\n\treason: Schema.String,\n}) {}\n\nexport class ContextInvariantError extends Schema.TaggedError<ContextInvariantError>()(\"ContextInvariantError\", {\n\treason: Schema.String,\n}) {}\n","/*\n * @file Codec provides the wire codec schema b/w harness <-> aikit\n * Use helper functions to encode-decode payload over the wire.\n * */\nimport { Message } from \"@codeworksh/aikit\";\nimport { DateTime, Effect, Option, Schema } from \"effect\";\nimport { validateAikitMessage, validateAikitUserMessage } from \"../schema.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport type { Session } from \"../session/session.ts\";\nimport { ContextDecodeError, ContextEncodeError } from \"./errors.ts\";\n\nexport interface EncodedMessage {\n\treadonly type: \"user\" | \"assistant\";\n\treadonly data: string;\n\treadonly parts: ReadonlyArray<Session.AppendPart>;\n}\n\ntype AikitPart = Message.AssistantMessage[\"parts\"][number] | Message.UserMessage[\"parts\"][number];\n\nconst reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause));\nconst decodeJsonObject = Schema.decodeUnknownEffect(SessionSchema.JsonObject);\nconst encodeJsonObject = Schema.encodeEffect(SessionSchema.JsonObject);\n\nexport const encodePart = Effect.fn(\"Context.encodePart\")(function* (\n\tpart: AikitPart,\n): Effect.fn.Return<Session.AppendPart, ContextEncodeError> {\n\tconst data = yield* encodeJsonObject(part).pipe(\n\t\tEffect.mapError(\n\t\t\t(cause) =>\n\t\t\t\tnew ContextEncodeError({\n\t\t\t\t\tmessageId: part.type === \"toolCall\" ? part.callID : \"part\",\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\treason: cause.message,\n\t\t\t\t}),\n\t\t),\n\t);\n\treturn {\n\t\ttype: part.type,\n\t\t...(part.type === \"toolCall\" ? { status: part.status, callId: part.callID, toolName: part.name } : {}),\n\t\tdata,\n\t};\n});\n\nconst parseJson = (data: string, entryId: string, type: string, subject: string) =>\n\tdecodeJsonObject(data).pipe(\n\t\tEffect.mapError(\n\t\t\t(cause) =>\n\t\t\t\tnew ContextDecodeError({\n\t\t\t\t\tentryId,\n\t\t\t\t\ttype,\n\t\t\t\t\treason: `${subject} is not valid JSON: ${reasonOf(cause)}`,\n\t\t\t\t}),\n\t\t),\n\t);\n\nconst validateDecoded = (\n\tvalue: unknown,\n\tentryId: string,\n\ttype: string,\n): Effect.Effect<Message.Message, ContextDecodeError> =>\n\tEffect.try({\n\t\ttry: () => validateAikitMessage(value, `context entry ${entryId}`),\n\t\tcatch: (cause) => new ContextDecodeError({ entryId, type, reason: reasonOf(cause) }),\n\t});\n\nexport const validateUserMessage = (\n\tvalue: unknown,\n\tentryId: string,\n\ttype: string,\n): Effect.Effect<Message.UserMessage, ContextDecodeError> =>\n\tEffect.try({\n\t\ttry: () => validateAikitUserMessage(value, `context entry ${entryId}`),\n\t\tcatch: (cause) => new ContextDecodeError({ entryId, type, reason: reasonOf(cause) }),\n\t});\n\nexport const encodeMessage = Effect.fn(\"Context.encodeMessage\")(function* (\n\tmessage: Message.Message,\n): Effect.fn.Return<EncodedMessage, ContextEncodeError> {\n\tconst validated = yield* Effect.try({\n\t\ttry: () => validateAikitMessage(message, `context message ${message.messageId}`),\n\t\tcatch: (cause) =>\n\t\t\tnew ContextEncodeError({\n\t\t\t\tmessageId: message.messageId,\n\t\t\t\trole: message.role,\n\t\t\t\treason: reasonOf(cause),\n\t\t\t}),\n\t});\n\tconst { parts, ...envelope } = validated;\n\tconst data = yield* encodeJsonObject(envelope).pipe(\n\t\tEffect.mapError(\n\t\t\t(cause) =>\n\t\t\t\tnew ContextEncodeError({\n\t\t\t\t\tmessageId: message.messageId,\n\t\t\t\t\trole: message.role,\n\t\t\t\t\treason: cause.message,\n\t\t\t\t}),\n\t\t),\n\t);\n\tconst encodedParts = yield* Effect.forEach(parts, (part) =>\n\t\tencodePart(part).pipe(\n\t\t\tEffect.mapError(\n\t\t\t\t(cause) =>\n\t\t\t\t\tnew ContextEncodeError({\n\t\t\t\t\t\tmessageId: message.messageId,\n\t\t\t\t\t\trole: message.role,\n\t\t\t\t\t\treason: cause.reason,\n\t\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t);\n\treturn {\n\t\ttype: validated.role,\n\t\tdata,\n\t\tparts: encodedParts,\n\t};\n});\n\nconst decodeParts = Effect.fn(\"Context.decodeParts\")(function* (\n\thydrated: Session.HydratedEntry,\n): Effect.fn.Return<ReadonlyArray<unknown>, ContextDecodeError> {\n\tconst { entry } = hydrated;\n\tconst sorted = [...hydrated.parts].sort((left, right) => left.partIndex - right.partIndex);\n\tconst parts: unknown[] = [];\n\tfor (const [index, row] of sorted.entries()) {\n\t\tif (row.entryId !== entry.id) {\n\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\tentryId: entry.id,\n\t\t\t\ttype: entry.type,\n\t\t\t\treason: `part ${index} belongs to entry ${row.entryId}`,\n\t\t\t});\n\t\t}\n\t\tif (row.partIndex !== index) {\n\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\tentryId: entry.id,\n\t\t\t\ttype: entry.type,\n\t\t\t\treason: `part indexes must be dense from 0; expected ${index}, received ${row.partIndex}`,\n\t\t\t});\n\t\t}\n\t\tconst part = yield* parseJson(row.data, entry.id, entry.type, `part ${index}`);\n\t\tif (typeof part !== \"object\" || part === null || !(\"type\" in part) || part.type !== row.type) {\n\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\tentryId: entry.id,\n\t\t\t\ttype: entry.type,\n\t\t\t\treason: `part ${index} type does not match promoted type \"${row.type}\"`,\n\t\t\t});\n\t\t}\n\t\tif (row.type === \"toolCall\") {\n\t\t\tconst promotedStatus = Option.getOrUndefined(row.status);\n\t\t\tconst promotedCallId = Option.getOrUndefined(row.callId);\n\t\t\tconst promotedToolName = Option.getOrUndefined(row.toolName);\n\t\t\tif (\n\t\t\t\t!(\"status\" in part) ||\n\t\t\t\tpart.status !== promotedStatus ||\n\t\t\t\t!(\"callID\" in part) ||\n\t\t\t\tpart.callID !== promotedCallId ||\n\t\t\t\t!(\"name\" in part) ||\n\t\t\t\tpart.name !== promotedToolName\n\t\t\t) {\n\t\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\t\tentryId: entry.id,\n\t\t\t\t\ttype: entry.type,\n\t\t\t\t\treason: `part ${index} tool columns do not match its authoritative JSON`,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (Option.isSome(row.status) || Option.isSome(row.callId) || Option.isSome(row.toolName)) {\n\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\tentryId: entry.id,\n\t\t\t\ttype: entry.type,\n\t\t\t\treason: `part ${index} type \"${row.type}\" must not carry promoted tool columns`,\n\t\t\t});\n\t\t}\n\t\tparts.push(part);\n\t}\n\treturn parts;\n});\n\nexport const decodeSyntheticMessage = Effect.fn(\"Context.decodeSyntheticMessage\")(function* (\n\thydrated: Session.HydratedEntry,\n): Effect.fn.Return<Message.UserMessage, ContextDecodeError> {\n\tconst { entry } = hydrated;\n\tconst parts = yield* decodeParts(hydrated);\n\treturn yield* validateUserMessage(\n\t\t{\n\t\t\tmessageId: entry.id,\n\t\t\trole: \"user\",\n\t\t\ttime: { created: DateTime.toEpochMillis(entry.createdAt) },\n\t\t\tparts,\n\t\t},\n\t\tentry.id,\n\t\tentry.type,\n\t);\n});\n\nexport const decodeMessage = Effect.fn(\"Context.decodeMessage\")(function* (\n\thydrated: Session.HydratedEntry,\n): Effect.fn.Return<Message.Message, ContextDecodeError> {\n\tconst { entry } = hydrated;\n\tif (entry.type !== \"user\" && entry.type !== \"assistant\") {\n\t\treturn yield* new ContextDecodeError({\n\t\t\tentryId: entry.id,\n\t\t\ttype: entry.type,\n\t\t\treason: \"only user and assistant entries contain complete aikit messages\",\n\t\t});\n\t}\n\n\tconst envelope = yield* parseJson(entry.data, entry.id, entry.type, \"message envelope\");\n\tconst parts = yield* decodeParts(hydrated);\n\n\tconst message = yield* validateDecoded({ ...(envelope as Record<string, unknown>), parts }, entry.id, entry.type);\n\tif (message.messageId !== entry.id) {\n\t\treturn yield* new ContextDecodeError({\n\t\t\tentryId: entry.id,\n\t\t\ttype: entry.type,\n\t\t\treason: `messageId \"${message.messageId}\" does not match entry id`,\n\t\t});\n\t}\n\tif (message.role !== entry.type) {\n\t\treturn yield* new ContextDecodeError({\n\t\t\tentryId: entry.id,\n\t\t\ttype: entry.type,\n\t\t\treason: `message role \"${message.role}\" does not match entry type`,\n\t\t});\n\t}\n\treturn message;\n});\n\nexport * as ContextCodec from \"./codec.ts\";\n","import { Message } from \"@codeworksh/aikit\";\nimport { DateTime, Effect, Schema } from \"effect\";\nimport { optional } from \"../schema.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport type { Session } from \"../session/session.ts\";\nimport { decodeMessage, decodeSyntheticMessage } from \"./codec.ts\";\nimport { ContextDecodeError } from \"./errors.ts\";\n\nexport interface Snapshot {\n\treadonly sessionId: string;\n\treadonly leafEntryId: string | null;\n\treadonly messages: ReadonlyArray<Message.Message>;\n\treadonly lastAssistant?: {\n\t\treadonly entryId: string;\n\t\treadonly message: Message.AssistantMessage;\n\t};\n}\n\nconst SyntheticData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tmessageId: Schema.String,\n\t\tcustomType: Schema.String,\n\t\tdisplay: Schema.Boolean,\n\t\tdetails: optional(Schema.Unknown),\n\t}),\n);\n\nconst BranchSummaryData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tfromEntryId: Schema.String,\n\t\tsummary: Schema.String,\n\t\tdetails: optional(Schema.Unknown),\n\t}),\n);\n\nconst CustomData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tcustomType: Schema.String,\n\t\tdata: optional(Schema.Unknown),\n\t}),\n);\n\nconst decodeSyntheticData = Schema.decodeUnknownEffect(SyntheticData);\nconst decodeCompactionData = Schema.decodeUnknownEffect(SessionSchema.CompactionData);\nconst decodeBranchSummaryData = Schema.decodeUnknownEffect(BranchSummaryData);\nconst decodeCustomData = Schema.decodeUnknownEffect(CustomData);\n\nconst decodeFailure = (entry: Session.HydratedEntry) => (error: { readonly message: string }) =>\n\tnew ContextDecodeError({\n\t\tentryId: entry.entry.id,\n\t\ttype: entry.entry.type,\n\t\treason: error.message,\n\t});\n\n// TODO(sanchitrk):\n// comeback to this when we've decided on compaction, branch summary, etc.\n\nconst compactionText = (summary: string) =>\n\t`The conversation history before this point was compacted into the following summary:\\n\\n<summary>\\n${summary}\\n</summary>`;\n\nconst branchSummaryText = (summary: string) =>\n\t`The following is a summary of a branch that this conversation came back from:\\n\\n<summary>\\n${summary}\\n</summary>`;\n\nconst wrapperMessage = (entry: Session.HydratedEntry, text: string): Message.UserMessage =>\n\tMessage.createUserMessage({\n\t\tmessageId: entry.entry.id,\n\t\trole: \"user\",\n\t\ttime: { created: DateTime.toEpochMillis(entry.entry.createdAt) },\n\t\tparts: [{ type: \"text\", text }],\n\t});\n\n// assembles entries which builds the LLM context.\n// a entry is hybrid data type; with entry types not relevant to the LLMs\n// yet stored into the timeline.\n//\n// NOTE(sanchitrk):\n// remove unnecessary cases. comeback to this when in use.\nexport const assemblePath = Effect.fn(\"Context.assemblePath\")(function* (\n\tsessionId: string,\n\tpath: ReadonlyArray<Session.HydratedEntry>,\n): Effect.fn.Return<Snapshot, ContextDecodeError> {\n\tconst leafEntryId = path.at(-1)?.entry.id ?? null;\n\tconst committedPath = path.filter((hydrated) => hydrated.entry.state === \"committed\");\n\tlet lastAssistant: Snapshot[\"lastAssistant\"];\n\tlet latestCompaction: { readonly index: number; readonly data: SessionSchema.CompactionData } | undefined;\n\n\tconst messagesByEntry = new Map<string, Message.Message>();\n\tconst compactions = new Map<string, SessionSchema.CompactionData>();\n\tconst branchSummaries = new Map<string, string>();\n\n\tfor (const [index, hydrated] of committedPath.entries()) {\n\t\tconst { entry } = hydrated;\n\t\tif (entry.sessionId !== sessionId) {\n\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\tentryId: entry.id,\n\t\t\t\ttype: entry.type,\n\t\t\t\treason: `entry belongs to session ${entry.sessionId}, not ${sessionId}`,\n\t\t\t});\n\t\t}\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"user\": {\n\t\t\t\tmessagesByEntry.set(entry.id, yield* decodeMessage(hydrated));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"assistant\": {\n\t\t\t\tconst message = yield* decodeMessage(hydrated);\n\t\t\t\tif (message.role !== \"assistant\") {\n\t\t\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\t\t\tentryId: entry.id,\n\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\treason: \"assistant entry decoded to a non-assistant message\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tmessagesByEntry.set(entry.id, message);\n\t\t\t\tlastAssistant = { entryId: entry.id, message };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"synthetic\": {\n\t\t\t\tconst data = yield* decodeSyntheticData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tif (data.messageId !== entry.id) {\n\t\t\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\t\t\tentryId: entry.id,\n\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\treason: `messageId \"${data.messageId}\" does not match entry id`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tmessagesByEntry.set(entry.id, yield* decodeSyntheticMessage(hydrated));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\": {\n\t\t\t\tconst data = yield* decodeCompactionData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tcompactions.set(entry.id, data);\n\t\t\t\tlatestCompaction = { index, data };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branchSummary\": {\n\t\t\t\tconst data = yield* decodeBranchSummaryData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tbranchSummaries.set(entry.id, data.summary);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom\": {\n\t\t\t\tyield* decodeCustomData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tlet effectivePath = committedPath;\n\tif (latestCompaction !== undefined) {\n\t\tconst { index, data } = latestCompaction;\n\t\tlet kept: ReadonlyArray<Session.HydratedEntry> = [];\n\t\tif (data.firstKeptEntryId !== null) {\n\t\t\tconst firstKeptIndex = committedPath.findIndex((item) => item.entry.id === data.firstKeptEntryId);\n\t\t\tif (firstKeptIndex < 0 || firstKeptIndex >= index) {\n\t\t\t\tconst entry = committedPath[index]!;\n\t\t\t\treturn yield* new ContextDecodeError({\n\t\t\t\t\tentryId: entry.entry.id,\n\t\t\t\t\ttype: entry.entry.type,\n\t\t\t\t\treason: `firstKeptEntryId \"${data.firstKeptEntryId}\" is not before the compaction on its path`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tkept = committedPath.slice(firstKeptIndex, index);\n\t\t}\n\t\teffectivePath = [committedPath[index]!, ...kept, ...committedPath.slice(index + 1)];\n\t}\n\n\tconst messages: Message.Message[] = [];\n\tfor (const hydrated of effectivePath) {\n\t\tconst { entry } = hydrated;\n\t\tconst message = messagesByEntry.get(entry.id);\n\t\tif (message !== undefined) {\n\t\t\tmessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst compaction = compactions.get(entry.id);\n\t\tif (compaction !== undefined) {\n\t\t\tmessages.push(wrapperMessage(hydrated, compactionText(compaction.summary)));\n\t\t\tcontinue;\n\t\t}\n\t\tconst branchSummary = branchSummaries.get(entry.id);\n\t\tif (branchSummary !== undefined) {\n\t\t\tmessages.push(wrapperMessage(hydrated, branchSummaryText(branchSummary)));\n\t\t}\n\t}\n\n\treturn {\n\t\tsessionId,\n\t\tleafEntryId,\n\t\tmessages,\n\t\t...(lastAssistant === undefined ? {} : { lastAssistant }),\n\t};\n});\n\nexport * as ContextAssembly from \"./assemble.ts\";\n","import { Context, Effect, Layer, Option } from \"effect\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { Session } from \"../session/session.ts\";\nimport { assemblePath, type Snapshot } from \"./assemble.ts\";\nimport type { ContextDecodeError } from \"./errors.ts\";\n\nexport type ContextReadError = Session.SessionNotFoundError | ContextDecodeError;\n\nexport interface Interface {\n\treadonly assemble: (sessionId: SessionSchema.ID) => Effect.Effect<Snapshot, ContextReadError>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/context/context/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sessions = yield* Session.Service;\n\t\tconst assemble = Effect.fn(\"Context.assemble\")(function* (sessionId: SessionSchema.ID) {\n\t\t\tconst found = yield* sessions.get(sessionId);\n\t\t\tif (Option.isNone(found)) return yield* new Session.SessionNotFoundError({ sessionId });\n\t\t\treturn yield* assemblePath(sessionId, yield* sessions.path(sessionId));\n\t\t});\n\t\treturn Service.of({ assemble });\n\t}),\n);\n\nexport * from \"./assemble.ts\";\nexport * from \"./codec.ts\";\nexport * from \"./errors.ts\";\n\nexport * as Context from \"./context.ts\";\n","import { type Effect, type Layer, Option, Schema } from \"effect\";\nimport type { SandboxProviderError } from \"./errors.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\n\n/** Version of the loadable sandbox-driver module ABI. */\nexport const apiVersion = 1 as const;\nexport type ApiVersion = typeof apiVersion;\n\n/** Open driver identity. Adding a driver never extends a union in core. */\nexport const Name = Schema.String.check(Schema.isNonEmpty()).pipe(Schema.brand(\"SandboxDriver.Name\"));\nexport type Name = typeof Name.Type;\n\n/** A path whose coordinate system is the mounted namespace. */\nexport const AbsolutePath = Schema.String.check(Schema.isStartsWith(\"/\")).pipe(\n\tSchema.brand(\"SandboxDriver.AbsolutePath\"),\n);\nexport type AbsolutePath = typeof AbsolutePath.Type;\n\nexport const RuntimeConfigBase = Schema.Struct({ defaultCwd: AbsolutePath });\nexport interface RuntimeConfigBase extends Schema.Schema.Type<typeof RuntimeConfigBase> {}\n\nexport interface Capabilities {\n\treadonly inspect: boolean;\n\treadonly reattach: boolean;\n\treadonly wake: boolean;\n\treadonly stop: boolean;\n\treadonly destroy: boolean;\n\treadonly cancels: boolean;\n}\n\nexport interface Observed {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus?: string | undefined;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface Provisioned<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly providerResourceId?: string | undefined;\n\treadonly providerStatus?: string | undefined;\n\treadonly runtimeConfig: RuntimeConfig;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface RuntimeInput<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly id: SandboxInstance.ID;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly runtimeConfig: RuntimeConfig;\n}\n\nexport interface Driver<CreateConfig, RuntimeConfig extends RuntimeConfigBase> {\n\treadonly name: Name;\n\treadonly kind: Exclude<SandboxInstance.Kind, \"local\">;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<CreateConfig, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfig, unknown>;\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: CreateConfig;\n\t}) => Effect.Effect<Provisioned<RuntimeConfig>, SandboxProviderError>;\n\treadonly runtimeConfigFor?:\n\t\t| ((input: {\n\t\t\t\treadonly providerResourceId: string;\n\t\t\t\treadonly overrides?: Partial<RuntimeConfig> | undefined;\n\t\t }) => Effect.Effect<RuntimeConfig, SandboxProviderError>)\n\t\t| undefined;\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfig>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nexport type Definition<CreateConfig, RuntimeConfig extends RuntimeConfigBase> = Pick<\n\tDriver<CreateConfig, RuntimeConfig>,\n\t\"name\" | \"createConfigCodec\" | \"runtimeConfigCodec\"\n>;\n\n/** Registry-only erased shape. Driver authors construct it via {@link driver}. */\nexport interface Registered {\n\treadonly name: Name;\n\treadonly kind: Exclude<SandboxInstance.Kind, \"local\">;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<unknown, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfigBase, unknown>;\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: unknown;\n\t}) => Effect.Effect<Provisioned<RuntimeConfigBase>, SandboxProviderError>;\n\treadonly runtimeConfigFor?:\n\t\t| ((input: {\n\t\t\t\treadonly providerResourceId: string;\n\t\t\t\treadonly overrides?: Readonly<Record<string, unknown>> | undefined;\n\t\t }) => Effect.Effect<RuntimeConfigBase, SandboxProviderError>)\n\t\t| undefined;\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfigBase>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nexport const erase = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tvalue: Driver<CreateConfig, RuntimeConfig>,\n): Registered => ({\n\tname: value.name,\n\tkind: value.kind,\n\tcapabilities: value.capabilities,\n\tcreateConfigCodec: value.createConfigCodec as Schema.Codec<unknown, unknown>,\n\truntimeConfigCodec: value.runtimeConfigCodec as Schema.Codec<RuntimeConfigBase, unknown>,\n\tcreate: (input) => value.create({ instanceId: input.instanceId, config: input.config as CreateConfig }),\n\t...(value.runtimeConfigFor === undefined\n\t\t? {}\n\t\t: {\n\t\t\t\truntimeConfigFor: (input: {\n\t\t\t\t\treadonly providerResourceId: string;\n\t\t\t\t\treadonly overrides?: Readonly<Record<string, unknown>> | undefined;\n\t\t\t\t}) =>\n\t\t\t\t\tvalue.runtimeConfigFor!({\n\t\t\t\t\t\tproviderResourceId: input.providerResourceId,\n\t\t\t\t\t\t...(input.overrides === undefined ? {} : { overrides: input.overrides as Partial<RuntimeConfig> }),\n\t\t\t\t\t}),\n\t\t\t}),\n\tattach: (input) => value.attach(input as RuntimeInput<RuntimeConfig>),\n\t...(value.inspect === undefined\n\t\t? {}\n\t\t: { inspect: (input: RuntimeInput<RuntimeConfigBase>) => value.inspect!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(value.wake === undefined\n\t\t? {}\n\t\t: { wake: (input: RuntimeInput<RuntimeConfigBase>) => value.wake!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(value.stop === undefined\n\t\t? {}\n\t\t: { stop: (input: RuntimeInput<RuntimeConfigBase>) => value.stop!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(value.destroy === undefined\n\t\t? {}\n\t\t: { destroy: (input: RuntimeInput<RuntimeConfigBase>) => value.destroy!(input as RuntimeInput<RuntimeConfig>) }),\n});\n\nexport type Source = \"core\" | \"builtin\" | \"package\" | \"file\";\n\nexport interface Registration {\n\treadonly registered: Registered;\n\treadonly apiVersion: ApiVersion;\n\treadonly source: Source;\n}\n\nexport interface Module<Options> {\n\treadonly apiVersion: ApiVersion;\n\treadonly name: Name;\n\treadonly options: Schema.Codec<Options, unknown>;\n\treadonly make: (options: Options) => Registration;\n}\n\nexport interface ModuleDefinition<Options> {\n\treadonly apiVersion: ApiVersion;\n\treadonly name: string | Name;\n\treadonly options: Schema.Codec<Options, unknown>;\n\treadonly make: (options: Options) => Registration;\n}\n\n/** Define the default export of a loadable sandbox package. */\nconst defineModule = <Options>(value: ModuleDefinition<Options>): Module<Options> => ({\n\t...value,\n\tname: Name.make(value.name),\n});\nexport { defineModule as module };\n\n/** Construct a driver and its registry contribution. */\nexport const driver = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tvalue: Driver<CreateConfig, RuntimeConfig>,\n): Driver<CreateConfig, RuntimeConfig> & Registration =>\n\tObject.assign(value, {\n\t\tregistered: erase(value),\n\t\tapiVersion,\n\t\tsource: \"builtin\" as const,\n\t});\n\n/** Attach trusted origin metadata without changing the driver implementation. */\nexport const withSource = (registration: Registration, source: Source): Registration => ({\n\t...registration,\n\tsource,\n});\n\nexport * as SandboxDriver from \"./driver.ts\";\n","import { Schema } from \"effect\";\nimport { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Lifecycle errors are confined to the control plane. Once a mount succeeds,\n * consumers continue to see only FileSystemError and ShellError.\n */\nexport class SandboxNotFoundError extends Schema.TaggedError<SandboxNotFoundError>()(\"SandboxNotFoundError\", {\n\tid: SandboxInstance.ID,\n}) {}\n\nexport class SandboxDriverNotRegisteredError extends Schema.TaggedError<SandboxDriverNotRegisteredError>()(\n\t\"SandboxDriverNotRegisteredError\",\n\t{\n\t\tdriver: Schema.String,\n\t\tregistered: Schema.optional(Schema.Array(Schema.String)),\n\t},\n) {}\n\nexport class SandboxDriverRegistrationError extends Schema.TaggedError<SandboxDriverRegistrationError>()(\n\t\"SandboxDriverRegistrationError\",\n\t{\n\t\tdriver: Schema.String,\n\t\treason: Schema.String,\n\t},\n) {}\n\nexport const SandboxDriverLoadPhase = Schema.Literals([\n\t\"resolve\",\n\t\"import\",\n\t\"module\",\n\t\"api-version\",\n\t\"options\",\n\t\"factory\",\n\t\"registration\",\n]);\nexport type SandboxDriverLoadPhase = typeof SandboxDriverLoadPhase.Type;\n\nexport class SandboxDriverLoadError extends Schema.TaggedError<SandboxDriverLoadError>()(\"SandboxDriverLoadError\", {\n\tspecifier: Schema.String,\n\tphase: SandboxDriverLoadPhase,\n\tdriver: Schema.optional(Schema.String),\n\treason: Schema.String,\n}) {}\n\nexport class SandboxBusyError extends Schema.TaggedError<SandboxBusyError>()(\"SandboxBusyError\", {\n\tid: SandboxInstance.ID,\n\trefCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nexport class SandboxMustBeStoppedError extends Schema.TaggedError<SandboxMustBeStoppedError>()(\n\t\"SandboxMustBeStoppedError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\tstatus: SandboxInstance.Status,\n\t},\n) {}\n\nexport class SandboxRemovedError extends Schema.TaggedError<SandboxRemovedError>()(\"SandboxRemovedError\", {\n\tid: SandboxInstance.ID,\n\tremovedAt: Schema.optional(Schema.DateTimeUtc),\n}) {}\n\nexport class SandboxUnavailError extends Schema.TaggedError<SandboxUnavailError>()(\"SandboxUnavailError\", {\n\tid: SandboxInstance.ID,\n\treason: Schema.String,\n}) {}\n\nexport class SandboxUnsupportedError extends Schema.TaggedError<SandboxUnsupportedError>()(\"SandboxUnsupportedError\", {\n\tid: Schema.optional(SandboxInstance.ID),\n\tdriver: Schema.String,\n\toperation: Schema.String,\n}) {}\n\nexport class SandboxTransitionConflictError extends Schema.TaggedError<SandboxTransitionConflictError>()(\n\t\"SandboxTransitionConflictError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\texpected: Schema.Array(SandboxInstance.Status),\n\t\tactual: SandboxInstance.Status,\n\t},\n) {}\n\n/**\n * A lifecycle failure safe to serialize, persist, or log.\n *\n * The raw SDK defect is deliberately absent from the schema. It is retained on\n * a non-enumerable symbol by {@link providerError}, so Effect's default\n * formatting and JSON serialization cannot expose credentials nested in it.\n */\nexport class SandboxProviderError extends Schema.TaggedError<SandboxProviderError>()(\"SandboxProviderError\", {\n\tdriver: Schema.String,\n\toperation: Schema.String,\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nconst rawCause = Symbol(\"@codework/sandbox/provider/error/raw/cause\");\nconst missingResource = Symbol(\"@codework/sandbox/provider/error/missing/resource\");\n\nexport const providerErrorCause = (error: SandboxProviderError): unknown =>\n\t(error as SandboxProviderError & { readonly [rawCause]?: unknown })[rawCause];\n\nexport const providerErrorIsNotFound = (error: SandboxProviderError): boolean =>\n\t(error as SandboxProviderError & { readonly [missingResource]?: boolean })[missingResource] === true;\n\nexport type Redactor = (value: string) => string;\n\nconst REDACTED = \"<redacted>\";\n\n/**\n * Conservative text redaction shared by every driver sanitizer.\n *\n * Disclaimer: This can really leak. Its never safe\n *\n * Configured secrets are removed exactly. Common authorization/header and URL\n * query shapes are masked as a second line of defence for values the caller did\n * not explicitly seed.\n *\n * Note: add support for diff regex as needed.\n */\nexport const makeRedactor = (secrets: Iterable<string> = []): Redactor => {\n\tconst configured = [...secrets].filter((secret) => secret.length > 0).sort((a, b) => b.length - a.length);\n\treturn (value) => {\n\t\tlet redacted = value;\n\t\tfor (const secret of configured) redacted = redacted.replaceAll(secret, REDACTED);\n\t\treturn redacted\n\t\t\t.replace(/\\b(authorization\\s*:\\s*(?:bearer|basic)\\s+)[^\\s,;]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b((?:api[-_]?key|token|secret|password)\\s*[=:]\\s*)[^\\s,;&]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/([?&](?:access_token|api_key|token|secret|password)=)[^&#\\s]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\\b/g, REDACTED);\n\t};\n};\n\nconst errorCode = (cause: unknown): string | undefined => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"code\" in cause)) return undefined;\n\tconst code = cause.code;\n\treturn typeof code === \"string\" || typeof code === \"number\" ? String(code) : undefined;\n};\n\nconst errorName = (cause: unknown): string => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"name\" in cause) || typeof cause.name !== \"string\")\n\t\treturn \"Error\";\n\treturn cause.name;\n};\n\nconst errorMessage = (cause: unknown): string => {\n\tif (typeof cause === \"object\" && cause !== null && \"message\" in cause && typeof cause.message === \"string\")\n\t\treturn cause.message;\n\treturn String(cause);\n};\n\nexport const sanitizeError = (cause: unknown, redact: Redactor = makeRedactor()): SandboxInstance.PersistedError => {\n\tconst code = errorCode(cause);\n\treturn {\n\t\tname: redact(errorName(cause)),\n\t\tmessage: redact(errorMessage(cause)),\n\t\t...(code === undefined ? {} : { code: redact(code) }),\n\t};\n};\n\nexport const providerError = (input: {\n\treadonly driver: string;\n\treadonly operation: string;\n\treadonly cause: unknown;\n\treadonly redact?: Redactor;\n\treadonly sanitize?: (cause: unknown, redact: Redactor) => SandboxInstance.PersistedError;\n\treadonly notFound?: boolean;\n}): SandboxProviderError => {\n\tconst redact = input.redact ?? makeRedactor();\n\tconst error = new SandboxProviderError({\n\t\tdriver: input.driver,\n\t\toperation: input.operation,\n\t\tsanitized: (input.sanitize ?? sanitizeError)(input.cause, redact),\n\t});\n\tObject.defineProperty(error, rawCause, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.cause,\n\t\twritable: false,\n\t});\n\tObject.defineProperty(error, missingResource, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.notFound === true,\n\t\twritable: false,\n\t});\n\treturn error;\n};\n\nexport type SandboxMountError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxRemovedError\n\t| SandboxProviderError;\n\nexport type SandboxCreateError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxProviderError;\n\nexport type SandboxRegisterError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxUnsupportedError\n\t| SandboxProviderError;\n\nexport type SandboxReadError = never;\n\nexport type SandboxRefreshError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxUnsupportedError\n\t| SandboxProviderError;\n\nexport type SandboxWakeError = SandboxRefreshError | SandboxRemovedError;\n\nexport type SandboxStopError = SandboxWakeError | SandboxBusyError | SandboxTransitionConflictError;\n\nexport type SandboxDestroyError = SandboxStopError | SandboxMustBeStoppedError;\n\nexport * as SandboxError from \"./errors.ts\";\n","import { NodeChildProcessSpawner, NodeFileSystem, NodePath } from \"@effect/platform-node\";\nimport { Effect, Layer } from \"effect\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\n/**\n * Child processes spawn directly on the host operating system.\n * Note that host processes see the real filesystem, not the sandbox's virtual one.\n **/\nexport const host = NodeChildProcessSpawner.layer.pipe(Layer.provide([NodeFileSystem.layer, NodePath.layer]));\n\n/**\n * Virtual sandboxes have no operating system behind them; attempting to run\n * a child process is a wiring mistake, surfaced as a defect.\n **/\nexport const unsupported = Layer.succeed(\n\tChildProcessSpawner.ChildProcessSpawner,\n\tChildProcessSpawner.make(() => Effect.die(new Error(\"process execution is not supported by this sandbox\"))),\n);\n\nexport * as Process from \"./process.ts\";\n","/* oxlint-disable effecttsgo/async-function -- VFS operations implement a Promise-based adapter contract. */\nimport type { VirtualFileSystem, VirtualStats } from \"@platformatic/vfs\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../util/posix.ts\";\nimport { SandboxFileSystem } from \"./filesystem.ts\";\n\n// The local backend: a `SandboxFileSystem.Service` over a `@platformatic/vfs`\n// VirtualFileSystem (in-memory, sqlite, or the real host OS). VFS is a\n// local-only concern — remote providers never import this module.\n\nexport class Vfs extends Context.Service<Vfs, VirtualFileSystem>()(\"@codeworksh/harness/sandbox/fs/vfs\") {}\n\nconst toFileStat = (stats: VirtualStats): SandboxFileSystem.FileStat => ({\n\tisFile: stats.isFile(),\n\tisDirectory: stats.isDirectory(),\n\tisSymbolicLink: stats.isSymbolicLink(),\n\tsize: stats.size,\n\tmtime: stats.mtime,\n});\n\n// The VFS backend authors the Promise-based provider surface; `fromProvider`\n// lifts it into the Effect service the harness consumes.\nexport interface Interface extends SandboxFileSystem.Provider {}\n\nconst bytes = (content: string | Uint8Array) =>\n\ttypeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content);\n\n/**\n * Provider factory method that implements the SandboxFileSytem\n * @param vfs VirtualFileSytem instance\n * @returns SandboxFileSytem provider instance\n */\nconst make = (vfs: VirtualFileSystem): Interface => {\n\t// Parents are `fromProvider`'s guarantee, not a backend's — a plain write here.\n\tconst writeFile = async (path: string, content: string | Uint8Array) => {\n\t\tawait vfs.promises.writeFile(path, bytes(content));\n\t};\n\n\tconst readdir = async (path: string) => vfs.promises.readdir(path);\n\n\t// Option validation lives in `fromProvider`, ahead of any mutation.\n\tconst rm = async (path: string, options?: SandboxFileSystem.RmOptions) => {\n\t\tlet stats: VirtualStats;\n\t\ttry {\n\t\t\tstats = await vfs.promises.lstat(path);\n\t\t} catch (cause) {\n\t\t\tif (options?.force && SandboxFileSystem.isNotFoundError(cause)) return;\n\t\t\tthrow cause;\n\t\t}\n\n\t\tif (stats.isDirectory()) {\n\t\t\tif (!options?.recursive) throw new Error(`rm: ${path}: is a directory`);\n\t\t\tfor (const entry of await readdir(path)) {\n\t\t\t\tawait rm(posix.join(path, entry), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\t...(options.force === undefined ? {} : { force: options.force }),\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait vfs.promises.rmdir(path);\n\t\t\treturn;\n\t\t}\n\n\t\tawait vfs.promises.unlink(path);\n\t};\n\n\treturn {\n\t\treadFile: (path) => vfs.promises.readFile(path, \"utf8\"),\n\t\treadFileBuffer: async (path) => new Uint8Array(await vfs.promises.readFile(path)),\n\t\twriteFile,\n\t\tstat: async (path) => toFileStat(await vfs.promises.stat(path)),\n\t\t// `stat` follows symlinks, so its `isSymbolicLink` describes the target and\n\t\t// is always false for a link. Symlink identity is asked for explicitly here\n\t\t// instead — the same split the remote backends expose, so a consumer cannot\n\t\t// tell local from remote by whether it can see a link at all.\n\t\tlstat: async (path) => toFileStat(await vfs.promises.lstat(path)),\n\t\treaddir,\n\t\texists: async (path) => {\n\t\t\ttry {\n\t\t\t\tawait vfs.promises.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tif (SandboxFileSystem.isNotFoundError(cause)) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path, options) => {\n\t\t\tawait vfs.promises.mkdir(path, options);\n\t\t},\n\t\trm,\n\t\t// Every VFS provider resolves symlinks itself (the host one via\n\t\t// `fs.realpath`) and rejects with ENOENT for a missing path.\n\t\trealpath: (path) => vfs.promises.realpath(path),\n\t};\n};\n\n/** The `SandboxFileSystem.Service` backed by the local {@link Vfs}. */\nexport const layer = Layer.effect(\n\tSandboxFileSystem.Service,\n\tEffect.gen(function* () {\n\t\treturn SandboxFileSystem.fromProvider(make(yield* Vfs));\n\t}),\n);\n\nexport * as Local from \"./vfs.ts\";\n","import { create, RealFSProvider } from \"@platformatic/vfs\";\nimport { Layer } from \"effect\";\n// The VFS provider contract is Promise/sync-based, so Effect's FileSystem cannot back it.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport fs from \"node:fs\";\nimport { Process } from \"../utils/process.ts\";\nimport { Local } from \"./vfs.ts\";\n\n// `RealFSProvider.realpath` mis-maps results for a `/` root (it looks for a\n// `//` prefix and falls back to echoing the input), so with provider paths\n// equal to OS paths, defer straight to the OS.\nclass HostProvider extends RealFSProvider {\n\toverride realpath(path: string) {\n\t\treturn fs.promises.realpath(path);\n\t}\n\toverride realpathSync(path: string) {\n\t\treturn fs.realpathSync(path);\n\t}\n}\n\n/**\n * The host VFS: provider-rooted at `/`, and never `chdir`ed.\n *\n * `chdir` is process-global state on a shared VFS, so baking a working directory\n * in here means two mounts at different directories cannot coexist — the second\n * would either see the first's or move it. The directory belongs to the mount\n * (`SandboxIO.mount`), which resolves relative paths per mount over this\n * transport.\n *\n * Having no virtual cwd is not the same as having `/` as one: a relative path\n * handed straight to this VFS still falls back to `process.cwd()`. That is a\n * reason to keep relative paths above the mount, not below it — nothing here\n * resolves them, and nothing here should.\n */\nexport const layer = () => {\n\tconst vfs = create(new HostProvider(\"/\"), {\n\t\tmoduleHooks: false,\n\t\tvirtualCwd: true,\n\t});\n\n\treturn Layer.merge(Layer.succeed(Local.Vfs, vfs), Process.host);\n};\n\nexport * as EnvNodeJSDefault from \"./nodejs.ts\";\n","import { Context, Effect, type JsonSchema, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"./driver.ts\";\nimport { SandboxDriverNotRegisteredError, SandboxDriverRegistrationError } from \"./errors.ts\";\n\nexport interface DriverInfo {\n\treadonly name: SandboxDriver.Name;\n\treadonly kind: SandboxDriver.Registered[\"kind\"];\n\treadonly apiVersion: SandboxDriver.ApiVersion;\n\treadonly source: SandboxDriver.Source;\n\treadonly capabilities: SandboxDriver.Capabilities;\n\treadonly createConfig: JsonSchema.JsonSchema;\n}\n\nexport interface RegistryService {\n\treadonly names: ReadonlySet<SandboxDriver.Name>;\n\treadonly drivers: ReadonlyArray<DriverInfo>;\n\treadonly find: (name: SandboxDriver.Name) => Option.Option<SandboxDriver.Registered>;\n\treadonly get: (name: SandboxDriver.Name) => Effect.Effect<SandboxDriver.Registered, SandboxDriverNotRegisteredError>;\n\treadonly decodeCreateConfig: (\n\t\tname: SandboxDriver.Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n\treadonly decodeRuntimeConfig: (\n\t\tname: SandboxDriver.Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<\n\t\tSandboxDriver.RuntimeConfigBase,\n\t\tSandboxDriverNotRegisteredError | SandboxDriverRegistrationError\n\t>;\n\treadonly encodeRuntimeConfig: (\n\t\tname: SandboxDriver.Name,\n\t\tinput: SandboxDriver.RuntimeConfigBase,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n}\n\nexport class Registry extends Context.Service<Registry, RegistryService>()(\"@codeworksh/harness/sandbox/registry\") {}\n\nconst codecFailure = (driver: SandboxDriver.Name, reason: unknown) =>\n\tnew SandboxDriverRegistrationError({ driver, reason: String(reason) });\n\nconst reserved = new Set([\"local\", \"memory\", \"sqldb\", \"vercel\", \"daytona\"]);\n\nexport const make = (\n\tdrivers: ReadonlyArray<SandboxDriver.Registration>,\n): Effect.Effect<RegistryService, SandboxDriverRegistrationError> =>\n\tEffect.gen(function* () {\n\t\tconst entries = new Map<SandboxDriver.Name, SandboxDriver.Registered>();\n\t\tconst infos = new Map<SandboxDriver.Name, DriverInfo>();\n\n\t\tfor (const registration of drivers) {\n\t\t\tconst value = registration.registered;\n\t\t\tif (entries.has(value.name)) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: value.name,\n\t\t\t\t\treason: \"duplicate driver registration\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (reserved.has(value.name) && registration.source !== \"core\" && registration.source !== \"builtin\") {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: value.name,\n\t\t\t\t\treason: \"reserved driver name cannot be registered by a third-party package\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (value.capabilities.destroy && !value.capabilities.stop) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: value.name,\n\t\t\t\t\treason: \"destroy capability requires stop capability\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const operation of [\"inspect\", \"wake\", \"stop\", \"destroy\"] as const) {\n\t\t\t\tif (value.capabilities[operation] !== (value[operation] !== undefined)) {\n\t\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\t\tdriver: value.name,\n\t\t\t\t\t\treason: `${operation} capability does not match its lifecycle implementation`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (value.capabilities.reattach !== (value.runtimeConfigFor !== undefined)) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: value.name,\n\t\t\t\t\treason: \"reattach capability does not match runtimeConfigFor implementation\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst createConfig = yield* Effect.try({\n\t\t\t\ttry: () => Schema.toJsonSchemaDocument(value.createConfigCodec).schema,\n\t\t\t\tcatch: (reason) => codecFailure(value.name, reason),\n\t\t\t});\n\t\t\tconst erased = SandboxDriver.erase(value);\n\t\t\tentries.set(value.name, erased);\n\t\t\tinfos.set(value.name, {\n\t\t\t\tname: value.name,\n\t\t\t\tkind: value.kind,\n\t\t\t\tapiVersion: registration.apiVersion,\n\t\t\t\tsource: registration.source,\n\t\t\t\tcapabilities: { ...value.capabilities },\n\t\t\t\tcreateConfig,\n\t\t\t});\n\t\t}\n\n\t\tconst find = (name: SandboxDriver.Name) => Option.fromUndefinedOr(entries.get(name));\n\t\tconst get = (name: SandboxDriver.Name) =>\n\t\t\tEffect.fromOption(find(name)).pipe(\n\t\t\t\tEffect.mapError(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tnew SandboxDriverNotRegisteredError({\n\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\tregistered: [...entries.keys()].sort().slice(0, 5),\n\t\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\tconst decodeCreateConfig = Effect.fn(\"SandboxDriver.Registry.decodeCreateConfig\")(function* (\n\t\t\tname: SandboxDriver.Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst value = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(value.createConfigCodec)(input).pipe(\n\t\t\t\tEffect.mapError((error) => codecFailure(name, error)),\n\t\t\t);\n\t\t});\n\n\t\tconst decodeRuntimeConfig = Effect.fn(\"SandboxDriver.Registry.decodeRuntimeConfig\")(function* (\n\t\t\tname: SandboxDriver.Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst value = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(value.runtimeConfigCodec)(input).pipe(\n\t\t\t\tEffect.mapError((error) => codecFailure(name, error)),\n\t\t\t);\n\t\t});\n\n\t\tconst encodeRuntimeConfig = Effect.fn(\"SandboxDriver.Registry.encodeRuntimeConfig\")(function* (\n\t\t\tname: SandboxDriver.Name,\n\t\t\tinput: SandboxDriver.RuntimeConfigBase,\n\t\t) {\n\t\t\tconst value = yield* get(name);\n\t\t\treturn yield* Schema.encodeUnknownEffect(value.runtimeConfigCodec)(input).pipe(\n\t\t\t\tEffect.mapError((error) => codecFailure(name, error)),\n\t\t\t);\n\t\t});\n\n\t\treturn Registry.of({\n\t\t\tnames: new Set(entries.keys()),\n\t\t\tdrivers: [...infos.values()].sort((left, right) => left.name.localeCompare(right.name)),\n\t\t\tfind,\n\t\t\tget,\n\t\t\tdecodeCreateConfig,\n\t\t\tdecodeRuntimeConfig,\n\t\t\tencodeRuntimeConfig,\n\t\t});\n\t});\n\nexport const layer = (...drivers: ReadonlyArray<SandboxDriver.Registration>) => Layer.effect(Registry, make(drivers));\n\nexport * as SandboxDriverRegistry from \"./registry.ts\";\n","import { Effect, Layer, Stream } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { type ExecResult, Shell, ShellError, type ShellOptions } from \"./shell.ts\";\n\n/**\n * A {@link Shell} backed by real host processes.\n *\n * This is the execution half of the default local sandbox: just-bash is an\n * in-process emulator over the VFS and cannot run an external binary, so any\n * sandbox that must invoke real programs (`git`, package managers) needs this\n * instead.\n *\n * `execArgv` spawns the vector directly — no shell, so nothing in an argument\n * can be interpreted as syntax. `exec` keeps the single-string contract by\n * going through `sh -c`.\n */\n\nexport interface Options {\n\t/** Environment entries merged over the inherited environment. */\n\treadonly env?: Record<string, string>;\n\t/** Shell used to interpret the string form of `exec`. */\n\treadonly shell?: string;\n}\n\nconst DEFAULT_SHELL = \"sh\";\n\nexport const layer = (options: Options = {}): Layer.Layer<Shell, never, ChildProcessSpawner.ChildProcessSpawner> =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.gen(function* () {\n\t\t\t// Captured once so each call resolves to `R = never`.\n\t\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\n\t\t\t// No base directory is read here. The shell and the filesystem must\n\t\t\t// agree on what a relative path means, and they do — because both take\n\t\t\t// it from the same mount rather than each deriving one. Reading\n\t\t\t// `vfs.cwd()` was the same reasoning applied one layer too low: it made\n\t\t\t// the pairing true for one mount and unrepresentable for two.\n\t\t\tconst run = (label: string, file: string, args: ReadonlyArray<string>, opts?: ShellOptions) =>\n\t\t\t\tEffect.scoped(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst handle = yield* spawner.spawn(\n\t\t\t\t\t\t\tChildProcess.make(file, [...args], {\n\t\t\t\t\t\t\t\tcwd: opts?.cwd,\n\t\t\t\t\t\t\t\tenv: { ...options.env, ...opts?.env },\n\t\t\t\t\t\t\t\textendEnv: true,\n\t\t\t\t\t\t\t\tstdin: \"ignore\",\n\t\t\t\t\t\t\t\tstdout: \"pipe\",\n\t\t\t\t\t\t\t\tstderr: \"pipe\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// stdout and stderr are drained concurrently with the exit wait:\n\t\t\t\t\t\t// a process that fills a pipe buffer would otherwise deadlock.\n\t\t\t\t\t\treturn yield* Effect.all(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\texitCode: handle.exitCode,\n\t\t\t\t\t\t\t\tstdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),\n\t\t\t\t\t\t\t\tstderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ concurrency: \"unbounded\" },\n\t\t\t\t\t\t);\n\t\t\t\t\t}),\n\t\t\t\t).pipe(\n\t\t\t\t\tEffect.map((result): ExecResult => result),\n\t\t\t\t\tEffect.mapError((cause) => new ShellError({ command: label, cause })),\n\t\t\t\t);\n\n\t\t\tconst exec = Effect.fn(\"HostShell.exec\")((command: string, opts?: ShellOptions) =>\n\t\t\t\trun(command, options.shell ?? DEFAULT_SHELL, [\"-c\", command], opts),\n\t\t\t);\n\n\t\t\t// The vector is handed to the OS as-is; it never passes through a parser.\n\t\t\tconst execArgv = Effect.fn(\"HostShell.execArgv\")((argv: ReadonlyArray<string>, opts?: ShellOptions) =>\n\t\t\t\targv.length === 0\n\t\t\t\t\t? Effect.fail(new ShellError({ command: \"\", cause: new Error(\"execArgv requires a program\") }))\n\t\t\t\t\t: run(argv.join(\" \"), argv[0]!, argv.slice(1), opts),\n\t\t\t);\n\n\t\t\treturn Shell.of({ exec, execArgv });\n\t\t}),\n\t);\n\nexport * as HostExe from \"./host.ts\";\n","import { Effect, Option, Schema } from \"effect\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { SandboxInstanceRow } from \"../db/schema.sql.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Row-level access to `sandbox_instance`. Deliberately dumb: it persists and\n * reads instance rows and knows nothing about drivers, provisioning, reference\n * counts, or lifecycle rules. `Sandbox.Controller` is added on top of this and\n * owns all of that.\n *\n * The host is not in this table at all — `local` is reserved and `NULL` is its\n * only storage form (see `SandboxInstance.toColumn`), so nothing here has to\n * seed, ensure, or repair a row for a host-based session to exist.\n *\n * State transitions are single conditional statements verified by affected-row\n * count, never a read-then-write transaction: `SqlClient` begins DEFERRED, and\n * under WAL a mid-transaction lock upgrade can fail with `SQLITE_BUSY_SNAPSHOT`,\n * which `busy_timeout` does not retry.\n */\n\nexport interface RegisterInput {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: string;\n\treadonly kind: SandboxInstance.Kind;\n\treadonly ownership: SandboxInstance.Ownership;\n\treadonly status?: SandboxInstance.Status | undefined;\n\treadonly providerResourceId?: string | undefined;\n\treadonly runtimeConfig?: string | undefined;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface Interface {\n\treadonly find: (id: SandboxInstance.ID) => Effect.Effect<Option.Option<SandboxInstanceRow>>;\n\treadonly list: Effect.Effect<ReadonlyArray<SandboxInstanceRow>>;\n\t/** Insert if absent, leaving an existing row untouched. Idempotent. */\n\treadonly register: (input: RegisterInput) => Effect.Effect<SandboxInstanceRow>;\n\t/**\n\t * Compare-and-set the lifecycle state. Returns whether the row moved, so a\n\t * caller can distinguish \"I own this transition\" from \"someone beat me\".\n\t */\n\treadonly transition: (input: {\n\t\treadonly id: SandboxInstance.ID;\n\t\treadonly from: ReadonlyArray<SandboxInstance.Status>;\n\t\treadonly to: SandboxInstance.Status;\n\t}) => Effect.Effect<boolean>;\n}\n\nexport const make = Effect.gen(function* () {\n\tconst sql = yield* SqlClient.SqlClient;\n\n\tconst findRow = SqlSchema.findOneOption({\n\t\tRequest: SandboxInstance.ID,\n\t\tResult: SandboxInstanceRow,\n\t\texecute: (id) => sql`SELECT * FROM sandbox_instance WHERE id = ${id}`,\n\t});\n\n\tconst listRows = SqlSchema.findAll({\n\t\tRequest: Schema.Void,\n\t\tResult: SandboxInstanceRow,\n\t\texecute: () => sql`SELECT * FROM sandbox_instance ORDER BY created_at`,\n\t});\n\n\t// ON CONFLICT(id), not OR IGNORE: the ignore must cover exactly the\n\t// idempotency case. OR IGNORE would also swallow a violation of the\n\t// (driver, provider_resource_id) unique index — a new id aliasing an\n\t// existing namespace — and surface it as an inexplicable missing row.\n\tconst insertRow = SqlSchema.void({\n\t\tRequest: SandboxInstanceRow.insert,\n\t\texecute: (row) => sql`INSERT INTO sandbox_instance ${sql.insert(row)} ON CONFLICT(id) DO NOTHING`,\n\t});\n\n\tconst find = (id: SandboxInstance.ID) => findRow(id).pipe(Effect.orDie);\n\n\tconst list = listRows(undefined).pipe(Effect.orDie);\n\n\tconst register = Effect.fn(\"SandboxStore.register\")(function* (input: RegisterInput) {\n\t\tconst row = yield* SandboxInstanceRow.insert\n\t\t\t.makeEffect({\n\t\t\t\tid: input.id,\n\t\t\t\tdriver: input.driver,\n\t\t\t\tkind: input.kind,\n\t\t\t\tproviderResourceId: Option.fromUndefinedOr(input.providerResourceId),\n\t\t\t\truntimeConfig: Option.fromUndefinedOr(input.runtimeConfig),\n\t\t\t\townership: input.ownership,\n\t\t\t\tstatus: input.status ?? \"online\",\n\t\t\t\tproviderStatus: Option.none(),\n\t\t\t\t// stateObservedAt defaults to the injected Clock's now\n\t\t\t\tmetadata: Option.fromUndefinedOr(input.metadata as Record<string, string> | undefined),\n\t\t\t\tlastError: Option.none(),\n\t\t\t\tlastMountedAt: Option.none(),\n\t\t\t\tlastUnmountedAt: Option.none(),\n\t\t\t\tlastUsedAt: Option.none(),\n\t\t\t\tremovedAt: Option.none(),\n\t\t\t})\n\t\t\t.pipe(Effect.orDie);\n\n\t\tyield* insertRow(row).pipe(Effect.orDie);\n\n\t\tconst stored = yield* find(input.id);\n\t\tif (Option.isNone(stored))\n\t\t\treturn yield* Effect.die(new Error(`sandbox instance insert did not persist: ${input.id}`));\n\t\treturn stored.value;\n\t});\n\n\tconst transition = Effect.fn(\"SandboxStore.transition\")(function* (input: {\n\t\treadonly id: SandboxInstance.ID;\n\t\treadonly from: ReadonlyArray<SandboxInstance.Status>;\n\t\treadonly to: SandboxInstance.Status;\n\t}) {\n\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t// RETURNING makes \"did I win this transition?\" part of the same statement.\n\t\t// Re-reading afterwards would answer a different question, since another\n\t\t// writer may have moved the row in between.\n\t\tconst moved = yield* sql`\n\t\t\tUPDATE sandbox_instance\n\t\t\tSET status = ${input.to}, updated_at = ${now}\n\t\t\tWHERE id = ${input.id} AND ${sql.in(\"status\", input.from)}\n\t\t\tRETURNING id\n\t\t`.pipe(Effect.orDie);\n\t\treturn moved.length > 0;\n\t});\n\n\treturn { find, list, register, transition } satisfies Interface;\n});\n\nexport * as SandboxStore from \"./store.ts\";\n","import { Cause, Context, DateTime, type Duration, Effect, Layer, LayerMap, Option, Schema, Semaphore } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\nimport { SandboxInstanceRow } from \"../db/schema.sql.ts\";\nimport { Space } from \"../space/space.ts\";\nimport { SandboxDriver } from \"./driver.ts\";\nimport {\n\tproviderError,\n\tproviderErrorIsNotFound,\n\tSandboxBusyError,\n\ttype SandboxCreateError,\n\ttype SandboxDestroyError,\n\ttype SandboxDriverNotRegisteredError,\n\tSandboxDriverRegistrationError,\n\ttype SandboxMountError,\n\tSandboxMustBeStoppedError,\n\tSandboxNotFoundError,\n\tSandboxProviderError,\n\ttype SandboxReadError,\n\ttype SandboxRefreshError,\n\ttype SandboxRegisterError,\n\tSandboxRemovedError,\n\ttype SandboxStopError,\n\tSandboxTransitionConflictError,\n\tSandboxUnavailError,\n\tSandboxUnsupportedError,\n\ttype SandboxWakeError,\n\tsanitizeError,\n} from \"./errors.ts\";\nimport { SandboxFileSystem } from \"./fs/filesystem.ts\";\nimport { EnvNodeJSDefault } from \"./fs/nodejs.ts\";\nimport { Local } from \"./fs/vfs.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\nimport { SandboxDriverRegistry } from \"./registry.ts\";\nimport { HostExe } from \"./shell/host.ts\";\nimport { withCwd as shellWithCwd } from \"./shell/shell.ts\";\nimport { SandboxStore } from \"./store.ts\";\n\nexport interface CreateInput<CreateConfig, RuntimeConfig extends SandboxDriver.RuntimeConfigBase> {\n\treadonly driver: SandboxDriver.Definition<CreateConfig, RuntimeConfig>;\n\treadonly config: CreateConfig;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n\t/** Reserved for isolated test/script constructors that already own an id. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n}\n\nexport interface RegisterInput<CreateConfig, RuntimeConfig extends SandboxDriver.RuntimeConfigBase> {\n\treadonly driver: SandboxDriver.Definition<CreateConfig, RuntimeConfig>;\n\treadonly providerResourceId: string;\n\treadonly runtimeConfig?: Partial<RuntimeConfig> | undefined;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface MountOptions {\n\t/** Absolute, or relative to RuntimeConfig.defaultCwd. */\n\treadonly cwd?: string;\n}\n\nexport interface DestroyOptions {\n\t/** Skip only this process's live-reference guard. */\n\treadonly force?: boolean;\n}\n\nexport interface ListInput {\n\treadonly driver?: SandboxDriver.Name;\n\treadonly status?: SandboxInstance.Status;\n\treadonly usage?: SandboxInstance.Usage;\n}\n\nexport interface Interface {\n\treadonly create: <CreateConfig, RuntimeConfig extends SandboxDriver.RuntimeConfigBase>(\n\t\tinput: CreateInput<CreateConfig, RuntimeConfig>,\n\t) => Effect.Effect<SandboxInstance.Info, SandboxCreateError>;\n\treadonly createAndMount: <CreateConfig, RuntimeConfig extends SandboxDriver.RuntimeConfigBase>(\n\t\tinput: CreateInput<CreateConfig, RuntimeConfig>,\n\t\toptions?: MountOptions,\n\t) => SandboxIO.Layer<SandboxCreateError | SandboxMountError>;\n\treadonly register: <CreateConfig, RuntimeConfig extends SandboxDriver.RuntimeConfigBase>(\n\t\tinput: RegisterInput<CreateConfig, RuntimeConfig>,\n\t) => Effect.Effect<SandboxInstance.Info, SandboxRegisterError>;\n\treadonly get: (id: SandboxInstance.ID) => Effect.Effect<Option.Option<SandboxInstance.Info>, SandboxReadError>;\n\treadonly list: (input?: ListInput) => Effect.Effect<ReadonlyArray<SandboxInstance.Info>, SandboxReadError>;\n\t/** Resolve a session cwd without mounting or waking the sandbox. */\n\treadonly resolveCwd: (\n\t\tid?: SandboxInstance.ID,\n\t\toverride?: string,\n\t) => Effect.Effect<SandboxDriver.AbsolutePath, SandboxMountError>;\n\treadonly refresh: (id: SandboxInstance.ID) => Effect.Effect<SandboxInstance.Info, SandboxRefreshError>;\n\treadonly mount: (id?: SandboxInstance.ID, options?: MountOptions) => SandboxIO.Layer<SandboxMountError>;\n\treadonly withMount: <A, E, R>(\n\t\tid: SandboxInstance.ID | undefined,\n\t\tuse: Effect.Effect<A, E, R>,\n\t\toptions?: MountOptions,\n\t) => Effect.Effect<A, E | SandboxMountError, Exclude<R, SandboxIO.Provides>>;\n\treadonly wake: (id: SandboxInstance.ID) => Effect.Effect<SandboxInstance.Info, SandboxWakeError>;\n\treadonly stop: (id: SandboxInstance.ID) => Effect.Effect<SandboxInstance.Info, SandboxStopError>;\n\treadonly destroy: (id: SandboxInstance.ID, options?: DestroyOptions) => Effect.Effect<void, SandboxDestroyError>;\n}\n\nexport class Controller extends Context.Service<Controller, Interface>()(\n\t\"@codeworksh/harness/sandbox/control/Controller\",\n) {}\n\nexport interface Options {\n\treadonly transportIdleTimeToLive?: Duration.Input;\n\treadonly provisioningTimeoutMs?: number;\n}\n\nconst hostTransport = Layer.provide(Layer.merge(Layer.fresh(Local.layer), HostExe.layer()), EnvNodeJSDefault.layer());\n\nconst asDate = DateTime.toDateUtc;\nconst optionalDate = Option.map(DateTime.toDateUtc);\nconst MetadataJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));\nconst PersistedErrorJson = Schema.fromJsonString(SandboxInstance.PersistedError);\nconst UnknownJson = Schema.fromJsonString(Schema.Unknown);\nconst decodeUnknownJson = Schema.decodeEffect(UnknownJson);\nconst encodeUnknownJson = Schema.encodeEffect(UnknownJson);\nconst encodeMetadataJson = Schema.encodeEffect(MetadataJson);\nconst encodePersistedErrorJson = Schema.encodeEffect(PersistedErrorJson);\n\n/** Schema-aware runtime check; `instanceof` does not survive schema decoding. */\nconst isSandboxProviderError = Schema.is(SandboxProviderError);\n\nconst parseJson = (driver: SandboxDriver.Name, operation: string, value: string) =>\n\tdecodeUnknownJson(value).pipe(Effect.mapError((cause) => providerError({ driver, operation, cause })));\n\nexport const make = Effect.fn(\"Sandbox.Controller.make\")(function* (options: Options = {}) {\n\tconst sql = yield* SqlClient.SqlClient;\n\tconst registry = yield* SandboxDriverRegistry.Registry;\n\tconst store = yield* SandboxStore.make;\n\tconst gate = yield* Semaphore.make(1);\n\tconst refs = new Map<SandboxInstance.ID, number>();\n\tconst hostDefaultCwd = process.cwd();\n\tconst hostCreatedAt = asDate(yield* DateTime.now);\n\n\tconst refCount = (id: SandboxInstance.ID) => refs.get(id) ?? 0;\n\tconst usage = (id: SandboxInstance.ID, count = refCount(id)): SandboxInstance.Usage =>\n\t\tid === SandboxInstance.ID.local ? \"pinned\" : count > 0 ? \"busy\" : \"idle\";\n\tinterface Lease {\n\t\theld: boolean;\n\t\tmounted: boolean;\n\t}\n\n\tconst acquireLease = (id: SandboxInstance.ID, lease: Lease) =>\n\t\tgate.withPermits(1)(\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst wasIdle = refCount(id) === 0;\n\t\t\t\trefs.set(id, refCount(id) + 1);\n\t\t\t\tlease.held = true;\n\t\t\t\treturn wasIdle;\n\t\t\t}),\n\t\t);\n\n\tconst releaseLease = (id: SandboxInstance.ID, lease: Lease) =>\n\t\tEffect.gen(function* () {\n\t\t\tif (!lease.held) return;\n\t\t\tyield* gate.withPermits(1)(\n\t\t\t\tEffect.sync(() => {\n\t\t\t\t\tconst next = Math.max(0, refCount(id) - 1);\n\t\t\t\t\tif (next === 0) refs.delete(id);\n\t\t\t\t\telse refs.set(id, next);\n\t\t\t\t\tlease.held = false;\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (!lease.mounted) return;\n\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\tyield* sql`\n\t\t\t\tUPDATE sandbox_instance\n\t\t\t\tSET last_unmounted_at = ${now}, last_used_at = ${now}, updated_at = ${now}\n\t\t\t\tWHERE id = ${id}\n\t\t\t`.pipe(Effect.orDie);\n\t\t});\n\n\tconst toInfo = (row: SandboxInstanceRow): SandboxInstance.Info => {\n\t\tconst count = refCount(row.id);\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tdriver: SandboxDriver.Name.make(row.driver),\n\t\t\tkind: row.kind,\n\t\t\tproviderResourceId: row.providerResourceId,\n\t\t\townership: row.ownership,\n\t\t\tstatus: row.status,\n\t\t\tusage: usage(row.id, count),\n\t\t\trefCount: count,\n\t\t\tproviderStatus: row.providerStatus,\n\t\t\tmetadata: Option.getOrElse(row.metadata, () => ({})),\n\t\t\tlastError: row.lastError,\n\t\t\tcreatedAt: asDate(row.createdAt),\n\t\t\tupdatedAt: asDate(row.updatedAt),\n\t\t\tstateObservedAt: asDate(row.stateObservedAt),\n\t\t\tlastMountedAt: optionalDate(row.lastMountedAt),\n\t\t\tlastUnmountedAt: optionalDate(row.lastUnmountedAt),\n\t\t\tlastUsedAt: optionalDate(row.lastUsedAt),\n\t\t\tremovedAt: optionalDate(row.removedAt),\n\t\t};\n\t};\n\n\tconst hostInfo = (): SandboxInstance.Info => ({\n\t\tid: SandboxInstance.ID.local,\n\t\tdriver: SandboxDriver.Name.make(\"local\"),\n\t\tkind: \"local\",\n\t\tproviderResourceId: Option.none(),\n\t\townership: \"external\",\n\t\tstatus: \"online\",\n\t\tusage: \"pinned\",\n\t\trefCount: 0,\n\t\tproviderStatus: Option.none(),\n\t\tmetadata: {},\n\t\tlastError: Option.none(),\n\t\tcreatedAt: hostCreatedAt,\n\t\tupdatedAt: hostCreatedAt,\n\t\tstateObservedAt: hostCreatedAt,\n\t\tlastMountedAt: Option.none(),\n\t\tlastUnmountedAt: Option.none(),\n\t\tlastUsedAt: Option.none(),\n\t\tremovedAt: Option.none(),\n\t});\n\n\tconst findRow = (id: SandboxInstance.ID) => store.find(id);\n\tconst requireRow = Effect.fn(\"Sandbox.Controller.requireRow\")(function* (id: SandboxInstance.ID) {\n\t\tconst found = yield* findRow(id);\n\t\tif (Option.isNone(found)) return yield* new SandboxNotFoundError({ id });\n\t\treturn found.value;\n\t});\n\n\tconst reload = Effect.fn(\"Sandbox.Controller.reload\")(function* (id: SandboxInstance.ID) {\n\t\treturn toInfo(yield* requireRow(id));\n\t});\n\n\tconst runtime = Effect.fn(\"Sandbox.Controller.runtime\")(function* (row: SandboxInstanceRow, operation: string) {\n\t\tconst driverName = SandboxDriver.Name.make(row.driver);\n\t\tconst driver = yield* registry.get(driverName);\n\t\tif (driver.kind !== row.kind) {\n\t\t\treturn yield* providerError({\n\t\t\t\tdriver: driverName,\n\t\t\t\toperation,\n\t\t\t\tcause: new Error(`registered kind ${driver.kind} conflicts with persisted kind ${row.kind}`),\n\t\t\t});\n\t\t}\n\t\tif (Option.isNone(row.runtimeConfig)) {\n\t\t\treturn yield* providerError({\n\t\t\t\tdriver: driverName,\n\t\t\t\toperation,\n\t\t\t\tcause: new Error(`sandbox runtime config is missing: ${row.id}`),\n\t\t\t});\n\t\t}\n\t\tconst decoded = yield* parseJson(driverName, operation, row.runtimeConfig.value);\n\t\tconst runtimeConfig = yield* registry\n\t\t\t.decodeRuntimeConfig(driverName, decoded)\n\t\t\t.pipe(Effect.mapError((cause) => providerError({ driver: driverName, operation, cause })));\n\t\treturn {\n\t\t\tdriver,\n\t\t\tinput: {\n\t\t\t\tid: row.id,\n\t\t\t\tproviderResourceId: row.providerResourceId,\n\t\t\t\truntimeConfig,\n\t\t\t},\n\t\t};\n\t});\n\n\tconst updateObservation = Effect.fn(\"Sandbox.Controller.updateObservation\")(function* (input: {\n\t\treadonly id: SandboxInstance.ID;\n\t\treadonly status: SandboxInstance.Status;\n\t\treadonly providerStatus?: string | undefined;\n\t\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n\t\treadonly lastError?: SandboxInstance.PersistedError | undefined;\n\t\treadonly clearError?: boolean | undefined;\n\t}) {\n\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\tconst metadata =\n\t\t\tinput.metadata === undefined ? null : yield* encodeMetadataJson(input.metadata).pipe(Effect.orDie);\n\t\tconst lastError =\n\t\t\tinput.clearError === true\n\t\t\t\t? null\n\t\t\t\t: input.lastError === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: yield* encodePersistedErrorJson(input.lastError).pipe(Effect.orDie);\n\t\tyield* sql`\n\t\t\tUPDATE sandbox_instance\n\t\t\tSET\n\t\t\t\tstatus = ${input.status},\n\t\t\t\tprovider_status = ${input.providerStatus ?? null},\n\t\t\t\tstate_observed_at = ${now},\n\t\t\t\tmetadata = COALESCE(${metadata}, metadata),\n\t\t\t\tlast_error = CASE\n\t\t\t\t\tWHEN ${input.clearError === true ? 1 : 0} = 1 THEN NULL\n\t\t\t\t\tWHEN ${lastError ?? null} IS NOT NULL THEN ${lastError ?? null}\n\t\t\t\t\tELSE last_error\n\t\t\t\tEND,\n\t\t\t\tupdated_at = ${now}\n\t\t\tWHERE id = ${input.id}\n\t\t`.pipe(Effect.orDie);\n\t});\n\n\tconst markUnavailable = Effect.fn(\"Sandbox.Controller.markUnavailable\")(function* (\n\t\tid: SandboxInstance.ID,\n\t\terror: SandboxProviderError,\n\t) {\n\t\tyield* updateObservation({\n\t\t\tid,\n\t\t\tstatus: \"unavail\",\n\t\t\tlastError: error.sanitized,\n\t\t});\n\t\treturn yield* new SandboxUnavailError({ id, reason: error.sanitized.message });\n\t});\n\n\tconst persistProviderFailure = Effect.fn(\"Sandbox.Controller.persistProviderFailure\")(function* (\n\t\tid: SandboxInstance.ID,\n\t\tstatus: SandboxInstance.Status,\n\t\terror: SandboxProviderError,\n\t) {\n\t\tyield* updateObservation({ id, status, lastError: error.sanitized });\n\t\treturn yield* error;\n\t});\n\n\ttype TransportError = SandboxNotFoundError | SandboxDriverNotRegisteredError | SandboxProviderError;\n\n\tconst transportLayer = (\n\t\tid: SandboxInstance.ID,\n\t): Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, TransportError> =>\n\t\tid === SandboxInstance.ID.local\n\t\t\t? hostTransport\n\t\t\t: Layer.unwrap(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst row = yield* requireRow(id);\n\t\t\t\t\t\tconst attached = yield* runtime(row, \"attach\");\n\t\t\t\t\t\treturn attached.driver.attach(attached.input);\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\tconst transports = yield* LayerMap.make(transportLayer, {\n\t\tidleTimeToLive: options.transportIdleTimeToLive ?? \"30 seconds\",\n\t});\n\n\t// A registry configured with the wrong kind cannot safely interpret existing\n\t// rows. Fail the process layer before any lifecycle operation runs.\n\tfor (const row of yield* store.list) {\n\t\tconst registered = registry.find(SandboxDriver.Name.make(row.driver));\n\t\tif (Option.isSome(registered) && registered.value.kind !== row.kind) {\n\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\tdriver: registered.value.name,\n\t\t\t\treason: `registered kind ${registered.value.kind} conflicts with persisted kind ${row.kind}`,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst startupNow = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\tconst provisioningCutoff = startupNow - (options.provisioningTimeoutMs ?? 300_000);\n\tconst creationInterrupted = yield* encodePersistedErrorJson({\n\t\tname: \"SandboxCreationInterrupted\",\n\t\tmessage: \"sandbox creation was interrupted before provisioning completed\",\n\t}).pipe(Effect.orDie);\n\tyield* sql`\n\t\t\tUPDATE sandbox_instance\n\t\t\tSET\n\t\t\t\tstatus = 'faulted',\n\t\t\t\tlast_error = ${creationInterrupted},\n\t\t\tupdated_at = ${startupNow}\n\t\tWHERE status = 'provisioning' AND state_observed_at < ${provisioningCutoff}\n\t`.pipe(Effect.orDie);\n\n\tconst get: Interface[\"get\"] = (id) =>\n\t\tid === SandboxInstance.ID.local ? Effect.succeedSome(hostInfo()) : Effect.map(findRow(id), Option.map(toInfo));\n\n\tconst list: Interface[\"list\"] = (input = {}) =>\n\t\tEffect.map(store.list, (rows) =>\n\t\t\t[hostInfo(), ...rows.map(toInfo)].filter(\n\t\t\t\t(info) =>\n\t\t\t\t\t(input.driver === undefined || info.driver === input.driver) &&\n\t\t\t\t\t(input.status === undefined || info.status === input.status) &&\n\t\t\t\t\t(input.usage === undefined || info.usage === input.usage),\n\t\t\t),\n\t\t);\n\n\tconst resolveCwd: Interface[\"resolveCwd\"] = Effect.fn(\"Sandbox.Controller.resolveCwd\")(function* (\n\t\tid = SandboxInstance.ID.local,\n\t\toverride,\n\t) {\n\t\tif (id === SandboxInstance.ID.local) {\n\t\t\treturn SandboxDriver.AbsolutePath.make(SandboxIO.resolveMountCwd(hostDefaultCwd, override));\n\t\t}\n\t\tconst row = yield* requireRow(id);\n\t\tif (row.status === \"removed\") {\n\t\t\treturn yield* new SandboxRemovedError({ id, removedAt: Option.getOrUndefined(row.removedAt) });\n\t\t}\n\t\tif (row.status === \"unavail\") {\n\t\t\treturn yield* new SandboxUnavailError({ id, reason: \"driver resource is unavailable\" });\n\t\t}\n\t\tconst attached = yield* runtime(row, \"resolveCwd\");\n\t\treturn SandboxDriver.AbsolutePath.make(\n\t\t\tSandboxIO.resolveMountCwd(attached.input.runtimeConfig.defaultCwd, override),\n\t\t);\n\t});\n\n\tconst create: Interface[\"create\"] = Effect.fn(\"Sandbox.Controller.create\")(function* (input) {\n\t\tconst driver = yield* registry.get(input.driver.name);\n\t\tconst config = yield* registry.decodeCreateConfig(input.driver.name, input.config);\n\t\tconst id = input.instanceId ?? SandboxInstance.ID.create();\n\t\tif (id === SandboxInstance.ID.local || Option.isSome(yield* store.find(id))) {\n\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\tdriver: driver.name,\n\t\t\t\treason: `sandbox instance id is already registered or reserved: ${id}`,\n\t\t\t});\n\t\t}\n\t\tyield* store.register({\n\t\t\tid,\n\t\t\tdriver: driver.name,\n\t\t\tkind: driver.kind,\n\t\t\townership: \"managed\",\n\t\t\tstatus: \"provisioning\",\n\t\t\tmetadata: input.metadata,\n\t\t});\n\n\t\tconst provisioned = yield* driver\n\t\t\t.create({ instanceId: id, config })\n\t\t\t.pipe(Effect.catch((error) => persistProviderFailure(id, \"faulted\", error)));\n\t\tconst finalize = Effect.gen(function* () {\n\t\t\tconst encoded = yield* registry.encodeRuntimeConfig(driver.name, provisioned.runtimeConfig);\n\t\t\tconst runtimeConfig = yield* encodeUnknownJson(encoded).pipe(\n\t\t\t\tEffect.mapError((cause) => providerError({ driver: driver.name, operation: \"create\", cause })),\n\t\t\t);\n\t\t\tconst metadata = { ...input.metadata, ...provisioned.metadata };\n\t\t\tconst persistedMetadata =\n\t\t\t\tObject.keys(metadata).length === 0 ? null : yield* encodeMetadataJson(metadata).pipe(Effect.orDie);\n\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\tyield* sql`\n\t\t\t\tUPDATE sandbox_instance\n\t\t\t\tSET\n\t\t\t\t\tprovider_resource_id = ${provisioned.providerResourceId ?? null},\n\t\t\t\t\truntime_config = ${runtimeConfig},\n\t\t\t\t\tstatus = 'online',\n\t\t\t\t\tprovider_status = ${provisioned.providerStatus ?? null},\n\t\t\t\t\tstate_observed_at = ${now},\n\t\t\t\t\tmetadata = ${persistedMetadata},\n\t\t\t\t\tlast_error = NULL,\n\t\t\t\t\tupdated_at = ${now}\n\t\t\t\tWHERE id = ${id} AND status = 'provisioning'\n\t\t\t`.pipe(Effect.orDie);\n\t\t\treturn yield* reload(id).pipe(Effect.orDie);\n\t\t});\n\n\t\treturn yield* finalize.pipe(\n\t\t\tEffect.catchCause((cause) => {\n\t\t\t\tconst compensate =\n\t\t\t\t\tdriver.destroy === undefined\n\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t: driver\n\t\t\t\t\t\t\t\t.destroy({\n\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\tproviderResourceId: Option.fromUndefinedOr(provisioned.providerResourceId),\n\t\t\t\t\t\t\t\t\truntimeConfig: provisioned.runtimeConfig,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.pipe(\n\t\t\t\t\t\t\t\t\tEffect.catch((error) =>\n\t\t\t\t\t\t\t\t\t\tEffect.logError(\"Failed to compensate sandbox creation\", error).pipe(\n\t\t\t\t\t\t\t\t\t\t\tEffect.annotateLogs({ sandboxInstanceId: id, driver: driver.name }),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\treturn compensate.pipe(\n\t\t\t\t\tEffect.andThen(\n\t\t\t\t\t\tupdateObservation({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tstatus: \"faulted\",\n\t\t\t\t\t\t\tlastError: sanitizeError(Cause.squash(cause)),\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.andThen(Effect.failCause(cause)),\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\t});\n\n\tconst register: Interface[\"register\"] = Effect.fn(\"Sandbox.Controller.register\")(function* (input) {\n\t\tconst driver = yield* registry.get(input.driver.name);\n\t\tconst existing = (yield* store.list).find(\n\t\t\t(row) =>\n\t\t\t\trow.driver === driver.name &&\n\t\t\t\tOption.getOrUndefined(row.providerResourceId) === input.providerResourceId &&\n\t\t\t\trow.status !== \"removed\",\n\t\t);\n\t\tif (driver.runtimeConfigFor === undefined) {\n\t\t\treturn yield* new SandboxUnsupportedError({\n\t\t\t\tdriver: driver.name,\n\t\t\t\toperation: \"register\",\n\t\t\t});\n\t\t}\n\t\tconst runtimeConfig = yield* driver.runtimeConfigFor({\n\t\t\tproviderResourceId: input.providerResourceId,\n\t\t\toverrides: input.runtimeConfig as Readonly<Record<string, unknown>> | undefined,\n\t\t});\n\t\tconst encoded = yield* registry.encodeRuntimeConfig(driver.name, runtimeConfig);\n\t\tconst persisted = yield* encodeUnknownJson(encoded).pipe(\n\t\t\tEffect.mapError((cause) => providerError({ driver: driver.name, operation: \"register\", cause })),\n\t\t);\n\n\t\tif (existing !== undefined) {\n\t\t\tif (existing.ownership !== \"external\" || existing.kind !== driver.kind) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.name,\n\t\t\t\t\treason: `resource is already registered with incompatible identity: ${input.providerResourceId}`,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (Option.isSome(existing.runtimeConfig) && existing.runtimeConfig.value !== persisted) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.name,\n\t\t\t\t\treason: `resource is already registered with different runtime config: ${input.providerResourceId}`,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn toInfo(existing);\n\t\t}\n\n\t\tconst id = SandboxInstance.ID.create();\n\t\tyield* store.register({\n\t\t\tid,\n\t\t\tdriver: driver.name,\n\t\t\tkind: driver.kind,\n\t\t\townership: \"external\",\n\t\t\tstatus: \"online\",\n\t\t\tproviderResourceId: input.providerResourceId,\n\t\t\truntimeConfig: persisted,\n\t\t\tmetadata: input.metadata,\n\t\t});\n\t\treturn yield* reload(id).pipe(Effect.orDie);\n\t});\n\n\tconst mountLayer = (id = SandboxInstance.ID.local, mountOptions: MountOptions = {}, reserved?: Lease) =>\n\t\tLayer.unwrap(\n\t\t\tEffect.gen(function* () {\n\t\t\t\tlet identity: SandboxIO.Identity;\n\t\t\t\tlet invalidateBeforeAttach = false;\n\t\t\t\tconst lease: Lease = reserved ?? { held: false, mounted: false };\n\n\t\t\t\tif (id === SandboxInstance.ID.local) {\n\t\t\t\t\tidentity = {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tdriver: SandboxDriver.Name.make(\"local\"),\n\t\t\t\t\t\tkind: \"local\",\n\t\t\t\t\t\tcwd: SandboxIO.resolveMountCwd(hostDefaultCwd, mountOptions.cwd),\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tconst row = yield* requireRow(id);\n\t\t\t\t\tif (row.status === \"removed\") {\n\t\t\t\t\t\treturn yield* new SandboxRemovedError({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tremovedAt: Option.getOrUndefined(row.removedAt),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (row.status === \"unavail\") {\n\t\t\t\t\t\treturn yield* new SandboxUnavailError({ id, reason: \"driver resource is unavailable\" });\n\t\t\t\t\t}\n\t\t\t\t\tif (!SandboxInstance.isMountable(row.status)) {\n\t\t\t\t\t\treturn yield* new SandboxUnavailError({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\treason: `sandbox is not mountable while ${row.status}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tinvalidateBeforeAttach = row.status !== \"online\";\n\t\t\t\t\tconst attached = yield* runtime(row, \"mount\");\n\t\t\t\t\tidentity = {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tdriver: attached.driver.name,\n\t\t\t\t\t\tkind: row.kind,\n\t\t\t\t\t\tcwd: SandboxIO.resolveMountCwd(attached.input.runtimeConfig.defaultCwd, mountOptions.cwd),\n\t\t\t\t\t};\n\n\t\t\t\t\tconst wasIdle = lease.held\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: yield* gate.withPermits(1)(\n\t\t\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\t\t\tconst latest = yield* requireRow(id);\n\t\t\t\t\t\t\t\t\tif (latest.status === \"removed\") {\n\t\t\t\t\t\t\t\t\t\treturn yield* new SandboxRemovedError({\n\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\tremovedAt: Option.getOrUndefined(latest.removedAt),\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (latest.status === \"unavail\" || !SandboxInstance.isMountable(latest.status)) {\n\t\t\t\t\t\t\t\t\t\treturn yield* new SandboxUnavailError({\n\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\treason: `sandbox is not mountable while ${latest.status}`,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst idle = refCount(id) === 0;\n\t\t\t\t\t\t\t\t\trefs.set(id, refCount(id) + 1);\n\t\t\t\t\t\t\t\t\tlease.held = true;\n\t\t\t\t\t\t\t\t\treturn idle;\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\tif (reserved === undefined) yield* Effect.addFinalizer(() => releaseLease(id, lease));\n\n\t\t\t\t\tif (wasIdle && invalidateBeforeAttach) yield* transports.invalidate(id);\n\t\t\t\t}\n\n\t\t\t\tconst handleTransportError = (error: TransportError): Effect.Effect<never, SandboxMountError> => {\n\t\t\t\t\tif (isSandboxProviderError(error) && providerErrorIsNotFound(error)) {\n\t\t\t\t\t\treturn markUnavailable(id, error);\n\t\t\t\t\t}\n\t\t\t\t\tif (isSandboxProviderError(error)) return persistProviderFailure(id, \"faulted\", error);\n\t\t\t\t\treturn Effect.fail(error);\n\t\t\t\t};\n\n\t\t\t\tconst context = yield* transports.contextEffect(id).pipe(\n\t\t\t\t\tEffect.catch((error) => {\n\t\t\t\t\t\tif (isSandboxProviderError(error) && providerErrorIsNotFound(error)) {\n\t\t\t\t\t\t\treturn markUnavailable(id, error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isSandboxProviderError(error)) {\n\t\t\t\t\t\t\t// A persisted `online` status can outlive a provider session\n\t\t\t\t\t\t\t// URL. Drop the failed entry and attach once more before\n\t\t\t\t\t\t\t// recording a fault; never create a replacement namespace.\n\t\t\t\t\t\t\treturn transports\n\t\t\t\t\t\t\t\t.invalidate(id)\n\t\t\t\t\t\t\t\t.pipe(Effect.andThen(transports.contextEffect(id)), Effect.catch(handleTransportError));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Effect.fail(error);\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tconst fs = Context.get(context, SandboxIO.FileSystem);\n\t\t\t\tconst shell = Context.get(context, SandboxIO.Shell);\n\t\t\t\tlease.mounted = true;\n\n\t\t\t\tif (id !== SandboxInstance.ID.local) {\n\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\tUPDATE sandbox_instance\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tstatus = 'online',\n\t\t\t\t\t\t\tlast_error = NULL,\n\t\t\t\t\t\t\tlast_mounted_at = ${now},\n\t\t\t\t\t\t\tlast_used_at = ${now},\n\t\t\t\t\t\t\tstate_observed_at = ${now},\n\t\t\t\t\t\t\tupdated_at = ${now}\n\t\t\t\t\t\tWHERE id = ${id}\n\t\t\t\t\t`.pipe(Effect.orDie);\n\t\t\t\t}\n\n\t\t\t\treturn Layer.mergeAll(\n\t\t\t\t\tLayer.succeed(SandboxIO.Current, identity),\n\t\t\t\t\tLayer.succeed(SandboxIO.FileSystem, SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t\t\t\tLayer.succeed(SandboxIO.Shell, shellWithCwd(shell, identity.cwd)),\n\t\t\t\t);\n\t\t\t}),\n\t\t);\n\n\tconst mount: Interface[\"mount\"] = (id, mountOptions) => mountLayer(id, mountOptions);\n\n\tconst withMount: Interface[\"withMount\"] = (id, use, mountOptions) =>\n\t\tuse.pipe(Effect.provide(mount(id, mountOptions)), Effect.scoped);\n\n\tconst refresh: Interface[\"refresh\"] = Effect.fn(\"Sandbox.Controller.refresh\")(function* (id) {\n\t\tif (id === SandboxInstance.ID.local) {\n\t\t\treturn yield* new SandboxUnsupportedError({\n\t\t\t\tid,\n\t\t\t\tdriver: \"local\",\n\t\t\t\toperation: \"refresh\",\n\t\t\t});\n\t\t}\n\t\tconst row = yield* requireRow(id);\n\t\tconst attached = yield* runtime(row, \"inspect\");\n\t\tif (attached.driver.inspect === undefined) {\n\t\t\treturn yield* new SandboxUnsupportedError({\n\t\t\t\tid,\n\t\t\t\tdriver: attached.driver.name,\n\t\t\t\toperation: \"refresh\",\n\t\t\t});\n\t\t}\n\t\tconst observed = yield* attached.driver\n\t\t\t.inspect(attached.input)\n\t\t\t.pipe(\n\t\t\t\tEffect.catch((error): Effect.Effect<never, SandboxProviderError | SandboxUnavailError> =>\n\t\t\t\t\tproviderErrorIsNotFound(error)\n\t\t\t\t\t\t? markUnavailable(id, error)\n\t\t\t\t\t\t: persistProviderFailure(id, \"faulted\", error),\n\t\t\t\t),\n\t\t\t);\n\t\tyield* updateObservation({\n\t\t\tid,\n\t\t\tstatus: observed.status,\n\t\t\tproviderStatus: observed.providerStatus,\n\t\t\tmetadata: observed.metadata,\n\t\t\tclearError: true,\n\t\t});\n\t\treturn yield* reload(id);\n\t});\n\n\tconst wake: Interface[\"wake\"] = Effect.fn(\"Sandbox.Controller.wake\")(function* (id) {\n\t\tif (id === SandboxInstance.ID.local) return hostInfo();\n\t\tconst row = yield* requireRow(id);\n\t\tif (row.status === \"removed\") {\n\t\t\treturn yield* new SandboxRemovedError({\n\t\t\t\tid,\n\t\t\t\tremovedAt: Option.getOrUndefined(row.removedAt),\n\t\t\t});\n\t\t}\n\t\tconst attached = yield* runtime(row, \"wake\");\n\t\tif (!attached.driver.capabilities.wake || attached.driver.wake === undefined) {\n\t\t\treturn yield* new SandboxUnsupportedError({\n\t\t\t\tid,\n\t\t\t\tdriver: attached.driver.name,\n\t\t\t\toperation: \"wake\",\n\t\t\t});\n\t\t}\n\t\tif (refCount(id) === 0) yield* transports.invalidate(id);\n\t\tconst observed = yield* attached.driver\n\t\t\t.wake(attached.input)\n\t\t\t.pipe(\n\t\t\t\tEffect.catch((error): Effect.Effect<never, SandboxProviderError | SandboxUnavailError> =>\n\t\t\t\t\tproviderErrorIsNotFound(error)\n\t\t\t\t\t\t? markUnavailable(id, error)\n\t\t\t\t\t\t: persistProviderFailure(id, \"faulted\", error),\n\t\t\t\t),\n\t\t\t);\n\t\tyield* updateObservation({\n\t\t\tid,\n\t\t\tstatus: observed.status,\n\t\t\tproviderStatus: observed.providerStatus,\n\t\t\tmetadata: observed.metadata,\n\t\t\tclearError: true,\n\t\t});\n\t\treturn yield* reload(id);\n\t});\n\n\tconst stop: Interface[\"stop\"] = Effect.fn(\"Sandbox.Controller.stop\")(function* (id) {\n\t\tif (id === SandboxInstance.ID.local) {\n\t\t\treturn yield* new SandboxUnsupportedError({ id, driver: \"local\", operation: \"stop\" });\n\t\t}\n\t\tconst row = yield* requireRow(id);\n\t\tconst driverName = SandboxDriver.Name.make(row.driver);\n\t\tconst driver = yield* registry.get(driverName);\n\t\tif (!driver.capabilities.stop || driver.stop === undefined || row.ownership !== \"managed\") {\n\t\t\treturn yield* new SandboxUnsupportedError({ id, driver: driverName, operation: \"stop\" });\n\t\t}\n\t\tconst claim = yield* gate.withPermits(1)(\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst latest = yield* requireRow(id);\n\t\t\t\tconst count = refCount(id);\n\t\t\t\tif (count > 0) return yield* new SandboxBusyError({ id, refCount: count });\n\t\t\t\tif (latest.status === \"offline\") return { claimed: false as const, row: latest };\n\t\t\t\tif (latest.status === \"removed\") {\n\t\t\t\t\treturn yield* new SandboxRemovedError({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tremovedAt: Option.getOrUndefined(latest.removedAt),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst moved = yield* store.transition({\n\t\t\t\t\tid,\n\t\t\t\t\tfrom: [\"online\", \"faulted\", \"unavail\"],\n\t\t\t\t\tto: \"suspending\",\n\t\t\t\t});\n\t\t\t\tif (!moved) {\n\t\t\t\t\tconst actual = yield* requireRow(id);\n\t\t\t\t\treturn yield* new SandboxTransitionConflictError({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\texpected: [\"online\", \"faulted\", \"unavail\"],\n\t\t\t\t\t\tactual: actual.status,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { claimed: true as const };\n\t\t\t}),\n\t\t);\n\t\tif (!claim.claimed) return toInfo(claim.row);\n\t\treturn yield* Effect.uninterruptibleMask((restore) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tyield* transports.invalidate(id);\n\t\t\t\tconst current = yield* requireRow(id);\n\t\t\t\tconst attached = yield* runtime(current, \"stop\");\n\t\t\t\tconst observed = yield* restore(\n\t\t\t\t\tattached.driver.stop!(attached.input).pipe(\n\t\t\t\t\t\tEffect.catch((error): Effect.Effect<never, SandboxProviderError | SandboxUnavailError> =>\n\t\t\t\t\t\t\tproviderErrorIsNotFound(error)\n\t\t\t\t\t\t\t\t? markUnavailable(id, error)\n\t\t\t\t\t\t\t\t: persistProviderFailure(id, \"faulted\", error),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t).pipe(\n\t\t\t\t\tEffect.onInterrupt(() =>\n\t\t\t\t\t\tupdateObservation({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tstatus: \"faulted\",\n\t\t\t\t\t\t\tlastError: {\n\t\t\t\t\t\t\t\tname: \"SandboxStopInterrupted\",\n\t\t\t\t\t\t\t\tmessage: \"sandbox stop was interrupted before the provider confirmed completion\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tyield* updateObservation({\n\t\t\t\t\tid,\n\t\t\t\t\tstatus: \"offline\",\n\t\t\t\t\tproviderStatus: observed.providerStatus,\n\t\t\t\t\tmetadata: observed.metadata,\n\t\t\t\t\tclearError: true,\n\t\t\t\t});\n\t\t\t\treturn yield* reload(id);\n\t\t\t}),\n\t\t);\n\t});\n\n\tconst destroy: Interface[\"destroy\"] = Effect.fn(\"Sandbox.Controller.destroy\")(function* (id, destroyOptions = {}) {\n\t\tif (id === SandboxInstance.ID.local) {\n\t\t\treturn yield* new SandboxUnsupportedError({ id, driver: \"local\", operation: \"destroy\" });\n\t\t}\n\t\tconst row = yield* requireRow(id);\n\t\tconst driverName = SandboxDriver.Name.make(row.driver);\n\t\tconst driver = yield* registry.get(driverName);\n\t\tif (!driver.capabilities.destroy || driver.destroy === undefined || row.ownership !== \"managed\") {\n\t\t\treturn yield* new SandboxUnsupportedError({ id, driver: driverName, operation: \"destroy\" });\n\t\t}\n\t\tconst claim = yield* gate.withPermits(1)(\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst latest = yield* requireRow(id);\n\t\t\t\tif (latest.status === \"removed\") return { claimed: false as const, refCount: 0 };\n\t\t\t\tconst count = refCount(id);\n\t\t\t\tif (count > 0 && destroyOptions.force !== true) {\n\t\t\t\t\treturn yield* new SandboxBusyError({ id, refCount: count });\n\t\t\t\t}\n\t\t\t\tif (latest.status !== \"offline\" && latest.status !== \"unavail\") {\n\t\t\t\t\treturn yield* new SandboxMustBeStoppedError({ id, status: latest.status });\n\t\t\t\t}\n\t\t\t\tconst moved = yield* store.transition({ id, from: [\"offline\", \"unavail\"], to: \"removing\" });\n\t\t\t\tif (!moved) {\n\t\t\t\t\tconst actual = yield* requireRow(id);\n\t\t\t\t\treturn yield* new SandboxTransitionConflictError({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\texpected: [\"offline\", \"unavail\"],\n\t\t\t\t\t\tactual: actual.status,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { claimed: true as const, refCount: count, restoreStatus: latest.status };\n\t\t\t}),\n\t\t);\n\t\tif (!claim.claimed) return yield* Effect.void;\n\t\tif (claim.refCount > 0) {\n\t\t\tyield* Effect.logWarning(\"Force destroying a mounted sandbox\").pipe(\n\t\t\t\tEffect.annotateLogs({ sandboxInstanceId: id, refCount: claim.refCount }),\n\t\t\t);\n\t\t}\n\t\tyield* transports.invalidate(id);\n\t\tconst current = yield* requireRow(id);\n\t\tconst attached = yield* runtime(current, \"destroy\");\n\t\tyield* attached.driver.destroy!(attached.input).pipe(\n\t\t\tEffect.catch((error) =>\n\t\t\t\tproviderErrorIsNotFound(error) ? Effect.void : persistProviderFailure(id, claim.restoreStatus, error),\n\t\t\t),\n\t\t);\n\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t// Tombstone and archive the env's spaces atomically (D-ENV). The UPDATE\n\t\t// goes first so the DEFERRED transaction takes its write lock up front.\n\t\tyield* sql\n\t\t\t.withTransaction(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tyield* sql`\n\t\t\t\t\t\tUPDATE sandbox_instance\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tstatus = 'removed',\n\t\t\t\t\t\t\tremoved_at = ${now},\n\t\t\t\t\t\t\tstate_observed_at = ${now},\n\t\t\t\t\t\t\tlast_error = NULL,\n\t\t\t\t\t\t\tupdated_at = ${now}\n\t\t\t\t\t\tWHERE id = ${id}\n\t\t\t\t\t`;\n\t\t\t\t\tyield* Space.archiveEnv(id);\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.orDie);\n\t});\n\n\tconst createAndMount: Interface[\"createAndMount\"] = (input, mountOptions) => {\n\t\tconst id = input.instanceId ?? SandboxInstance.ID.create();\n\t\tconst lease: Lease = { held: false, mounted: false };\n\t\treturn Layer.unwrap(\n\t\t\tEffect.gen(function* () {\n\t\t\t\t// Reserve before the provider call. Once create inserts the\n\t\t\t\t// provisioning row, no observer can ever see it as idle.\n\t\t\t\tyield* acquireLease(id, lease);\n\t\t\t\tyield* Effect.addFinalizer(() => releaseLease(id, lease));\n\t\t\t\tyield* create({ ...input, instanceId: id });\n\t\t\t\treturn mountLayer(id, mountOptions, lease);\n\t\t\t}),\n\t\t);\n\t};\n\n\treturn Controller.of({\n\t\tcreate,\n\t\tcreateAndMount,\n\t\tregister,\n\t\tget,\n\t\tlist,\n\t\tresolveCwd,\n\t\trefresh,\n\t\tmount,\n\t\twithMount,\n\t\twake,\n\t\tstop,\n\t\tdestroy,\n\t});\n});\n\nexport const layer = (options?: Options) => Layer.effect(Controller, make(options));\n\nexport * as SandboxController from \"./control.ts\";\n","/* oxlint-disable effecttsgo/async-function -- Seeding bridges native files and the Promise-based VFS contract. */\nimport type { create } from \"@platformatic/vfs\";\nimport { Effect, Option } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { fileSystem } from \"../../host.ts\";\nimport { posix } from \"../../util/posix.ts\";\n\nexport interface SeedOptions {\n\t/** Virtual working directory used to resolve relative filesystem paths. Defaults to \"/\". */\n\treadonly cwd?: string;\n\t/** Initial files to write before optional read-only freeze. */\n\treadonly seed?: Record<string, string | Uint8Array>;\n\t/** Copy a host directory into the sandbox filesystem before optional read-only freeze. */\n\treadonly seedFromDirectory?: {\n\t\treadonly path: string;\n\t\treadonly target?: string;\n\t};\n}\n\ntype VirtualFileSystem = ReturnType<typeof create>;\n\nconst copyDirectory = async (\n\tvfs: VirtualFileSystem,\n\tsourceDirectory: string,\n\ttargetDirectory: string,\n): Promise<void> => {\n\tawait vfs.promises.mkdir(targetDirectory, { recursive: true });\n\n\tfor (const name of await Effect.runPromise(fileSystem.readDirectory(sourceDirectory))) {\n\t\tconst sourcePath = posix.join(sourceDirectory, name);\n\t\tconst targetPath = posix.join(targetDirectory, name);\n\t\tconst link = await Effect.runPromise(fileSystem.readLink(sourcePath).pipe(Effect.option));\n\n\t\tif (Option.isSome(link)) {\n\t\t\tawait vfs.promises.symlink(link.value, targetPath);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst entry = await Effect.runPromise(fileSystem.stat(sourcePath));\n\n\t\tif (entry.type === \"Directory\") {\n\t\t\tawait copyDirectory(vfs, sourcePath, targetPath);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (entry.type === \"File\") {\n\t\t\tawait vfs.promises.writeFile(\n\t\t\t\ttargetPath,\n\t\t\t\tBuffer.from(await Effect.runPromise(fileSystem.readFile(sourcePath))),\n\t\t\t);\n\t\t}\n\t}\n};\n\nexport const initialize = async (vfs: VirtualFileSystem, options?: SeedOptions): Promise<void> => {\n\tconst cwd = options?.cwd ?? \"/\";\n\tif (!posix.isAbsolute(cwd)) {\n\t\tthrow new TypeError(`Virtual filesystem default cwd must be absolute: ${cwd}`);\n\t}\n\tconst resolve = (value: string) => (posix.isAbsolute(value) ? posix.normalize(value) : posix.resolve(cwd, value));\n\n\tawait vfs.promises.mkdir(cwd, { recursive: true });\n\n\tif (options?.seedFromDirectory) {\n\t\tawait copyDirectory(vfs, options.seedFromDirectory.path, resolve(options.seedFromDirectory.target ?? cwd));\n\t}\n\n\tfor (const [filePath, data] of Object.entries(options?.seed ?? {})) {\n\t\tconst target = resolve(filePath);\n\t\tawait vfs.promises.mkdir(posix.dirname(target), { recursive: true });\n\t\tawait vfs.promises.writeFile(target, typeof data === \"string\" ? data : Buffer.from(data));\n\t}\n};\n\nexport * as Seed from \"./seed.ts\";\n","/* oxlint-disable effecttsgo/async-function -- VFS operations implement a Promise-based adapter contract. */\nimport { create, MemoryProvider } from \"@platformatic/vfs\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Process } from \"../utils/process.ts\";\nimport { Seed, type SeedOptions } from \"../utils/seed.ts\";\nimport { Local } from \"./vfs.ts\";\n\nexport class InMemoryError extends Schema.TaggedError<InMemoryError>()(\"InMemoryError\", {\n\tmessage: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\nexport interface Options extends SeedOptions {\n\t/** Freeze the provider to prevent writes. Defaults to false. */\n\treadonly readOnly?: boolean;\n\t/**\n\t * Spawn child processes on the host OS even though the filesystem is\n\t * virtual. Defaults to false: process execution is refused.\n\t */\n\treadonly hostProcess?: boolean;\n}\n\n/** Build one namespace. Drivers keep this value beyond transport-cache eviction. */\nexport const make = (options?: Options) =>\n\tEffect.tryPromise({\n\t\ttry: async () => {\n\t\t\tconst provider = new MemoryProvider();\n\t\t\tconst vfs = create(provider, { moduleHooks: false, virtualCwd: true });\n\n\t\t\tawait Seed.initialize(vfs, options);\n\t\t\tif (options?.readOnly) provider.setReadOnly();\n\t\t\treturn vfs;\n\t\t},\n\t\tcatch: (cause) =>\n\t\t\tnew InMemoryError({\n\t\t\t\tmessage: \"Failed to initialize the in-memory filesystem\",\n\t\t\t\tcause,\n\t\t\t}),\n\t});\n\n// A purely in-memory filesystem with no backing resource to release; every\n// layer build gets its own fresh, isolated tree.\nexport const layer = (options?: Options) =>\n\tLayer.merge(Layer.effect(Local.Vfs, make(options)), options?.hostProcess ? Process.host : Process.unsupported);\n\nexport * as EnvInMemory from \"./inmemory.ts\";\n","/* oxlint-disable effecttsgo/async-function -- just-bash exposes a Promise-based shell adapter contract. */\nimport { RealFSProvider, type VirtualFileSystem } from \"@platformatic/vfs\";\nimport { Effect, Layer } from \"effect\";\nimport { Bash, type IFileSystem } from \"just-bash\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../util/posix.ts\";\nimport { Local } from \"../fs/vfs.ts\";\nimport { SandboxIO } from \"../io.ts\";\nimport type { LocalPrimitives } from \"../sandbox.ts\";\nimport {\n\ttype ExecResult,\n\tfromExec,\n\ttype ISandboxExe,\n\tperMount,\n\tShell,\n\tShellError,\n\ttype ShellOptions,\n} from \"./shell.ts\";\n\n// The shared exec contract lives in `shell.ts`; re-export the pieces this\n// module used to own so existing `EnvBash.Shell` / `EnvBash.ShellError`\n// consumers keep working.\nexport { Shell, ShellError };\nexport type { ExecResult, ISandboxExe as Interface };\n\n// just-bash's IFileSystem implemented on top of the sandbox's vfs, so shell\n// commands and SandboxFileSystem.Service operate on the very same tree — there is\n// exactly one filesystem.\n//\ninterface Metadata {\n\treadonly mode?: number;\n\treadonly mtime?: Date;\n}\n\nconst metadataByVfs = new WeakMap<VirtualFileSystem, Map<string, Metadata>>();\n\nconst metadataFor = (vfs: VirtualFileSystem): Map<string, Metadata> => {\n\tconst existing = metadataByVfs.get(vfs);\n\tif (existing !== undefined) return existing;\n\tconst metadata = new Map<string, Metadata>();\n\tmetadataByVfs.set(vfs, metadata);\n\treturn metadata;\n};\n\n// VFS has no chmod/utimes primitives, so bash-visible mode and mtime changes\n// are kept in an overlay shared by every bridge over the same VFS. The overlay\n// only observes operations made through this bridge: mutating the raw VFS\n// directly (for example deleting and recreating a path) can leave a stale\n// overlay entry behind. Hard links fail loudly because their shared-inode\n// semantics cannot be represented by the VFS API.\nexport const bridge = (vfs: VirtualFileSystem, cwd: string): IFileSystem => {\n\tconst metadata = metadataFor(vfs);\n\tconst key = (path: string) => vfs.resolvePath(path);\n\t// Glob expansion enumerates from here. On the host that must be the mount's\n\t// directory: the VFS is rooted at `/` and never chdirs now, so reading its\n\t// cwd would enumerate the entire machine for every `*`.\n\tconst walkRoot = () => (vfs.provider instanceof RealFSProvider ? cwd : \"/\");\n\n\tconst encodingOf = (options?: { encoding?: string | null } | string) => {\n\t\tconst encoding = typeof options === \"string\" ? options : options?.encoding;\n\t\treturn (encoding ?? \"utf8\") as BufferEncoding;\n\t};\n\n\tconst assertWritable = (method: string, path: string) => {\n\t\tif (!vfs.readonly) return;\n\t\tconst error = new Error(`EROFS: read-only file system, ${method} '${path}'`) as NodeJS.ErrnoException;\n\t\terror.code = \"EROFS\";\n\t\tthrow error;\n\t};\n\n\tconst removeMetadata = (path: string) => {\n\t\tconst target = key(path);\n\t\tfor (const item of metadata.keys()) {\n\t\t\tif (item === target || item.startsWith(`${target}/`)) metadata.delete(item);\n\t\t}\n\t};\n\n\tconst moveMetadata = (src: string, dest: string) => {\n\t\tconst source = key(src);\n\t\tconst target = key(dest);\n\t\tconst moved = [...metadata.entries()].filter(([path]) => path === source || path.startsWith(`${source}/`));\n\t\tremoveMetadata(dest);\n\t\tremoveMetadata(src);\n\t\tfor (const [path, value] of moved) metadata.set(`${target}${path.slice(source.length)}`, value);\n\t};\n\n\t// a write refreshes the VFS's own mtime, so an overlaid mtime from an\n\t// earlier touch would be stale — drop it and let the provider's show\n\tconst dropOverlaidMtime = async (path: string) => {\n\t\tconst target = key(await vfs.promises.realpath(path));\n\t\tconst existing = metadata.get(target);\n\t\tif (existing?.mtime === undefined) return;\n\t\tif (existing.mode === undefined) metadata.delete(target);\n\t\telse metadata.set(target, { mode: existing.mode });\n\t};\n\n\tconst rm: IFileSystem[\"rm\"] = async (path, options) => {\n\t\tlet stats: Awaited<ReturnType<typeof vfs.promises.lstat>>;\n\t\ttry {\n\t\t\tstats = await vfs.promises.lstat(path);\n\t\t} catch (error) {\n\t\t\t// force only pardons missing paths; permission or provider failures\n\t\t\t// must not masquerade as successful cleanup\n\t\t\tif (options?.force && (error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n\t\t\tthrow error;\n\t\t}\n\t\tif (stats.isDirectory()) {\n\t\t\tif (!options?.recursive) throw new Error(`rm: ${path}: is a directory`);\n\t\t\tfor (const name of await vfs.promises.readdir(path)) {\n\t\t\t\tawait rm(posix.join(path, name), options);\n\t\t\t}\n\t\t\tawait vfs.promises.rmdir(path);\n\t\t} else {\n\t\t\tawait vfs.promises.unlink(path);\n\t\t}\n\t\tremoveMetadata(path);\n\t};\n\n\tconst cp: IFileSystem[\"cp\"] = async (src, dest, options) => {\n\t\tconst stats = await vfs.promises.stat(src);\n\t\tif (stats.isDirectory()) {\n\t\t\tif (!options?.recursive) throw new Error(`cp: ${src}: is a directory (not copied)`);\n\t\t\tawait vfs.promises.mkdir(dest, { recursive: true });\n\t\t\tfor (const name of await vfs.promises.readdir(src)) {\n\t\t\t\tawait cp(posix.join(src, name), posix.join(dest, name), options);\n\t\t\t}\n\t\t} else {\n\t\t\tawait vfs.promises.copyFile(src, dest);\n\t\t\t// just-bash's native filesystem carries mode and mtime over to the\n\t\t\t// copy, but VFS copyFile stamps a fresh mtime — pin the source's\n\t\t\t// bash-visible metadata onto the destination\n\t\t\tconst override = metadata.get(key(await vfs.promises.realpath(src)));\n\t\t\tmetadata.set(key(await vfs.promises.realpath(dest)), {\n\t\t\t\t...override,\n\t\t\t\tmtime: override?.mtime ?? stats.mtime,\n\t\t\t});\n\t\t}\n\t};\n\n\tconst toStat = (\n\t\tpath: string,\n\t\tstats: {\n\t\t\tisFile(): boolean;\n\t\t\tisDirectory(): boolean;\n\t\t\tisSymbolicLink(): boolean;\n\t\t\tmode: number;\n\t\t\tsize: number;\n\t\t\tmtime: Date;\n\t\t},\n\t) => {\n\t\tconst override = metadata.get(key(path));\n\t\treturn {\n\t\t\tisFile: stats.isFile(),\n\t\t\tisDirectory: stats.isDirectory(),\n\t\t\tisSymbolicLink: stats.isSymbolicLink(),\n\t\t\tmode: override?.mode === undefined ? stats.mode : (stats.mode & ~0o7777) | override.mode,\n\t\t\tsize: stats.size,\n\t\t\tmtime: override?.mtime ?? stats.mtime,\n\t\t};\n\t};\n\n\treturn {\n\t\treadFile: async (path, options) => {\n\t\t\tconst content = await vfs.promises.readFile(path, encodingOf(options));\n\t\t\treturn content as string;\n\t\t},\n\t\treadFileBuffer: async (path) => (await vfs.promises.readFile(path)) as Buffer,\n\t\twriteFile: async (path, content, options) => {\n\t\t\tawait vfs.promises.writeFile(\n\t\t\t\tpath,\n\t\t\t\ttypeof content === \"string\" ? content : Buffer.from(content),\n\t\t\t\tencodingOf(options),\n\t\t\t);\n\t\t\tawait dropOverlaidMtime(path);\n\t\t},\n\t\tappendFile: async (path, content, options) => {\n\t\t\tawait vfs.promises.appendFile(\n\t\t\t\tpath,\n\t\t\t\ttypeof content === \"string\" ? content : Buffer.from(content),\n\t\t\t\tencodingOf(options),\n\t\t\t);\n\t\t\tawait dropOverlaidMtime(path);\n\t\t},\n\t\t// async existence via stat, so the bridge does not depend on a\n\t\t// provider's synchronous exists implementation.\n\t\texists: async (path) => {\n\t\t\ttry {\n\t\t\t\tawait vfs.promises.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\tstat: async (path) => {\n\t\t\tconst stats = await vfs.promises.stat(path);\n\t\t\treturn toStat(await vfs.promises.realpath(path), stats);\n\t\t},\n\t\tlstat: async (path) => toStat(path, await vfs.promises.lstat(path)),\n\t\tmkdir: async (path, options) => {\n\t\t\tawait vfs.promises.mkdir(path, options);\n\t\t},\n\t\treaddir: (path) => vfs.promises.readdir(path),\n\t\treaddirWithFileTypes: async (path) => {\n\t\t\tconst entries = await vfs.promises.readdir(path, { withFileTypes: true });\n\t\t\treturn entries.map((entry) => ({\n\t\t\t\tname: entry.name,\n\t\t\t\tisFile: entry.isFile(),\n\t\t\t\tisDirectory: entry.isDirectory(),\n\t\t\t\tisSymbolicLink: entry.isSymbolicLink(),\n\t\t\t}));\n\t\t},\n\t\trm,\n\t\tcp,\n\t\tmv: async (src, dest) => {\n\t\t\tawait vfs.promises.rename(src, dest);\n\t\t\tmoveMetadata(src, dest);\n\t\t},\n\t\tresolvePath: (base, path) => posix.resolve(base, path),\n\t\tgetAllPaths: () => {\n\t\t\tconst paths: string[] = [];\n\t\t\tconst walk = (dir: string) => {\n\t\t\t\tlet entries: ReturnType<typeof vfs.readdirSync>;\n\t\t\t\ttry {\n\t\t\t\t\tentries = vfs.readdirSync(dir, { withFileTypes: true });\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\tconst full = posix.join(dir, entry.name);\n\t\t\t\t\tpaths.push(full);\n\t\t\t\t\tif (entry.isDirectory()) walk(full);\n\t\t\t\t}\n\t\t\t};\n\t\t\twalk(walkRoot());\n\t\t\treturn paths;\n\t\t},\n\t\tchmod: async (path, mode) => {\n\t\t\tassertWritable(\"chmod\", path);\n\t\t\tawait vfs.promises.stat(path);\n\t\t\tconst target = key(await vfs.promises.realpath(path));\n\t\t\tmetadata.set(target, { ...metadata.get(target), mode });\n\t\t},\n\t\tsymlink: (target, linkPath) => vfs.promises.symlink(target, linkPath),\n\t\tlink: () => Promise.reject(new Error(\"hard links are not supported by this sandbox\")),\n\t\treadlink: (path) => vfs.promises.readlink(path),\n\t\trealpath: (path) => vfs.promises.realpath(path),\n\t\tutimes: async (path, _atime, mtime) => {\n\t\t\tassertWritable(\"utimes\", path);\n\t\t\tawait vfs.promises.stat(path);\n\t\t\tconst target = key(await vfs.promises.realpath(path));\n\t\t\tmetadata.set(target, { ...metadata.get(target), mtime });\n\t\t},\n\t};\n};\n\nconst fromBash = (bash: Bash): ISandboxExe => {\n\tconst exec = Effect.fn(\"Shell.exec\")(function* (command: string, options?: ShellOptions) {\n\t\treturn yield* Effect.tryPromise({\n\t\t\t// `tryPromise` aborts this signal when the fiber is interrupted, and\n\t\t\t// just-bash stops at its next statement boundary. Without threading it\n\t\t\t// through, an interrupted command keeps running in-process to\n\t\t\t// completion: the fiber unwinds promptly and the work leaks behind it,\n\t\t\t// still writing to the sandbox filesystem long after its caller is gone.\n\t\t\ttry: (signal) => bash.exec(command, { ...options, signal }),\n\t\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t\t});\n\t});\n\n\t// just-bash parses a command string, so `execArgv` goes through the shared\n\t// quoting fallback rather than spawning a vector directly.\n\treturn Shell.of(fromExec({ exec }));\n};\n\nconst make = (vfs: VirtualFileSystem, cwd: string): ISandboxExe => fromBash(new Bash({ fs: bridge(vfs, cwd), cwd }));\n\n// just-bash only needs the async IFileSystem surface. The lone synchronous\n// touchpoint, getAllPaths for glob expansion, degrades to an empty list.\nconst shell = (cwd: string) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Local.Vfs, (vfs) => make(vfs, cwd)),\n\t);\n\n/**\n * A cached virtual transport whose Bash interpreter is constructed only when a\n * mount binds its cwd. This matches Flue's BashFactory ownership: mounts share\n * the VFS, but shell state (functions, options, command hashes) is mount-local.\n */\nexport const transport = <E, RIn>(\n\tinner: Layer.Layer<LocalPrimitives, E, RIn>,\n): Layer.Layer<Shell | LocalPrimitives, E, RIn> =>\n\tLayer.provideMerge(\n\t\tLayer.effect(\n\t\t\tShell,\n\t\t\tEffect.map(Local.Vfs, (vfs) => {\n\t\t\t\tconst root = make(vfs, \"/\");\n\t\t\t\treturn perMount(root, (cwd) => make(vfs, cwd));\n\t\t\t}),\n\t\t),\n\t\tinner,\n\t);\n\n/**\n * Wraps any local VFS-backed sandbox with a just-bash shell that executes\n * against the sandbox's own vfs: pick the filesystem backend (default, inmemory, sqldb) and gain a Shell service on top of it.\n */\n// `cwd` is required rather than defaulted. A default of `/` is harmless over a\n// VFS and catastrophic over the host: `walkRoot` would enumerate the entire\n// machine, synchronously, on the first glob. A caller that has to name the\n// directory cannot fall into that by omission.\nexport const layer = <E, RIn>(\n\tinner: Layer.Layer<LocalPrimitives, E, RIn>,\n\tcwd: string,\n): Layer.Layer<Shell | LocalPrimitives, E, RIn> =>\n\tLayer.provideMerge(shell(SandboxIO.resolveMountCwd(\"/\", cwd)), inner);\n\n/**\n * A mount over a bash-wrapped sandbox: `SandboxIO.Current`, the sandbox\n * filesystem, the just-bash Shell, and the backend's own primitives. The\n * Shell-typed counterpart of `Sandbox.services`.\n */\nexport const services = <E, RIn>(\n\tinner: Layer.Layer<LocalPrimitives, E, RIn>,\n\tidentity: SandboxIO.Identity,\n): Layer.Layer<SandboxIO.Provides | LocalPrimitives, E, RIn> =>\n\tLayer.provideMerge(SandboxIO.mount(identity), Layer.provideMerge(Local.layer, layer(inner, identity.cwd)));\n\nexport * as EnvBash from \"./justbash.ts\";\n","import type { VirtualFileSystem } from \"@platformatic/vfs\";\nimport { Layer } from \"effect\";\nimport type { ChildProcessSpawner } from \"effect/unstable/process\";\nimport { SandboxFileSystem } from \"./fs/filesystem.ts\";\nimport { Local } from \"./fs/vfs.ts\";\nimport { EnvBash } from \"./shell/justbash.ts\";\nimport { Shell } from \"./shell/shell.ts\";\nimport { Process } from \"./utils/process.ts\";\n\ntype Primitives = Local.Vfs | ChildProcessSpawner.ChildProcessSpawner;\n\nexport const transportLayer = <E, R>(\n\tprimitives: Layer.Layer<Primitives, E, R>,\n): Layer.Layer<SandboxFileSystem.Service | Shell, E, R> =>\n\tLayer.provideMerge(Layer.merge(Layer.fresh(Local.layer), EnvBash.transport(primitives)), primitives);\n\n/** A cwd-neutral FileSystem + just-bash transport over one retained VFS. */\nexport const transport = (vfs: VirtualFileSystem): Layer.Layer<SandboxFileSystem.Service | Shell> => {\n\tconst primitives = Layer.merge(Layer.succeed(Local.Vfs, vfs), Process.unsupported);\n\treturn transportLayer(primitives);\n};\n","import type { VirtualFileSystem } from \"@platformatic/vfs\";\nimport { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { providerError } from \"../errors.ts\";\nimport { EnvInMemory } from \"../fs/inmemory.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { transport } from \"../virtual.ts\";\n\nexport interface RuntimeConfig extends SandboxDriver.RuntimeConfigBase {}\n\nexport const CreateConfig = Schema.Struct({\n\tdefaultCwd: Schema.optional(SandboxDriver.AbsolutePath),\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = SandboxDriver.RuntimeConfigBase;\n\nexport interface MemoryDriver {\n\treadonly driver: SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration;\n}\n\nexport const make = (): MemoryDriver => {\n\tconst name = SandboxDriver.Name.make(\"memory\");\n\tconst resources = new Map<SandboxInstance.ID, VirtualFileSystem>();\n\n\tconst find = (operation: string, input: SandboxDriver.RuntimeInput<RuntimeConfig>) => {\n\t\tconst vfs = resources.get(input.id);\n\t\treturn vfs === undefined\n\t\t\t? Effect.fail(\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause: new Error(`memory namespace is unavailable in this process: ${input.id}`),\n\t\t\t\t\t\tnotFound: true,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t: Effect.succeed(vfs);\n\t};\n\n\tconst driver = SandboxDriver.driver<CreateConfig, RuntimeConfig>({\n\t\tname,\n\t\tkind: \"virtual\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: false,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) => {\n\t\t\tconst defaultCwd = config.defaultCwd ?? SandboxDriver.AbsolutePath.make(\"/\");\n\t\t\treturn EnvInMemory.make({ cwd: config.initializeCwd ?? defaultCwd }).pipe(\n\t\t\t\tEffect.mapError((cause) => providerError({ driver: name, operation: \"create\", cause })),\n\t\t\t\tEffect.map((vfs) => {\n\t\t\t\t\tresources.set(instanceId, vfs);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tproviderResourceId: `memory:${instanceId}`,\n\t\t\t\t\t\tproviderStatus: \"online\",\n\t\t\t\t\t\truntimeConfig: { defaultCwd },\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tattach: (input) => Layer.unwrap(Effect.map(find(\"attach\", input), transport)),\n\t\tinspect: (input) =>\n\t\t\tEffect.as(find(\"inspect\", input), {\n\t\t\t\tstatus: \"online\",\n\t\t\t\tproviderStatus: \"online\",\n\t\t\t}),\n\t\twake: (input) =>\n\t\t\tEffect.as(find(\"wake\", input), {\n\t\t\t\tstatus: \"online\",\n\t\t\t\tproviderStatus: \"online\",\n\t\t\t}),\n\t\tstop: (input) =>\n\t\t\tEffect.as(find(\"stop\", input), {\n\t\t\t\tstatus: \"offline\" as const,\n\t\t\t\tproviderStatus: \"retained\",\n\t\t\t}),\n\t\tdestroy: (input) =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst existed = resources.delete(input.id);\n\t\t\t\treturn existed || Option.isSome(input.providerResourceId)\n\t\t\t\t\t? Effect.void\n\t\t\t\t\t: Effect.fail(\n\t\t\t\t\t\t\tproviderError({\n\t\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\t\toperation: \"destroy\",\n\t\t\t\t\t\t\t\tcause: new Error(`memory namespace is unavailable: ${input.id}`),\n\t\t\t\t\t\t\t\tnotFound: true,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t}),\n\t});\n\n\treturn { driver };\n};\n\nexport * as MemorySandboxDriver from \"./memory.ts\";\n","/* oxlint-disable effecttsgo/async-function -- VFS operations implement a Promise-based adapter contract. */\nimport { create, SqliteProvider } from \"@platformatic/vfs\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Process } from \"../utils/process.ts\";\nimport { Seed, type SeedOptions } from \"../utils/seed.ts\";\nimport { Local } from \"./vfs.ts\";\n\nexport class SqldbError extends Schema.TaggedError<SqldbError>()(\"SqldbError\", {\n\tmessage: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\n// SqliteProvider holds a single node:sqlite connection for the lifetime of\n// the layer; omitting `location` keeps the whole filesystem in `:memory:`.\nexport interface Namespace {\n\treadonly provider: SqliteProvider;\n\treadonly vfs: ReturnType<typeof create>;\n}\n\nexport const make = (location?: string, options?: Options) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<Namespace> => {\n\t\t\tconst provider = new SqliteProvider(location);\n\t\t\ttry {\n\t\t\t\tconst vfs = create(provider, { moduleHooks: false, virtualCwd: true });\n\n\t\t\t\tawait Seed.initialize(vfs, options);\n\t\t\t\tif (options?.readOnly) provider.setReadOnly();\n\n\t\t\t\treturn { provider, vfs };\n\t\t\t} catch (error) {\n\t\t\t\tprovider.close();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcatch: (cause) =>\n\t\t\tnew SqldbError({\n\t\t\t\tmessage: \"Failed to initialize the SQLite filesystem\",\n\t\t\t\tcause,\n\t\t\t}),\n\t});\n\nconst vfsLayer = (location?: string, options?: Options) =>\n\tLayer.effect(\n\t\tLocal.Vfs,\n\t\tEffect.acquireRelease(make(location, options), ({ provider }) => Effect.sync(() => provider.close())).pipe(\n\t\t\tEffect.map(({ vfs }) => vfs),\n\t\t),\n\t);\n\nexport interface Options extends SeedOptions {\n\t/** Freeze the provider to prevent writes. Defaults to false. */\n\treadonly readOnly?: boolean;\n\t/**\n\t * Spawn child processes on the host OS even though the filesystem is\n\t * virtual. Defaults to false: process execution is refused.\n\t */\n\treadonly hostProcess?: boolean;\n}\n\ninterface LayerOptions {\n\tlocation?: string;\n\toptions?: Options;\n}\n\nexport const layer = (opts?: LayerOptions) =>\n\tLayer.merge(\n\t\tvfsLayer(opts?.location, opts?.options),\n\t\topts?.options?.hostProcess ? Process.host : Process.unsupported,\n\t);\n\nexport * as EnvSqldb from \"./sqldb.ts\";\n","import type { VirtualFileSystem } from \"@platformatic/vfs\";\nimport { Effect, Layer, Option, Schema } from \"effect\";\nimport { fileSystem } from \"../../host.ts\";\nimport { posix } from \"../../util/posix.ts\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { providerError } from \"../errors.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { EnvSqldb } from \"../fs/sqldb.ts\";\nimport { transport, transportLayer } from \"../virtual.ts\";\n\nexport interface RuntimeConfig extends SandboxDriver.RuntimeConfigBase {\n\treadonly location?: string | undefined;\n\treadonly inMemory: boolean;\n}\n\nexport const CreateConfig = Schema.Struct({\n\tdefaultCwd: Schema.optional(SandboxDriver.AbsolutePath),\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n\tlocation: Schema.optional(Schema.String),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tlocation: Schema.optional(Schema.String),\n\tinMemory: Schema.Boolean,\n});\n\ninterface MemoryResource {\n\treadonly provider: EnvSqldb.Namespace[\"provider\"];\n\treadonly vfs: VirtualFileSystem;\n}\n\nexport const make = () => {\n\tconst name = SandboxDriver.Name.make(\"sqldb\");\n\tconst memory = new Map<SandboxInstance.ID, MemoryResource>();\n\n\tconst runtimeLocation = (input: SandboxDriver.RuntimeInput<RuntimeConfig>) =>\n\t\tinput.runtimeConfig.location ?? Option.getOrUndefined(input.providerResourceId);\n\tconst persistentTransport = (location: string) => {\n\t\tconst backend = EnvSqldb.layer({ location });\n\t\treturn transportLayer(\n\t\t\tLayer.effectContext(\n\t\t\t\tLayer.build(backend).pipe(\n\t\t\t\t\tEffect.mapError((cause) => providerError({ driver: name, operation: \"attach\", cause })),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\tconst memoryResource = (operation: string, id: SandboxInstance.ID) => {\n\t\tconst resource = memory.get(id);\n\t\treturn resource === undefined\n\t\t\t? Effect.fail(\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause: new Error(`in-memory sqlite namespace is unavailable in this process: ${id}`),\n\t\t\t\t\t\tnotFound: true,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t: Effect.succeed(resource);\n\t};\n\n\tconst driver = SandboxDriver.driver<CreateConfig, RuntimeConfig>({\n\t\tname,\n\t\tkind: \"virtual\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) => {\n\t\t\tconst defaultCwd = config.defaultCwd ?? SandboxDriver.AbsolutePath.make(\"/\");\n\t\t\tconst location = config.location === undefined ? undefined : posix.resolve(config.location);\n\t\t\treturn EnvSqldb.make(location, { cwd: config.initializeCwd ?? defaultCwd }).pipe(\n\t\t\t\tEffect.mapError((cause) => providerError({ driver: name, operation: \"create\", cause })),\n\t\t\t\tEffect.map((namespace) => {\n\t\t\t\t\tif (location === undefined) memory.set(instanceId, namespace);\n\t\t\t\t\telse namespace.provider.close();\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...(location === undefined ? {} : { providerResourceId: location }),\n\t\t\t\t\t\tproviderStatus: location === undefined ? \"online\" : \"offline\",\n\t\t\t\t\t\truntimeConfig: {\n\t\t\t\t\t\t\tdefaultCwd,\n\t\t\t\t\t\t\t...(location === undefined ? {} : { location }),\n\t\t\t\t\t\t\tinMemory: location === undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) => {\n\t\t\tif (!posix.isAbsolute(providerResourceId)) {\n\t\t\t\treturn Effect.fail(\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation: \"runtimeConfigFor\",\n\t\t\t\t\t\tcause: new Error(`sqldb resource path must be absolute: ${providerResourceId}`),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst location = posix.resolve(providerResourceId);\n\t\t\treturn Effect.succeed({\n\t\t\t\tdefaultCwd: overrides?.defaultCwd ?? SandboxDriver.AbsolutePath.make(\"/\"),\n\t\t\t\tlocation,\n\t\t\t\tinMemory: false,\n\t\t\t});\n\t\t},\n\t\tattach: (input) => {\n\t\t\tif (input.runtimeConfig.inMemory) {\n\t\t\t\treturn Layer.unwrap(Effect.map(memoryResource(\"attach\", input.id), (resource) => transport(resource.vfs)));\n\t\t\t}\n\t\t\tconst location = runtimeLocation(input);\n\t\t\treturn location === undefined\n\t\t\t\t? Layer.unwrap(\n\t\t\t\t\t\tEffect.fail(\n\t\t\t\t\t\t\tproviderError({\n\t\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\t\toperation: \"attach\",\n\t\t\t\t\t\t\t\tcause: new Error(`sqldb runtime location is missing: ${input.id}`),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: persistentTransport(location);\n\t\t},\n\t\tinspect: (input) => {\n\t\t\tif (input.runtimeConfig.inMemory) {\n\t\t\t\treturn Effect.as(memoryResource(\"inspect\", input.id), {\n\t\t\t\t\tstatus: \"online\" as const,\n\t\t\t\t\tproviderStatus: \"online\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst location = runtimeLocation(input);\n\t\t\tif (location === undefined) {\n\t\t\t\treturn Effect.fail(\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation: \"inspect\",\n\t\t\t\t\t\tcause: new Error(`sqldb runtime location is missing: ${input.id}`),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn fileSystem.access(location).pipe(\n\t\t\t\tEffect.mapError((cause) => providerError({ driver: name, operation: \"inspect\", cause, notFound: true })),\n\t\t\t\tEffect.as({ status: \"offline\" as const, providerStatus: \"closed\" }),\n\t\t\t);\n\t\t},\n\t\twake: (input) =>\n\t\t\tinput.runtimeConfig.inMemory\n\t\t\t\t? Effect.as(memoryResource(\"wake\", input.id), {\n\t\t\t\t\t\tstatus: \"online\" as const,\n\t\t\t\t\t\tproviderStatus: \"online\",\n\t\t\t\t\t})\n\t\t\t\t: Effect.succeed({ status: \"online\", providerStatus: \"open-on-attach\" }),\n\t\tstop: (input) =>\n\t\t\tinput.runtimeConfig.inMemory\n\t\t\t\t? Effect.as(memoryResource(\"stop\", input.id), {\n\t\t\t\t\t\tstatus: \"offline\" as const,\n\t\t\t\t\t\tproviderStatus: \"retained\",\n\t\t\t\t\t})\n\t\t\t\t: Effect.succeed({ status: \"offline\", providerStatus: \"closed\" }),\n\t\tdestroy: (input) => {\n\t\t\tif (input.runtimeConfig.inMemory) {\n\t\t\t\tconst resource = memory.get(input.id);\n\t\t\t\tif (resource !== undefined) resource.provider.close();\n\t\t\t\tmemory.delete(input.id);\n\t\t\t\treturn Effect.void;\n\t\t\t}\n\t\t\tconst location = runtimeLocation(input);\n\t\t\treturn location === undefined\n\t\t\t\t? Effect.fail(\n\t\t\t\t\t\tproviderError({\n\t\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\t\toperation: \"destroy\",\n\t\t\t\t\t\t\tcause: new Error(`sqldb runtime location is missing: ${input.id}`),\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t: fileSystem\n\t\t\t\t\t\t.remove(location, { force: true })\n\t\t\t\t\t\t.pipe(Effect.mapError((cause) => providerError({ driver: name, operation: \"destroy\", cause })));\n\t\t},\n\t});\n\n\treturn { driver };\n};\n\nexport * as SqldbSandboxDriver from \"./sqldb.ts\";\n","import { Context } from \"effect\";\n\n/**\n * The driver's own locator for the attached resource — a Vercel sandbox name, a\n * Daytona sandbox id.\n *\n * Deliberately *not* on `SandboxIO.Current`: consumers never parse one,\n * and keeps it separate from the application id precisely so a driver's format can\n * change without touching identity.\n *\n * It exists for the control plane, which records it as `provider_resource_id`,\n * and for tests that reattach to the same resource.\n *\n * One tag for every driver rather than one per driver. A mount has exactly one\n * driver, so there is nothing to disambiguate, and the control plane has to read\n * the locator without knowing which driver produced it — keeps the\n * driver name open, so anything keyed on a closed `\"vercel\" | \"daytona\"` set is\n * a bug waiting for the third driver.\n */\nexport class Service extends Context.Service<Service, { readonly providerResourceId: string }>()(\n\t\"@codeworksh/harness/sandbox/resource/Service\",\n) {}\n\nexport * as SandboxResource from \"./resource.ts\";\n","import { posix } from \"../../util/posix.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\n\nexport type FileStat = SandboxFileSystem.FileStat;\n\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/** Resolve provider paths without adding policy or mutable working-directory state. */\nexport const make = (provider: Interface, options?: Options): SandboxFileSystem.Provider => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t\trealpath: (path) => provider.realpath(resolve(path)),\n\t};\n};\n\nexport const withProvider = make;\n","/* oxlint-disable effecttsgo/async-function -- Daytona's SDK boundary is Promise-based. */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../util/posix.ts\";\nimport { sanitizeError } from \"../../sandbox/errors.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\nimport { SandboxInstance } from \"../../sandbox/instance.ts\";\nimport { SandboxIO } from \"../../sandbox/io.ts\";\nimport { SandboxResource } from \"../../sandbox/resource.ts\";\nimport { type ISandboxExe, quote, quoteArgv, resolveCwd, Shell, ShellError } from \"../../sandbox/shell/shell.ts\";\nimport * as RemoteFileSystem from \"./fs.ts\";\n\ntype CodeLanguage = import(\"@daytona/sdk\").CodeLanguage;\ntype Daytona = import(\"@daytona/sdk\").Daytona;\ntype FileInfo = import(\"@daytona/sdk\").FileInfo;\ntype Image = import(\"@daytona/sdk\").Image;\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\n/** Fallback when Daytona cannot report a snapshot/image-specific work directory. */\nexport const DEFAULT_CWD = \"/home/daytona\";\n\n/**\n * The mount cwd for a Daytona namespace.\n *\n * An absolute override replaces the namespace default outright, so the\n * `getWorkDir()` round-trip is skipped: it would discover a value we then throw\n * away. Otherwise the sandbox's own work directory is the default, and\n * {@link DEFAULT_CWD} covers a snapshot or image that reports none.\n *\n * Taken as a thunk rather than read off the sandbox so all three branches are\n * testable without provisioning one — this decides where every Daytona mount\n * roots, and §8.1 makes a wrong answer here resolve silently rather than fail.\n */\nexport const mountCwd = async (\n\tcwd: string | undefined,\n\tgetWorkDir: () => Promise<string | undefined>,\n): Promise<string> => {\n\tconst defaultCwd = posix.isAbsolute(cwd ?? \"\") ? DEFAULT_CWD : ((await getWorkDir()) ?? DEFAULT_CWD);\n\treturn SandboxIO.resolveMountCwd(defaultCwd, cwd);\n};\n\nexport class DaytonaError extends Schema.TaggedError<DaytonaError>()(\"DaytonaError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nexport interface Options {\n\t/** API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n\treadonly apiKey?: string | undefined;\n\t/** API URL. Falls back to `DAYTONA_API_URL` / the SDK default. */\n\treadonly apiUrl?: string | undefined;\n\t/** Target region. Falls back to `DAYTONA_TARGET` / the SDK default. */\n\treadonly target?: string | undefined;\n\t/** Reuse an existing sandbox by id or name instead of creating one. */\n\treadonly sandboxId?: string | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Image (registry reference or declarative `Image`) to create the sandbox from. */\n\treadonly image?: string | Image | undefined;\n\t/** Runtime used for code execution. Defaults to `\"typescript\"`. */\n\treadonly language?: CodeLanguage | string | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** Resource allocation (cpu / memory / disk). */\n\treadonly resources?: Resources | undefined;\n\t/** OS user to run as inside the sandbox. */\n\treadonly user?: string | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `getWorkDir()`;\n\t * omitted values use it, with `/home/daytona` as the provider fallback.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Idle minutes before the sandbox auto-stops. */\n\treadonly autoStopInterval?: number | undefined;\n\t/** Per-command timeout in seconds. 0 means no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n\treadonly cwd: string;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandboxes/daytona/provider/Remote\") {}\n\nconst assertCommandSucceeded = (command: string, result: { exitCode: number; result?: string }) => {\n\tif (result.exitCode !== 0) throw new Error(result.result || `command failed (${result.exitCode}): ${command}`);\n};\n\nconst dateFrom = (value: string | undefined) => {\n\tif (value === undefined) return undefined;\n\treturn Option.getOrUndefined(DateTime.make(value).pipe(Option.map(DateTime.toDateUtc)));\n};\n\nexport const createSandbox = (daytona: Daytona, options: Options) => {\n\tconst base = {\n\t\tlanguage: options.language ?? \"typescript\",\n\t\t...(options.envVars === undefined ? {} : { envVars: options.envVars }),\n\t\t...(options.user === undefined ? {} : { user: options.user }),\n\t\t...(options.autoStopInterval === undefined ? {} : { autoStopInterval: options.autoStopInterval }),\n\t\tautoDeleteInterval: -1,\n\t};\n\treturn options.image !== undefined\n\t\t? daytona.create({\n\t\t\t\t...base,\n\t\t\t\timage: options.image,\n\t\t\t\t...(options.resources === undefined ? {} : { resources: options.resources }),\n\t\t\t})\n\t\t: daytona.create({ ...base, ...(options.snapshot === undefined ? {} : { snapshot: options.snapshot }) });\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Daytona } = await import(\"@daytona/sdk\");\n\t\t\t\tconst daytona = new Daytona({\n\t\t\t\t\t...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),\n\t\t\t\t\t...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n\t\t\t\t\t...(options.target === undefined ? {} : { target: options.target }),\n\t\t\t\t});\n\t\t\t\tconst sandbox = options.sandboxId\n\t\t\t\t\t? await daytona.get(options.sandboxId)\n\t\t\t\t\t: await createSandbox(daytona, options);\n\t\t\t\treturn {\n\t\t\t\t\tsandbox,\n\t\t\t\t\tcwd: await mountCwd(options.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t};\n\t\t\t},\n\t\t\tcatch: (cause) => new DaytonaError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\nexport const statsFrom = (info: FileInfo): RemoteFileSystem.FileStat => {\n\tconst symlink = info.mode === undefined ? undefined : info.mode.startsWith(\"l\");\n\tconst mtime = dateFrom(info.modifiedAt ?? info.modTime);\n\n\t// omit size/mtime/isSymbolicLink the toolbox did not report — never fabricate\n\treturn {\n\t\tisFile: !info.isDir && symlink !== true,\n\t\tisDirectory: info.isDir,\n\t\t...(symlink === undefined ? {} : { isSymbolicLink: symlink }),\n\t\t...(info.size === undefined ? {} : { size: info.size }),\n\t\t...(mtime === undefined ? {} : { mtime }),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\" | \"realpath\"\n>;\n\nconst providerFrom = (sandbox: RemoteSandbox, options: Options) => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: async (path: string) => (await sandbox.fs.downloadFile(path)).toString(\"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.downloadFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.uploadFile(typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content), path),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.getFileDetails(path)),\n\t\t// The toolbox file-details endpoint follows symlinks. Detect the entry\n\t\t// with the sandbox shell first so lstat never reports target metadata as\n\t\t// if it described the link itself.\n\t\tlstat: async (path: string) => {\n\t\t\tconst command = `test -L ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tif (result.exitCode === 0) {\n\t\t\t\treturn { isFile: false, isDirectory: false, isSymbolicLink: true };\n\t\t\t}\n\t\t\tif (result.exitCode === 1) return statsFrom(await sandbox.fs.getFileDetails(path));\n\t\t\tassertCommandSucceeded(command, result);\n\t\t\tthrow new Error(`unreachable lstat result for ${path}`);\n\t\t},\n\t\treaddir: async (path: string) => (await sandbox.fs.listFiles(path)).map((entry) => entry.name),\n\t\t// Only a genuine 404 means \"absent\". Auth, rate-limit, and transport\n\t\t// failures propagate: a caller that deletes records on absence must not\n\t\t// be told a path is gone because the API was briefly unreachable.\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.getFileDetails(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tconst { DaytonaNotFoundError } = await import(\"@daytona/sdk\");\n\t\t\t\tif (cause instanceof DaytonaNotFoundError) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tif (!mkdirOptions?.recursive) {\n\t\t\t\tawait sandbox.fs.createFolder(path, \"755\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst command = `mkdir -p ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tassertCommandSucceeded(command, result);\n\t\t},\n\t\trm: async (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) => {\n\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.deleteFile(path, rmOptions?.recursive);\n\t\t\t} catch (cause) {\n\t\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\trealpath: async (path: string) => {\n\t\t\tconst run = async (script: string) => {\n\t\t\t\tconst command = quoteArgv([\"sh\", \"-c\", script, \"_\", path]);\n\t\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\t\treturn { command, result };\n\t\t\t};\n\t\t\tconst asDirectory = await run(SandboxFileSystem.realpathScripts[0]);\n\t\t\tif (asDirectory.result.exitCode === 0) return (asDirectory.result.result ?? \"\").trimEnd();\n\t\t\tconst asFile = await run(SandboxFileSystem.realpathScripts[1]);\n\t\t\tassertCommandSucceeded(asFile.command, asFile.result);\n\t\t\treturn (asFile.result.result ?? \"\").trimEnd();\n\t\t},\n\t};\n\n\treturn filesystem;\n};\n\n// Daytona's execute API folds stderr into `result` and reports a single exit\n// code, so the shell surfaces the combined output as stdout and leaves stderr\n// empty rather than inventing a split.\nconst runCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\topts?: { env?: Record<string, string>; cwd?: string },\n) =>\n\tEffect.tryPromise({\n\t\ttry: () =>\n\t\t\tsandbox.process.executeCommand(command, resolveCwd(options.cwd, opts?.cwd), opts?.env, options.execTimeout),\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t}).pipe(Effect.map((response) => ({ stdout: response.result ?? \"\", stderr: \"\", exitCode: response.exitCode })));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\trunCommand(sandbox, options, command, opts);\n\n// `executeCommand` takes a single string, so the vector is quoted here rather\n// than spawned; the per-call cwd rides the toolbox's own cwd argument instead\n// of a `cd` prefix.\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) =>\n\t\trunCommand(sandbox, options, quoteArgv(argv), opts);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn SandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, mounted), { cwd }));\n\t\t}),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn Shell.of({ exec: exec(sandbox, mounted), execArgv: execArgv(sandbox, mounted) });\n\t\t}),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * Mount wrappers supply an absolute cwd to every public operation. Internal\n * filesystem helper commands already receive absolute paths, so the transport\n * itself keeps no mutable working-directory state and owns no resource\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Daytona's locator is the sandbox id. See `SandboxResource` for why this is a\n// shared tag rather than a Daytona-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.id })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, ({ cwd }) =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"daytona\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Daytona sandbox provides the runtime filesystem service directly plus\n * the sandbox's native remote shell. It intentionally does not provide VFS:\n * remote filesystems have no synchronous filesystem surface.\n */\nexport const layer = (options: Options = {}): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, DaytonaError> =>\n\tLayer.mergeAll(filesystemLayer(options), shellLayer(options), identityLayer(options), resourceLayer).pipe(\n\t\tLayer.provide(remote(options)),\n\t);\n\nexport const services = layer;\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver, SandboxInstance, SandboxProvider } from \"../../sandbox.ts\";\nimport * as EnvDaytona from \"./provider.ts\";\n\nexport const Options = Schema.Struct({\n\tapiKey: Schema.optional(Schema.String),\n\tapiUrl: Schema.optional(Schema.String),\n\ttarget: Schema.optional(Schema.String),\n});\nexport type Options = typeof Options.Type;\nexport const ClientOptions = Options;\nexport type ClientOptions = Options;\n\nexport const ResourcesConfig = Schema.Struct({\n\tcpu: Schema.optional(Schema.Finite),\n\tgpu: Schema.optional(Schema.Finite),\n\tmemory: Schema.optional(Schema.Finite),\n\tdisk: Schema.optional(Schema.Finite),\n});\nexport type ResourcesConfig = typeof ResourcesConfig.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\timage: Schema.optional(Schema.String),\n\tlanguage: Schema.optional(Schema.String),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tresources: Schema.optional(ResourcesConfig),\n\tuser: Schema.optional(Schema.String),\n\tcwd: Schema.optional(Schema.String),\n\tautoStopInterval: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tuser: Schema.optional(Schema.String),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"daytona\");\ntype DaytonaSdk = typeof import(\"@daytona/sdk\");\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\nconst statusFrom = (\n\tstate: RemoteSandbox[\"state\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => {\n\tconst providerStatus = state ?? \"unknown\";\n\treturn {\n\t\tstatus:\n\t\t\tstate === \"stopped\" || state === \"archived\"\n\t\t\t\t? \"offline\"\n\t\t\t\t: state === \"stopping\" || state === \"archiving\" || state === \"snapshotting\" || state === \"destroying\"\n\t\t\t\t\t? \"suspending\"\n\t\t\t\t\t: state === \"destroyed\"\n\t\t\t\t\t\t? \"unavail\"\n\t\t\t\t\t\t: state === \"error\" || state === \"build_failed\" || state === \"unknown\"\n\t\t\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t\t\t: \"online\",\n\t\tproviderStatus,\n\t};\n};\n\nconst shouldWake = (sandbox: RemoteSandbox): boolean => sandbox.state === \"stopped\" || sandbox.state === \"archived\";\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst redact = SandboxProvider.makeRedactor([client.apiKey ?? \"\"]);\n\tconst daytona = (sdk: DaytonaSdk) =>\n\t\tnew sdk.Daytona({\n\t\t\t...(client.apiKey === undefined ? {} : { apiKey: client.apiKey }),\n\t\t\t...(client.apiUrl === undefined ? {} : { apiUrl: client.apiUrl }),\n\t\t\t...(client.target === undefined ? {} : { target: client.target }),\n\t\t});\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: (sdk: DaytonaSdk) => Promise<A>,\n\t): Effect.Effect<A, SandboxProvider.SandboxProviderError> =>\n\t\tEffect.suspend(() => {\n\t\t\tlet sdk: DaytonaSdk | undefined;\n\t\t\treturn Effect.tryPromise({\n\t\t\t\ttry: () =>\n\t\t\t\t\timport(\"@daytona/sdk\").then((loaded) => {\n\t\t\t\t\t\tsdk = loaded;\n\t\t\t\t\t\treturn run(loaded);\n\t\t\t\t\t}),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tSandboxProvider.providerError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\tredact,\n\t\t\t\t\t\tnotFound: sdk !== undefined && cause instanceof sdk.DaytonaNotFoundError,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t});\n\n\tconst get = (providerResourceId: string, operation: string) =>\n\t\tattempt(operation, (sdk) => daytona(sdk).get(providerResourceId));\n\n\tconst refresh = (sandbox: RemoteSandbox, operation: string) =>\n\t\tattempt(operation, () => sandbox.refreshData()).pipe(Effect.as(sandbox));\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.state),\n\t\tmetadata: {\n\t\t\ttarget: sandbox.target,\n\t\t},\n\t});\n\n\tconst wake = (sandbox: RemoteSandbox, operation: string) =>\n\t\tshouldWake(sandbox)\n\t\t\t? attempt(operation, () => sandbox.start()).pipe(Effect.map(() => sandbox))\n\t\t\t: Effect.succeed(sandbox);\n\n\tconst runtime = (\n\t\tdefaultCwd: string,\n\t\tinput: { readonly user?: string | undefined; readonly execTimeout?: number | undefined },\n\t) => ({\n\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(defaultCwd),\n\t\t...(input.user === undefined ? {} : { user: input.user }),\n\t\t...(input.execTimeout === undefined ? {} : { execTimeout: input.execTimeout }),\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\t// Installed SDK 0.187.0 has no cancellation signal on\n\t\t\t// executeCommand; session execution cannot carry cwd/env safely.\n\t\t\tcancels: false,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst base = {\n\t\t\t\t\tlanguage: config.language ?? \"typescript\",\n\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t...(config.user === undefined ? {} : { user: config.user }),\n\t\t\t\t\t...(config.autoStopInterval === undefined ? {} : { autoStopInterval: config.autoStopInterval }),\n\t\t\t\t\tautoDeleteInterval: -1,\n\t\t\t\t\tlabels: {\n\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst sandbox = yield* attempt(\"create\", (loaded) => {\n\t\t\t\t\tconst sdk = daytona(loaded);\n\t\t\t\t\treturn config.image === undefined\n\t\t\t\t\t\t? sdk.create({ ...base, ...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }) })\n\t\t\t\t\t\t: sdk.create({\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\timage: config.image,\n\t\t\t\t\t\t\t\t...(config.resources === undefined ? {} : { resources: config.resources as Resources }),\n\t\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst defaultCwd = yield* attempt(\"create.cwd\", () =>\n\t\t\t\t\tEnvDaytona.mountCwd(config.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.state);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.id,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: runtime(defaultCwd, config),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttarget: sandbox.target,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst sandbox = yield* get(providerResourceId, \"runtimeConfigFor\");\n\t\t\t\tconst defaultCwd =\n\t\t\t\t\toverrides?.defaultCwd ??\n\t\t\t\t\tSandboxDriver.AbsolutePath.make(\n\t\t\t\t\t\tyield* attempt(\"runtimeConfigFor.cwd\", () =>\n\t\t\t\t\t\t\tEnvDaytona.mountCwd(undefined, () => sandbox.getWorkDir()),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdefaultCwd,\n\t\t\t\t\t...(overrides?.user === undefined ? { user: sandbox.user } : { user: overrides.user }),\n\t\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t\t};\n\t\t\t}),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst sandbox = yield* get(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t);\n\t\t\t\t\tyield* wake(sandbox, \"attach.wake\");\n\t\t\t\t\treturn EnvDaytona.transport(\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(refresh(sandbox, \"inspect.refresh\"), observed),\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(wake(sandbox, \"wake.start\"), observed),\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nconst sandbox = SandboxDriver.module({\n\tapiVersion: SandboxDriver.apiVersion,\n\tname,\n\toptions: Options,\n\tmake,\n});\n\nexport const config = (value: CreateConfig) => ({ driver: \"daytona\" as const, config: value });\n\nexport default sandbox;\n","import { posix } from \"../../util/posix.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\n\n// The provider contract and FileStat live in `filesystem.ts` (the single source of truth, VFS-free).\n// A remote provider implements this Interface; `make` wraps\n// it into the same runtime surface the local vfs backend exposes.\nexport type FileStat = SandboxFileSystem.FileStat;\n\n// Remote-aware callers can opt into metadata that is not part of the generic\n// SandboxFileSystem surface. In particular, `stat` keeps the familiar\n// provider-level meaning, while `lstat` explicitly asks for the directory entry\n// itself so symlink identity is not inferred from a method with mixed provider\n// semantics.\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\t/**\n\t * Optional remote working directory for relative paths. When omitted, relative\n\t * paths are passed through so the remote provider can use its own default cwd.\n\t */\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/**\n * Wrap a remote provider into the runtime filesystem surface: resolve relative\n * paths against `cwd`, and nothing else. Parent creation and `rm` option\n * validation are the runtime's job and live in `SandboxFileSystem.fromProvider`,\n * which every backend passes through — putting them here would cover only the\n * backends that happen to use this wrapper.\n */\nexport const make = (provider: Interface, options?: Options): SandboxFileSystem.Provider => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\t// option validation happens in `fromProvider`, before any mutation\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t\trealpath: (path) => provider.realpath(resolve(path)),\n\t};\n};\n\nexport const withProvider = make;\n","/* oxlint-disable effecttsgo/async-function -- Vercel's sandbox SDK boundary is Promise-based. */\nimport { Context, Effect, Layer, Schema, Stream } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { makeRedactor, type Redactor, sanitizeError as sanitizeSandboxError } from \"../../sandbox/errors.ts\";\nimport { SandboxFileSystem } from \"../../sandbox/fs/filesystem.ts\";\nimport { SandboxInstance } from \"../../sandbox/instance.ts\";\nimport { SandboxIO } from \"../../sandbox/io.ts\";\nimport { SandboxResource } from \"../../sandbox/resource.ts\";\nimport {\n\ttype ExecChunk,\n\ttype ExecResult,\n\ttype ISandboxExe,\n\tquoteArgv,\n\tresolveCwd,\n\tShell,\n\tShellError,\n} from \"../../sandbox/shell/shell.ts\";\nimport * as RemoteFileSystem from \"./fs.ts\";\n\nconst utf8 = new TextEncoder();\ntype Command = import(\"@vercel/sandbox\").Command;\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\n/** Vercel's namespace-intrinsic working directory. */\nexport const DEFAULT_CWD = \"/vercel/sandbox\";\n\nexport class VercelError extends Schema.TaggedError<VercelError>()(\"VercelError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nconst ApiFailure = Schema.Struct({\n\tjson: Schema.Struct({\n\t\terror: Schema.Struct({\n\t\t\tmessage: Schema.optional(Schema.String),\n\t\t\tcode: Schema.optional(Schema.String),\n\t\t}),\n\t}),\n});\nconst isApiFailure = Schema.is(ApiFailure);\n\n/** Prefer Vercel's structured API failure while retaining the shared redaction boundary. */\nexport const sanitizeProviderError = (\n\tcause: unknown,\n\tredact: Redactor = makeRedactor(),\n): SandboxInstance.PersistedError => {\n\tconst fallback = sanitizeSandboxError(cause, redact);\n\tif (!isApiFailure(cause)) return fallback;\n\tconst message = cause.json.error.message?.trim();\n\tconst code = cause.json.error.code?.trim();\n\treturn {\n\t\t...fallback,\n\t\t...(message === undefined || message.length === 0 ? {} : { message: redact(message) }),\n\t\t...(code === undefined || code.length === 0 ? {} : { code: redact(code) }),\n\t};\n};\n\n/**\n * Vercel API credentials. Either all three are provided together or none are:\n * when omitted, the SDK resolves them from the `VERCEL_OIDC_TOKEN` env var\n * (the token's payload carries the project and team ids).\n */\nexport interface Credentials {\n\treadonly token: string;\n\treadonly teamId: string;\n\treadonly projectId: string;\n}\n\nexport interface Options {\n\t/** Auth token (OIDC or access token). Falls back to `VERCEL_OIDC_TOKEN`. */\n\treadonly token?: string | undefined;\n\t/** Team id. Derived from the OIDC token when omitted. */\n\treadonly teamId?: string | undefined;\n\t/** Project id. Derived from the OIDC token when omitted. */\n\treadonly projectId?: string | undefined;\n\t/** Reuse an existing sandbox by name instead of creating one. */\n\treadonly sandboxName?: string | undefined;\n\t/** Explicit name for a newly created sandbox. */\n\treadonly name?: string | undefined;\n\t/** Provider-side diagnostic labels (maximum five). */\n\treadonly tags?: Record<string, string> | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot id to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Source to seed the sandbox filesystem from (git or tarball). */\n\treadonly source?:\n\t\t| {\n\t\t\t\treadonly type: \"git\";\n\t\t\t\treadonly url: string;\n\t\t\t\treadonly revision?: string | undefined;\n\t\t\t\treadonly depth?: number | undefined;\n\t\t }\n\t\t| { readonly type: \"tarball\"; readonly url: string };\n\t/** Runtime used by the sandbox. Defaults to the SDK default (`node24`). */\n\treadonly runtime?: string | undefined;\n\t/** Ports to expose from the sandbox (max 4). */\n\treadonly ports?: number[] | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** vCPU allocation (memory scales at 2048 MB per vCPU). */\n\treadonly vcpus?: number | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `/vercel/sandbox`;\n\t * omitted values use that namespace default.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Milliseconds before the sandbox auto-terminates. */\n\treadonly timeout?: number | undefined;\n\t/** Per-command timeout in milliseconds. Omit for no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandboxes/vercel/provider/Remote\") {}\n\n// Vercel requires all three credential fields together or none — partial\n// credentials are rejected by the SDK — so only forward them when complete.\nexport const credentialsFrom = (options: Options): Credentials | undefined =>\n\toptions.token !== undefined && options.teamId !== undefined && options.projectId !== undefined\n\t\t? { token: options.token, teamId: options.teamId, projectId: options.projectId }\n\t\t: undefined;\n\nexport const createSandbox = async (options: Options, creds: Credentials | undefined = credentialsFrom(options)) => {\n\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\tconst withCreds = <T extends object>(params: T) => (creds ? { ...params, ...creds } : params);\n\tconst source =\n\t\toptions.source?.type === \"git\"\n\t\t\t? {\n\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\turl: options.source.url,\n\t\t\t\t\t...(options.source.revision === undefined ? {} : { revision: options.source.revision }),\n\t\t\t\t\t...(options.source.depth === undefined ? {} : { depth: options.source.depth }),\n\t\t\t\t}\n\t\t\t: options.source;\n\tconst base = {\n\t\t...(options.name === undefined ? {} : { name: options.name }),\n\t\t...(options.tags === undefined ? {} : { tags: options.tags }),\n\t\t...(options.envVars === undefined ? {} : { env: options.envVars }),\n\t\t...(options.ports === undefined ? {} : { ports: options.ports }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.vcpus === undefined ? {} : { resources: { vcpus: options.vcpus } }),\n\t};\n\treturn options.snapshot !== undefined\n\t\t? Sandbox.create(withCreds({ ...base, source: { type: \"snapshot\" as const, snapshotId: options.snapshot } }))\n\t\t: Sandbox.create(\n\t\t\t\twithCreds({\n\t\t\t\t\t...base,\n\t\t\t\t\t...(options.runtime === undefined ? {} : { runtime: options.runtime }),\n\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t}),\n\t\t\t);\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\t\t\t\tconst creds = credentialsFrom(options);\n\t\t\t\tconst sandbox = options.sandboxName\n\t\t\t\t\t? await Sandbox.get(creds ? { ...creds, name: options.sandboxName } : { name: options.sandboxName })\n\t\t\t\t\t: await createSandbox(options, creds);\n\t\t\t\treturn { sandbox };\n\t\t\t},\n\t\t\tcatch: (cause) => new VercelError({ sanitized: sanitizeProviderError(cause) }),\n\t\t}),\n\t);\n\ninterface Stats {\n\treadonly size: number;\n\treadonly mtime: Date;\n\treadonly isFile: () => boolean;\n\treadonly isDirectory: () => boolean;\n\treadonly isSymbolicLink: () => boolean;\n}\n\nexport const statsFrom = (stats: Stats): RemoteFileSystem.FileStat => {\n\tconst mtime = stats.mtime;\n\n\t// omit size/mtime the stat could not report — never fabricate\n\treturn {\n\t\tisFile: stats.isFile(),\n\t\tisDirectory: stats.isDirectory(),\n\t\tisSymbolicLink: stats.isSymbolicLink(),\n\t\t...(Number.isFinite(stats.size) ? { size: stats.size } : {}),\n\t\t...(mtime instanceof Date && !Number.isNaN(mtime.getTime()) ? { mtime } : {}),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\" | \"realpath\"\n>;\n\n// The Vercel `fs` surface is `node:fs/promises`-compatible, so the provider\n// maps almost directly. The `RemoteFileSystem.make` wrapper resolves relative\n// paths against `cwd` and guarantees parent creation on `writeFile`. Only\n// `realpath` has no fs counterpart and shells out.\nconst providerFrom = (sandbox: RemoteSandbox, options: Options): RemoteFilesystemProvider => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: (path: string) => sandbox.fs.readFile(path, \"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.readFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.writeFile(path, typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content)),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.stat(path)),\n\t\t// Keep symlink identity explicit: Vercel's `stat` follows symlinks\n\t\t// (`stat -L`), so remote-aware callers must ask for `lstat` when they\n\t\t// need the entry itself instead of the target's metadata.\n\t\tlstat: async (path: string) => statsFrom(await sandbox.fs.lstat(path)),\n\t\t// `withFileTypes` lists via `find`, which includes dotfiles (`.git` …);\n\t\t// the bare `readdir` shells out to `ls -1` and would drop them.\n\t\treaddir: async (path: string) => (await sandbox.fs.readdir(path, { withFileTypes: true })).map((e) => e.name),\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tif (SandboxFileSystem.isNotFoundError(cause)) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tawait sandbox.fs.mkdir(\n\t\t\t\tpath,\n\t\t\t\tmkdirOptions?.recursive === undefined ? {} : { recursive: mkdirOptions.recursive },\n\t\t\t);\n\t\t},\n\t\t// `rm -f` is native, so force/recursive delegate straight through; the\n\t\t// wrapper has already rejected any unsupported option before we get here.\n\t\trm: (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) =>\n\t\t\tsandbox.fs.rm(path, {\n\t\t\t\t...(rmOptions?.recursive === undefined ? {} : { recursive: rmOptions.recursive }),\n\t\t\t\t...(rmOptions?.force === undefined ? {} : { force: rmOptions.force }),\n\t\t\t}),\n\t\trealpath: async (path: string) => {\n\t\t\tfor (const script of SandboxFileSystem.realpathScripts) {\n\t\t\t\tconst result = await (await spawnArgv(sandbox, options, [\"sh\", \"-c\", script, \"_\", path])).wait();\n\t\t\t\tif (result.exitCode === 0) return (await result.stdout()).trimEnd();\n\t\t\t}\n\t\t\t// same shape `fs.stat` rejects with, so `isNotFoundError` recognises it\n\t\t\tthrow Object.assign(new Error(`ENOENT: no such file or directory, realpath '${path}'`), { code: \"ENOENT\" });\n\t\t},\n\t};\n\n\treturn filesystem;\n};\n\n// Arbitrary command strings run through `sh -c` to match the single-string\n// contract the rest of the harness expects. Commands run **detached** so the\n// returned `Command` exposes `kill`/`logs`/`wait`: a `cwd`/`env` is threaded in,\n// and the per-command `execTimeout` is a server-side SIGKILL deadline.\nconst spawn = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => spawnArgv(sandbox, options, [\"sh\", \"-c\", command], env, cwd);\n\n// Vercel spawns a program with a real argument vector, so `execArgv` needs no\n// quoting at all — the args never pass through a shell.\nconst spawnArgv = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\targv: ReadonlyArray<string>,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => {\n\tconst resolvedCwd = resolveCwd(options.cwd, cwd);\n\treturn sandbox.runCommand({\n\t\tcmd: argv[0]!,\n\t\targs: argv.slice(1),\n\t\t...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }),\n\t\t...(env === undefined ? {} : { env }),\n\t\tdetached: true,\n\t\t...(options.execTimeout === undefined ? {} : { timeoutMs: options.execTimeout }),\n\t});\n};\n\n// Acquire a detached command and register its kill as a scope finalizer, so an\n// interrupt / timeout from the consumer actually terminates the remote process\n// (best-effort SIGKILL) instead of leaving it running server-side.\n// `command` labels failures only; the spawn itself is supplied by the caller so\n// string and argv execution share one kill finalizer.\nconst acquireWith = (command: string, run: () => Promise<Command>) =>\n\tEffect.acquireRelease(Effect.tryPromise({ try: run, catch: (cause) => new ShellError({ command, cause }) }), (cmd) =>\n\t\tEffect.promise(() => cmd.kill(\"SIGKILL\").catch(() => {})),\n\t);\n\n// Vercel reports stdout and stderr separately with a distinct exit code, so the\n// shell surfaces both streams faithfully.\nconst collect = (command: string) => (cmd: Command) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<ExecResult> => {\n\t\t\tconst result = await cmd.wait();\n\t\t\tconst [stdout, stderr] = await Promise.all([result.stdout(), result.stderr()]);\n\t\t\treturn { stdout, stderr, exitCode: result.exitCode };\n\t\t},\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t});\n\nconst acquireCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n) => acquireWith(command, () => spawn(sandbox, options, command, env, cwd));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) => {\n\t\t// quoted for the error label only — the spawn passes argv through untouched\n\t\tconst command = quoteArgv(argv);\n\t\treturn acquireWith(command, () => spawnArgv(sandbox, options, argv, opts?.env, opts?.cwd)).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\t};\n\n// Streaming output via `Command.logs` (an async generator of stdout/stderr\n// entries), followed by the exit code from `wait`. The kill finalizer fires when\n// the consuming scope closes (interrupt / timeout).\nconst stream =\n\t(sandbox: RemoteSandbox, options: Options): NonNullable<ISandboxExe[\"stream\"]> =>\n\t(command, opts) =>\n\t\tStream.unwrap(\n\t\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\t\tEffect.map((cmd) => {\n\t\t\t\t\tconst logs = Stream.fromAsyncIterable(cmd.logs(), (cause) => new ShellError({ command, cause })).pipe(\n\t\t\t\t\t\tStream.map((log): ExecChunk => ({ _tag: log.stream, bytes: utf8.encode(log.data) })),\n\t\t\t\t\t);\n\t\t\t\t\tconst exit = Stream.fromEffect(\n\t\t\t\t\t\tEffect.tryPromise({ try: () => cmd.wait(), catch: (cause) => new ShellError({ command, cause }) }),\n\t\t\t\t\t).pipe(Stream.map((finished): ExecChunk => ({ _tag: \"exit\", exitCode: finished.exitCode })));\n\t\t\t\t\treturn Stream.concat(logs, exit);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tSandboxFileSystem.fromProvider(\n\t\t\t\tRemoteFileSystem.make(\n\t\t\t\t\tproviderFrom(sandbox, options),\n\t\t\t\t\toptions.cwd === undefined ? undefined : { cwd: options.cwd },\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * The controller binds a cwd per mount, so neither filesystem nor shell stores\n * one here. The returned layer owns no provider resource and has no deletion\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Vercel's locator is the sandbox name. See `SandboxResource` for why this is a\n// shared tag rather than a Vercel-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.name })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, () =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"vercel\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: DEFAULT_CWD,\n\t\t\t\t...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Vercel sandbox provides the runtime filesystem service directly plus the\n * sandbox's native remote shell. It intentionally does not provide VFS: remote\n * filesystems have no synchronous filesystem surface.\n */\nexport const layer = (\n\toptions: Options = {},\n): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, VercelError> => {\n\tconst mounted = { ...options, cwd: SandboxIO.resolveMountCwd(DEFAULT_CWD, options.cwd) };\n\treturn Layer.mergeAll(filesystemLayer(mounted), shellLayer(mounted), identityLayer(mounted), resourceLayer).pipe(\n\t\tLayer.provide(remote(mounted)),\n\t);\n};\n\nexport const services = layer;\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver, SandboxInstance, SandboxProvider } from \"../../sandbox.ts\";\nimport * as EnvVercel from \"./provider.ts\";\n\nexport const Options = Schema.Struct({\n\ttoken: Schema.optional(Schema.String),\n\tteamId: Schema.optional(Schema.String),\n\tprojectId: Schema.optional(Schema.String),\n});\nexport type Options = typeof Options.Type;\nexport const ClientOptions = Options;\nexport type ClientOptions = Options;\n\nexport const Source = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"git\"),\n\t\turl: Schema.String,\n\t\trevision: Schema.optional(Schema.String),\n\t\tdepth: Schema.optional(Schema.Finite),\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"tarball\"),\n\t\turl: Schema.String,\n\t}),\n]);\nexport type Source = typeof Source.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\tsource: Schema.optional(Source),\n\truntime: Schema.optional(Schema.String),\n\tports: Schema.optional(Schema.Array(Schema.Finite)),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tvcpus: Schema.optional(Schema.Finite),\n\ttimeout: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"vercel\");\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\nconst statusFrom = (\n\tstatus: RemoteSandbox[\"status\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => ({\n\tstatus:\n\t\tstatus === \"stopped\"\n\t\t\t? \"offline\"\n\t\t\t: status === \"stopping\" || status === \"snapshotting\"\n\t\t\t\t? \"suspending\"\n\t\t\t\t: status === \"failed\" || status === \"aborted\"\n\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t: \"online\",\n\tproviderStatus: status,\n});\n\nconst isNotFound = (cause: unknown): boolean => {\n\tif (typeof cause !== \"object\" || cause === null) return false;\n\tconst response = \"response\" in cause && cause.response instanceof Response ? cause.response : undefined;\n\tconst code =\n\t\t\"code\" in cause && typeof cause.code === \"string\"\n\t\t\t? cause.code\n\t\t\t: \"json\" in cause &&\n\t\t\t\t typeof cause.json === \"object\" &&\n\t\t\t\t cause.json !== null &&\n\t\t\t\t \"error\" in cause.json &&\n\t\t\t\t typeof cause.json.error === \"object\" &&\n\t\t\t\t cause.json.error !== null &&\n\t\t\t\t \"code\" in cause.json.error &&\n\t\t\t\t typeof cause.json.error.code === \"string\"\n\t\t\t\t? cause.json.error.code\n\t\t\t\t: undefined;\n\treturn response?.status === 404 || code === \"not_found\" || code === \"sandbox_not_found\";\n};\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst credentials = EnvVercel.credentialsFrom(client);\n\tconst redact = SandboxProvider.makeRedactor([client.token ?? \"\"]);\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: () => Promise<A>,\n\t): Effect.Effect<A, SandboxProvider.SandboxProviderError> =>\n\t\tEffect.tryPromise({\n\t\t\ttry: run,\n\t\t\tcatch: (cause) =>\n\t\t\t\tSandboxProvider.providerError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation,\n\t\t\t\t\tcause,\n\t\t\t\t\tredact,\n\t\t\t\t\tsanitize: EnvVercel.sanitizeProviderError,\n\t\t\t\t\tnotFound: isNotFound(cause),\n\t\t\t\t}),\n\t\t});\n\n\tconst get = (providerResourceId: string, resume: boolean, operation: string) =>\n\t\tattempt(operation, () =>\n\t\t\timport(\"@vercel/sandbox\").then(({ Sandbox }) =>\n\t\t\t\tSandbox.get(\n\t\t\t\t\tcredentials === undefined\n\t\t\t\t\t\t? { name: providerResourceId, resume }\n\t\t\t\t\t\t: { ...credentials, name: providerResourceId, resume },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.status),\n\t\tmetadata: {\n\t\t\tcwd: sandbox.cwd,\n\t\t},\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\tinspect: true,\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst source =\n\t\t\t\t\tconfig.source?.type === \"git\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\t\t\t\turl: config.source.url,\n\t\t\t\t\t\t\t\t...(config.source.revision === undefined ? {} : { revision: config.source.revision }),\n\t\t\t\t\t\t\t\t...(config.source.depth === undefined ? {} : { depth: config.source.depth }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: config.source;\n\t\t\t\tconst sandbox = yield* attempt(\"create\", () =>\n\t\t\t\t\tEnvVercel.createSandbox(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...client,\n\t\t\t\t\t\t\t...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }),\n\t\t\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t\t\t\t...(config.runtime === undefined ? {} : { runtime: config.runtime }),\n\t\t\t\t\t\t\t...(config.ports === undefined ? {} : { ports: [...config.ports] }),\n\t\t\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t\t\t...(config.vcpus === undefined ? {} : { vcpus: config.vcpus }),\n\t\t\t\t\t\t\t...(config.timeout === undefined ? {} : { timeout: config.timeout }),\n\t\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t\t\ttags: {\n\t\t\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcredentials,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.status);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.name,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tcwd: sandbox.cwd,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.map(get(providerResourceId, false, \"runtimeConfigFor\"), (sandbox) => ({\n\t\t\t\tdefaultCwd: overrides?.defaultCwd ?? SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t})),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.map(\n\t\t\t\t\tget(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t),\n\t\t\t\t\t(sandbox) =>\n\t\t\t\t\t\tEnvVercel.transport(\n\t\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\ttrue,\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nconst sandbox = SandboxDriver.module({\n\tapiVersion: SandboxDriver.apiVersion,\n\tname,\n\toptions: Options,\n\tmake,\n});\n\nexport const config = (value: CreateConfig) => ({ driver: \"vercel\" as const, config: value });\n\nexport default sandbox;\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { posix as path } from \"../util/posix.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\n\n// TODO: shouldn't it be called GitError or something\nexport class AppProcessError extends Schema.TaggedError<AppProcessError>()(\"AppProcessError\", {\n\tcommand: Schema.String,\n\texitCode: Schema.optional(Schema.Finite),\n\tstderr: Schema.optional(Schema.String),\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface Result {\n\treadonly exitCode: number;\n\treadonly text: string;\n\treadonly stderr: string;\n}\n\nexport type RevParse = \"--show-toplevel\" | \"--git-dir\" | \"--git-common-dir\";\n\nexport interface Interface {\n\t/** Run `git <args>` in `directory`; fails only when the process cannot be spawned. */\n\treadonly exec: (directory: string, args: ReadonlyArray<string>) => Effect.Effect<Result, AppProcessError>;\n\treadonly revParse: (directory: string, arg: RevParse) => Effect.Effect<string | undefined>;\n\treadonly remote: (directory: string, name?: string) => Effect.Effect<string | undefined>;\n\treadonly roots: (directory: string) => Effect.Effect<string[]>;\n\treadonly origin: (directory: string) => Effect.Effect<string | undefined>;\n\treadonly head: (directory: string) => Effect.Effect<string | undefined>;\n\treadonly dir: (directory: string) => Effect.Effect<string | undefined>;\n\treadonly branch: (directory: string) => Effect.Effect<string | undefined>;\n\treadonly remoteHead: (directory: string) => Effect.Effect<string | undefined>;\n\treadonly clone: (input: {\n\t\tremote: string;\n\t\ttarget: string;\n\t\tbranch?: string;\n\t\tdepth?: number;\n\t}) => Effect.Effect<Result, AppProcessError>;\n\treadonly fetch: (directory: string) => Effect.Effect<Result, AppProcessError>;\n\treadonly fetchBranch: (directory: string, branch: string) => Effect.Effect<Result, AppProcessError>;\n\treadonly checkout: (directory: string, branch: string) => Effect.Effect<Result, AppProcessError>;\n\treadonly reset: (directory: string, target: string) => Effect.Effect<Result, AppProcessError>;\n\treadonly push: (input: {\n\t\treadonly directory: string;\n\t\treadonly refspec: string;\n\t\treadonly remote?: string;\n\t\treadonly env?: Record<string, string>;\n\t}) => Effect.Effect<Result, AppProcessError>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/git/git/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst shell = yield* SandboxIO.Shell;\n\n\t\t// Arguments go through `execArgv`, never a command string: branch names and\n\t\t// paths are caller-supplied, and a space or `$(…)` in one must stay data.\n\t\tconst execute =\n\t\t\t(cwd: string) => (args: ReadonlyArray<string>, options?: { readonly env?: Record<string, string> }) =>\n\t\t\t\tshell\n\t\t\t\t\t.execArgv([\"git\", ...args], {\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t...(options?.env === undefined ? {} : { env: options.env }),\n\t\t\t\t\t})\n\t\t\t\t\t.pipe(\n\t\t\t\t\t\tEffect.map(\n\t\t\t\t\t\t\t(result) =>\n\t\t\t\t\t\t\t\t({\n\t\t\t\t\t\t\t\t\texitCode: result.exitCode,\n\t\t\t\t\t\t\t\t\ttext: result.stdout,\n\t\t\t\t\t\t\t\t\tstderr: result.stderr,\n\t\t\t\t\t\t\t\t}) satisfies Result,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.mapError((cause) => new AppProcessError({ command: [\"git\", ...args].join(\" \"), cause })),\n\t\t\t\t\t);\n\n\t\tconst run = (cwd: string) => (args: ReadonlyArray<string>) =>\n\t\t\texecute(cwd)(args).pipe(Effect.orElseSucceed(() => ({ exitCode: 1, text: \"\", stderr: \"\" })));\n\n\t\tconst exec = Effect.fn(\"Git.exec\")((directory: string, args: ReadonlyArray<string>) => execute(directory)(args));\n\n\t\tconst revParse = Effect.fn(\"Git.revParse\")(function* (directory: string, arg: RevParse) {\n\t\t\tconst result = yield* run(directory)([\"rev-parse\", arg]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn resolvePath(directory, result.text);\n\t\t});\n\n\t\tconst remote = Effect.fn(\"Git.remote\")(function* (directory: string, name = \"origin\") {\n\t\t\tconst result = yield* run(directory)([\"remote\", \"get-url\", name]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn result.text.trim() || undefined;\n\t\t});\n\n\t\tconst roots = Effect.fn(\"Git.roots\")(function* (directory: string) {\n\t\t\tconst result = yield* run(directory)([\"rev-list\", \"--max-parents=0\", \"HEAD\"]);\n\t\t\tif (result.exitCode !== 0) return [];\n\t\t\treturn result.text\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((item) => item.trim())\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.toSorted();\n\t\t});\n\n\t\tconst origin = Effect.fn(\"Git.origin\")(function* (directory: string) {\n\t\t\tconst result = yield* run(directory)([\"config\", \"--get\", \"remote.origin.url\"]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn result.text.trim() || undefined;\n\t\t});\n\n\t\tconst head = Effect.fn(\"Git.head\")(function* (directory: string) {\n\t\t\tconst result = yield* run(directory)([\"rev-parse\", \"HEAD\"]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn result.text.trim() || undefined;\n\t\t});\n\n\t\tconst dir = Effect.fn(\"Git.dir\")(function* (directory: string) {\n\t\t\tconst result = yield* revParse(directory, \"--git-dir\");\n\t\t\treturn result === undefined ? undefined : AbsolutePath.make(result);\n\t\t});\n\n\t\tconst branch = Effect.fn(\"Git.branch\")(function* (directory: string) {\n\t\t\tconst result = yield* run(directory)([\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn result.text.trim() || undefined;\n\t\t});\n\n\t\tconst remoteHead = Effect.fn(\"Git.remoteHead\")(function* (directory: string) {\n\t\t\tconst result = yield* run(directory)([\"symbolic-ref\", \"refs/remotes/origin/HEAD\"]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn result.text.trim().replace(/^refs\\/remotes\\//, \"\") || undefined;\n\t\t});\n\n\t\tconst clone = Effect.fn(\"Git.clone\")(\n\t\t\t(input: { remote: string; target: string; branch?: string; depth?: number }) =>\n\t\t\t\texecute(path.dirname(input.target))([\n\t\t\t\t\t\"clone\",\n\t\t\t\t\t\"--depth\",\n\t\t\t\t\tString(input.depth ?? 100),\n\t\t\t\t\t...(input.branch ? [\"--branch\", input.branch] : []),\n\t\t\t\t\t\"--\",\n\t\t\t\t\tinput.remote,\n\t\t\t\t\tinput.target,\n\t\t\t\t]),\n\t\t);\n\n\t\tconst fetch = Effect.fn(\"Git.fetch\")((directory: string) => execute(directory)([\"fetch\", \"--all\", \"--prune\"]));\n\n\t\tconst fetchBranch = Effect.fn(\"Git.fetchBranch\")((directory: string, branch: string) =>\n\t\t\texecute(directory)([\"fetch\", \"origin\", `+refs/heads/${branch}:refs/remotes/origin/${branch}`]),\n\t\t);\n\n\t\tconst checkout = Effect.fn(\"Git.checkout\")((directory: string, branch: string) =>\n\t\t\texecute(directory)([\"checkout\", \"-B\", branch, `origin/${branch}`]),\n\t\t);\n\n\t\tconst reset = Effect.fn(\"Git.reset\")((directory: string, target: string) =>\n\t\t\texecute(directory)([\"reset\", \"--hard\", target]),\n\t\t);\n\n\t\tconst push = Effect.fn(\"Git.push\")(\n\t\t\t(input: {\n\t\t\t\treadonly directory: string;\n\t\t\t\treadonly refspec: string;\n\t\t\t\treadonly remote?: string;\n\t\t\t\treadonly env?: Record<string, string>;\n\t\t\t}) =>\n\t\t\t\texecute(input.directory)(\n\t\t\t\t\t[\"push\", \"--\", input.remote ?? \"origin\", input.refspec],\n\t\t\t\t\tinput.env === undefined ? undefined : { env: input.env },\n\t\t\t\t),\n\t\t);\n\n\t\treturn Service.of({\n\t\t\texec,\n\t\t\trevParse,\n\t\t\tremote,\n\t\t\troots,\n\t\t\torigin,\n\t\t\thead,\n\t\t\tdir,\n\t\t\tbranch,\n\t\t\tremoteHead,\n\t\t\tclone,\n\t\t\tfetch,\n\t\t\tfetchBranch,\n\t\t\tcheckout,\n\t\t\treset,\n\t\t\tpush,\n\t\t});\n\t}),\n);\n\n/**\n * Run git inside the given sandbox — local, remote, or virtual. Every command\n * goes through the sandbox shell, so git never executes anywhere other than\n * where the caller's files live. Discovery and identity live in `repo/`,\n * worktree management in `worktree/`; this module is only the command runner.\n *\n * The sandbox must have a real `git` binary. A VFS-backed shell (`EnvBash`) has\n * builtins only, so commands there exit 127 and every probe reports nothing.\n */\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) => layer.pipe(Layer.provide(sandbox));\n\nexport const defaultLayer = (rootPath: string) => layerWith(Sandbox.defaultLayer(rootPath));\n\n/** Resolve a (possibly relative) git output path against `cwd`, trimming the trailing newline. */\nexport function resolvePath(cwd: string, value: string) {\n\tconst trimmed = value.replace(/[\\r\\n]+$/, \"\");\n\tif (!trimmed) return cwd;\n\tif (path.isAbsolute(trimmed)) return path.normalize(trimmed);\n\treturn path.resolve(cwd, trimmed);\n}\n\nexport * as Git from \"./git.ts\";\n","import { Schema } from \"effect\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\n\nconst Fields = {\n\tdirectory: AbsolutePath,\n\tsandboxInstanceId: SandboxInstance.ID,\n};\n\nexport class DirectoryNotFoundError extends Schema.TaggedError<DirectoryNotFoundError>()(\n\t\"Location.DirectoryNotFoundError\",\n\tFields,\n) {}\n\nexport class NotDirectoryError extends Schema.TaggedError<NotDirectoryError>()(\"Location.NotDirectoryError\", Fields) {}\n\nexport type Error = DirectoryNotFoundError | NotDirectoryError;\n","import { Effect } from \"effect\";\nimport { posix } from \"../../util/posix.ts\";\nimport type { SandboxFileSystem } from \"./filesystem.ts\";\n\n/**\n * Operations derived from the {@link SandboxFileSystem.Interface} primitives.\n *\n * These take the filesystem as an argument rather than living on the service,\n * so every backend — VFS, in-memory, Daytona, Vercel — gets one implementation\n * and none can report them as unsupported. A backend method belongs in the\n * service only when it cannot be expressed in terms of the others.\n *\n * Paths are POSIX, matching the rest of `sandbox/`.\n */\n\n/**\n * Best-effort existence check: a backend that cannot answer reports `false`.\n * Only for callers where an unreliable answer is acceptable — never for one\n * that deletes or overwrites on the strength of an absent result.\n */\nexport const existsOrFalse = (fs: SandboxFileSystem.Interface, path: string) =>\n\tfs.exists(path).pipe(Effect.orElseSucceed(() => false));\n\n/**\n * Walk from `start` towards the root, collecting every `targets` entry that\n * exists along the way. Stops after `stop` when given, otherwise at the root.\n * Results are ordered nearest-first, so `[0]` is the closest match.\n *\n * A probe that fails is treated as a miss and the walk continues: searching is\n * inherently best-effort, and one unreadable directory should not abort it.\n */\nexport const up = Effect.fn(\"SandboxFileSystem.up\")(function* (\n\tfs: SandboxFileSystem.Interface,\n\toptions: { readonly targets: ReadonlyArray<string>; readonly start: string; readonly stop?: string },\n) {\n\tconst found: string[] = [];\n\tlet current = posix.normalize(options.start);\n\tconst stop = options.stop === undefined ? undefined : posix.normalize(options.stop);\n\n\twhile (true) {\n\t\tfor (const target of options.targets) {\n\t\t\tconst candidate = posix.join(current, target);\n\t\t\tif (yield* existsOrFalse(fs, candidate)) found.push(candidate);\n\t\t}\n\n\t\tif (stop === current) break;\n\n\t\tconst parent = posix.dirname(current);\n\t\tif (parent === current) break;\n\t\tcurrent = parent;\n\t}\n\n\treturn found;\n});\n\n/** True when `path` exists and is a directory; false when it is absent or unreadable. */\nexport const isDirectory = Effect.fn(\"SandboxFileSystem.isDirectory\")(function* (\n\tfs: SandboxFileSystem.Interface,\n\tpath: string,\n) {\n\treturn yield* fs.stat(path).pipe(\n\t\tEffect.map((stat) => stat.isDirectory),\n\t\tEffect.orElseSucceed(() => false),\n\t);\n});\n\n/** True when `path` exists and is a regular file; false when it is absent or unreadable. */\nexport const isFile = Effect.fn(\"SandboxFileSystem.isFile\")(function* (fs: SandboxFileSystem.Interface, path: string) {\n\treturn yield* fs.stat(path).pipe(\n\t\tEffect.map((stat) => stat.isFile),\n\t\tEffect.orElseSucceed(() => false),\n\t);\n});\n\n/** Read a file, or `undefined` when it is missing or unreadable. */\nexport const readFileSafe = Effect.fn(\"SandboxFileSystem.readFileSafe\")(function* (\n\tfs: SandboxFileSystem.Interface,\n\tpath: string,\n) {\n\treturn yield* fs.readFile(path).pipe(Effect.orElseSucceed(() => undefined));\n});\n\n/**\n * Canonical path, or the normalized input when the backend cannot resolve it\n * (missing path, no symlink support, transport failure). Best-effort by design.\n */\nexport const realpath = Effect.fn(\"SandboxFileSystem.realpath\")(function* (\n\tfs: SandboxFileSystem.Interface,\n\tpath: string,\n) {\n\treturn yield* fs.realpath(path).pipe(Effect.orElseSucceed(() => posix.normalize(path)));\n});\n\nexport * as SandboxFs from \"./util.ts\";\n","import { Context, Effect, Layer } from \"effect\";\nimport { Git } from \"../git/git.ts\";\nimport { SandboxFs } from \"../sandbox/fs/util.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\nimport { Hash } from \"../util/hash.ts\";\nimport { posix as path } from \"../util/posix.ts\";\nimport { RepoSchema } from \"./schema.ts\";\n\n/** Per-clone file under the store that pins the project id (see PROJECT.md §1 \"marker\"). */\nexport const MARKER = \"codework\";\n\nexport interface Identity {\n\t/** `marker ?? remoteHash ?? rootCommit`; undefined when none is available (caller falls back). */\n\treadonly id: string | undefined;\n\treadonly name: string;\n\t/** True when a portable id was computed and written to the marker this call. */\n\treadonly stamp: boolean;\n}\n\nexport interface Interface {\n\t/** Locate the checkout containing `input`, or undefined when there is none git can read. */\n\treadonly find: (input: AbsolutePath) => Effect.Effect<RepoSchema.Info | undefined>;\n\t/** PROJECT.md §5.1 PHASE 2. Stamps the marker when a portable id is found for the first time. */\n\treadonly identity: (repo: RepoSchema.Info) => Effect.Effect<Identity>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/repo/repo/Service\") {}\n\n/**\n * Canonical `host/path` for a remote url (D-URL): host and path lowercased,\n * `.git` suffix and surrounding slashes stripped, scp form accepted.\n * `file:` urls and empty input yield undefined.\n */\nexport function normalize(url: string): string | undefined {\n\tconst value = url.trim();\n\tif (!value) return undefined;\n\n\ttry {\n\t\tconst parsed = new URL(value);\n\t\tif (parsed.protocol === \"file:\") return undefined;\n\t\treturn parts(parsed.hostname, parsed.pathname);\n\t} catch {\n\t\tconst scp = value.match(/^([^@/:]+@)?([^/:]+):(.+)$/);\n\t\tif (scp) return parts(scp[2]!, scp[3]!);\n\t\treturn undefined;\n\t}\n}\n\nfunction parts(host: string, name: string) {\n\tconst pathname = name\n\t\t.replace(/^\\/+/, \"\")\n\t\t.replace(/\\.git\\/?$/, \"\")\n\t\t.replace(/\\/+$/, \"\");\n\tif (!host || !pathname) return undefined;\n\treturn `${host}/${pathname}`.toLowerCase();\n}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\tconst git = yield* Git.Service;\n\n\t\tconst find = Effect.fn(\"Repo.find\")(function* (input: AbsolutePath) {\n\t\t\tconst dotgit = (yield* SandboxFs.up(fs, { targets: [\".git\"], start: input }))[0];\n\t\t\tif (!dotgit) return undefined;\n\n\t\t\tconst cwd = path.dirname(dotgit);\n\t\t\tconst directory = yield* git.revParse(cwd, \"--show-toplevel\");\n\t\t\tconst gitDir = yield* git.revParse(cwd, \"--git-dir\");\n\t\t\tconst store = yield* git.revParse(cwd, \"--git-common-dir\");\n\t\t\t// bare, corrupt, or no git binary (exit 127) → not a repo we can use\n\t\t\tif (directory === undefined || gitDir === undefined || store === undefined) return undefined;\n\n\t\t\treturn {\n\t\t\t\tdirectory: AbsolutePath.make(yield* SandboxFs.realpath(fs, directory)),\n\t\t\t\tgitDir: AbsolutePath.make(yield* SandboxFs.realpath(fs, gitDir)),\n\t\t\t\tstore: AbsolutePath.make(yield* SandboxFs.realpath(fs, store)),\n\t\t\t} satisfies RepoSchema.Info;\n\t\t});\n\n\t\tconst identity = Effect.fn(\"Repo.identity\")(function* (repo: RepoSchema.Info) {\n\t\t\tconst marker = path.join(repo.store, MARKER);\n\t\t\tconst pinned = (yield* SandboxFs.readFileSafe(fs, marker))?.trim() || undefined;\n\n\t\t\tconst url = yield* git.remote(repo.directory);\n\t\t\tconst normalized = url === undefined ? undefined : normalize(url);\n\t\t\tconst remote =\n\t\t\t\tnormalized === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: { id: Hash.fast(`git:${normalized}`), name: path.basename(normalized) };\n\n\t\t\tconst root = (yield* git.roots(repo.directory))[0];\n\n\t\t\tconst id = pinned ?? remote?.id ?? root;\n\t\t\tconst stamp = pinned === undefined && id !== undefined;\n\t\t\tif (stamp) {\n\t\t\t\tyield* fs\n\t\t\t\t\t.writeFile(marker, id)\n\t\t\t\t\t.pipe(\n\t\t\t\t\t\tEffect.catch((error) => Effect.logWarning(\"Repo.identity: failed to write marker\", marker, error)),\n\t\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\tname: remote?.name ?? path.basename(repo.directory),\n\t\t\t\tstamp,\n\t\t\t} satisfies Identity;\n\t\t});\n\n\t\treturn Service.of({ find, identity });\n\t}),\n);\n\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) =>\n\tlayer.pipe(Layer.provide(Git.layer), Layer.provide(sandbox));\n\nexport const defaultLayer = (rootPath: string) => layerWith(Sandbox.defaultLayer(rootPath));\n\nexport * as Repo from \"./repo.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { Git } from \"../git/git.ts\";\nimport { RepoSchema } from \"../repo/schema.ts\";\nimport { SandboxFs } from \"../sandbox/fs/util.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\n\nexport class WorktreeError extends Schema.TaggedError<WorktreeError>()(\"Worktree.WorktreeError\", {\n\toperation: Schema.Literals([\"add\", \"remove\", \"list\"]),\n\tmessage: Schema.String,\n\tdirectory: Schema.optional(AbsolutePath),\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface Entry {\n\t/** realpath of the checkout */\n\treadonly location: AbsolutePath;\n\t/** True for the main checkout (the one owning the store). */\n\treadonly main: boolean;\n}\n\nexport interface Input {\n\treadonly repo: RepoSchema.Info;\n\treadonly directory: AbsolutePath;\n}\n\nexport interface Interface {\n\t/** `git worktree list`, main checkout first. Never prunes (D-PRUNE). */\n\treadonly list: (repo: RepoSchema.Info) => Effect.Effect<ReadonlyArray<Entry>, WorktreeError>;\n\t/** Detached worktree at `directory` checked out at the repo's HEAD. */\n\treadonly add: (input: Input) => Effect.Effect<void, WorktreeError>;\n\t/** Force-remove the worktree, then prune stale administrative entries. */\n\treadonly remove: (input: Input) => Effect.Effect<void, WorktreeError>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/worktree/worktree/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\tconst git = yield* Git.Service;\n\n\t\tconst worktree = Effect.fnUntraced(function* (\n\t\t\toperation: WorktreeError[\"operation\"],\n\t\t\tcwd: string,\n\t\t\targs: string[],\n\t\t\tdirectory?: AbsolutePath,\n\t\t) {\n\t\t\tconst result = yield* git\n\t\t\t\t.exec(cwd, [\"worktree\", ...args])\n\t\t\t\t.pipe(\n\t\t\t\t\tEffect.mapError((cause) => new WorktreeError({ operation, directory, message: cause.message, cause })),\n\t\t\t\t);\n\t\t\tif (result.exitCode === 0) return result.text;\n\t\t\treturn yield* new WorktreeError({\n\t\t\t\toperation,\n\t\t\t\tdirectory,\n\t\t\t\tmessage: result.stderr.trim() || result.text.trim() || \"Git failed\",\n\t\t\t});\n\t\t});\n\n\t\tconst list = Effect.fn(\"Worktree.list\")(function* (repo: RepoSchema.Info) {\n\t\t\tconst text = yield* worktree(\"list\", repo.directory, [\"list\", \"--porcelain\"]);\n\t\t\tconst locations = text\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.filter((line) => line.startsWith(\"worktree \"))\n\t\t\t\t.map((line) => Git.resolvePath(repo.directory, line.slice(\"worktree \".length).trim()));\n\t\t\treturn yield* Effect.forEach(locations, (location, index) =>\n\t\t\t\tSandboxFs.realpath(fs, location).pipe(\n\t\t\t\t\tEffect.map((real): Entry => ({ location: AbsolutePath.make(real), main: index === 0 })),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\n\t\tconst add = Effect.fn(\"Worktree.add\")(function* (input: Input) {\n\t\t\tyield* worktree(\"add\", input.repo.directory, [\"add\", \"--detach\", input.directory, \"HEAD\"], input.directory);\n\t\t});\n\n\t\tconst remove = Effect.fn(\"Worktree.remove\")(function* (input: Input) {\n\t\t\tyield* worktree(\"remove\", input.repo.store, [\"remove\", \"--force\", input.directory], input.directory);\n\t\t\tyield* git.exec(input.repo.store, [\"worktree\", \"prune\"]).pipe(Effect.ignore);\n\t\t});\n\n\t\treturn Service.of({ list, add, remove });\n\t}),\n);\n\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) =>\n\tlayer.pipe(Layer.provide(Git.layer), Layer.provide(sandbox));\n\nexport const defaultLayer = (rootPath: string) => layerWith(Sandbox.defaultLayer(rootPath));\n\nexport * as Worktree from \"./worktree.ts\";\n","import { Context, Effect, Layer, Option, Schema, Semaphore } from \"effect\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { Database } from \"../db/db.ts\";\nimport { ProjectRow } from \"../db/schema.sql.ts\";\nimport { Git } from \"../git/git.ts\";\nimport { DirectoryNotFoundError, NotDirectoryError, type Error as LocationError } from \"../location/error.ts\";\nimport { Repo } from \"../repo/repo.ts\";\nimport type { RepoSchema } from \"../repo/schema.ts\";\nimport { SandboxFs } from \"../sandbox/fs/util.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\nimport { SpaceSchema } from \"../space/schema.ts\";\nimport { Space } from \"../space/space.ts\";\nimport { Hash } from \"../util/hash.ts\";\nimport { posix as path } from \"../util/posix.ts\";\nimport { Worktree } from \"../worktree/worktree.ts\";\nimport { ProjectSchema } from \"./schema.ts\";\n\n/** Deterministic, env-local id for a directory without a portable identity. Never written to a marker. */\nexport const provisional = (env: SandboxInstance.ID, location: string): ProjectSchema.ID =>\n\tProjectSchema.ID.make(Hash.fast(JSON.stringify([\"dir\", SandboxInstance.toColumn(env) ?? \"local\", location])));\n\nexport interface Resolved {\n\treadonly project: ProjectSchema.Info;\n\treadonly space: SpaceSchema.Info;\n\t/** Realpath of `cwd`; equal to or under `space.location`. */\n\treadonly directory: AbsolutePath;\n\t/** `space.kind ∈ { primary, plain }` */\n\treadonly isDefault: boolean;\n}\n\nexport interface Interface {\n\treadonly resolveOrCreate: (cwd: AbsolutePath) => Effect.Effect<Resolved, LocationError>;\n\treadonly get: (id: ProjectSchema.ID) => Effect.Effect<Option.Option<ProjectSchema.Info>>;\n\treadonly list: () => Effect.Effect<ProjectSchema.Info[]>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/project/project/Service\") {}\n\ninterface Member {\n\treadonly location: AbsolutePath;\n\treadonly main: boolean;\n}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\tconst repos = yield* Repo.Service;\n\t\tconst worktrees = yield* Worktree.Service;\n\t\tconst spaces = yield* Space.Service;\n\t\tconst { id: env } = yield* SandboxIO.Current;\n\t\tconst envColumn = SandboxInstance.toColumn(env);\n\n\t\t// D-LOCK: one long-running server, so an in-process lock is the global one.\n\t\tconst lock = yield* Semaphore.make(1);\n\n\t\tconst findProject = SqlSchema.findOneOption({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: ProjectRow,\n\t\t\texecute: (id) => sql`SELECT * FROM project WHERE id = ${id}`,\n\t\t});\n\n\t\tconst findAllProjects = SqlSchema.findAll({\n\t\t\tRequest: Schema.Void,\n\t\t\tResult: ProjectRow,\n\t\t\texecute: () => sql`SELECT * FROM project ORDER BY name, id`,\n\t\t});\n\n\t\t// name and created_at never move on conflict\n\t\tconst upsertProject = SqlSchema.void({\n\t\t\tRequest: ProjectRow.insert,\n\t\t\texecute: (row) => sql`\n\t\t\t\tINSERT INTO project ${sql.insert(row)}\n\t\t\t\tON CONFLICT(id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at\n\t\t\t`,\n\t\t});\n\n\t\tconst toInfo = (row: ProjectRow, vcs: RepoSchema.Vcs | undefined): ProjectSchema.Info =>\n\t\t\tnew ProjectSchema.Info({\n\t\t\t\tid: ProjectSchema.ID.make(row.id),\n\t\t\t\tname: row.name,\n\t\t\t\tstatus: row.status,\n\t\t\t\t...(vcs === undefined ? {} : { vcs }),\n\t\t\t});\n\n\t\t// Info carries `vcs` only when resolved from a checkout; a bare lookup has no repo to ask.\n\t\tconst get = Effect.fn(\"Project.get\")(function* (id: ProjectSchema.ID) {\n\t\t\treturn Option.map(yield* findProject(id).pipe(Effect.orDie), (row) => toInfo(row, undefined));\n\t\t});\n\n\t\tconst list = Effect.fn(\"Project.list\")(function* () {\n\t\t\treturn (yield* findAllProjects().pipe(Effect.orDie)).map((row) => toInfo(row, undefined));\n\t\t});\n\n\t\t// PHASE 2b: git's worktree list, filtered to what is actually on disk, main first.\n\t\tconst family = Effect.fnUntraced(function* (repo: RepoSchema.Info) {\n\t\t\tconst listed = yield* worktrees.list(repo).pipe(Effect.orElseSucceed((): ReadonlyArray<Member> => []));\n\t\t\tconst present = yield* Effect.filter(listed, (member) => SandboxFs.isDirectory(fs, member.location));\n\t\t\tconst members: Member[] = present.some((member) => member.location === repo.directory)\n\t\t\t\t? [...present]\n\t\t\t\t: [...present, { location: repo.directory, main: repo.gitDir === repo.store }];\n\t\t\treturn members.toSorted((a, b) => Number(b.main) - Number(a.main));\n\t\t});\n\n\t\tconst resolveOrCreate = Effect.fn(\"Project.resolveOrCreate\")(function* (cwd: AbsolutePath) {\n\t\t\tconst exists = yield* fs.exists(cwd).pipe(Effect.orDie);\n\t\t\tif (!exists) return yield* new DirectoryNotFoundError({ directory: cwd, sandboxInstanceId: env });\n\t\t\tconst stat = yield* fs.stat(cwd).pipe(Effect.orDie);\n\t\t\tif (!stat.isDirectory) return yield* new NotDirectoryError({ directory: cwd, sandboxInstanceId: env });\n\t\t\tconst location = AbsolutePath.make(yield* fs.realpath(cwd).pipe(Effect.orDie));\n\n\t\t\tconst repo = yield* repos.find(location);\n\t\t\tconst ident = repo === undefined ? undefined : yield* repos.identity(repo);\n\n\t\t\tconst worktree = repo?.directory ?? location;\n\t\t\tconst projectId = ident?.id === undefined ? provisional(env, worktree) : ProjectSchema.ID.make(ident.id);\n\t\t\tconst name = ident?.name ?? path.basename(worktree);\n\t\t\tconst vcs: RepoSchema.Vcs | undefined = repo === undefined ? undefined : { type: \"git\", store: repo.store };\n\t\t\tconst members: ReadonlyArray<Member> =\n\t\t\t\trepo === undefined ? [{ location: worktree, main: true }] : yield* family(repo);\n\n\t\t\tconst candidates = yield* sql<{ id: string; projectId: string; location: string }>`\n\t\t\t\tSELECT id, project_id, location FROM space WHERE env IS ${envColumn} AND project_id != ${projectId}\n\t\t\t`.pipe(Effect.orDie);\n\t\t\tconst strays = candidates.filter(\n\t\t\t\t(row) => row.location === worktree || row.location.startsWith(`${worktree}/`),\n\t\t\t);\n\t\t\t// A stray belongs to this checkout only when its nearest `.git` is ours —\n\t\t\t// a nested repository keeps its own project (S12). Plain dirs adopt nothing.\n\t\t\tconst dotgit = path.join(worktree, \".git\");\n\t\t\tconst verified =\n\t\t\t\trepo === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: yield* Effect.filter(strays, (row) =>\n\t\t\t\t\t\t\tSandboxFs.up(fs, { targets: [\".git\"], start: row.location }).pipe(\n\t\t\t\t\t\t\t\tEffect.map((found) => found[0] === dotgit),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\n\t\t\tconst primaryRows = yield* sql<{ location: string }>`\n\t\t\t\tSELECT location FROM space\n\t\t\t\tWHERE project_id = ${projectId} AND env IS ${envColumn} AND kind = 'primary'\n\t\t\t`.pipe(Effect.orDie);\n\t\t\tlet existingPrimary = primaryRows[0]?.location;\n\t\t\tconst claim = (location: string) => {\n\t\t\t\tif (existingPrimary !== undefined && existingPrimary !== location) return false;\n\t\t\t\texistingPrimary = location;\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tconst worktreeSpaceId = Space.id(env, worktree);\n\n\t\t\tyield* sql\n\t\t\t\t.withTransaction(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst row = yield* ProjectRow.insert.makeEffect({ id: projectId, name, status: \"active\" });\n\t\t\t\t\t\tyield* upsertProject(row);\n\n\t\t\t\t\t\tfor (const member of members) {\n\t\t\t\t\t\t\tconst kind: SpaceSchema.Kind =\n\t\t\t\t\t\t\t\trepo === undefined\n\t\t\t\t\t\t\t\t\t? \"plain\"\n\t\t\t\t\t\t\t\t\t: !member.main\n\t\t\t\t\t\t\t\t\t\t? \"linked\"\n\t\t\t\t\t\t\t\t\t\t: claim(member.location)\n\t\t\t\t\t\t\t\t\t\t\t? \"primary\"\n\t\t\t\t\t\t\t\t\t\t\t: \"copy\";\n\t\t\t\t\t\t\tyield* spaces.rehome({\n\t\t\t\t\t\t\t\tid: Space.id(env, member.location),\n\t\t\t\t\t\t\t\tprojectId,\n\t\t\t\t\t\t\t\tlocation: member.location,\n\t\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\t\tenv,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Strays at the worktree itself were re-pointed by rehome (same id).\n\t\t\t\t\t\tfor (const stray of verified) {\n\t\t\t\t\t\t\tif (stray.location === worktree) continue;\n\t\t\t\t\t\t\tyield* spaces.absorb({ strayId: SpaceSchema.ID.make(stray.id), into: worktreeSpaceId });\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// RESTRICT keeps this honest: a project still referenced is left alone.\n\t\t\t\t\t\tfor (const strayProject of new Set(verified.map((stray) => stray.projectId))) {\n\t\t\t\t\t\t\tyield* sql`\n\t\t\t\t\t\t\t\tDELETE FROM project WHERE id = ${strayProject}\n\t\t\t\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM space WHERE project_id = ${strayProject})\n\t\t\t\t\t\t\t`;\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\n\t\t\tconst project = yield* findProject(projectId).pipe(Effect.orDie);\n\t\t\tconst space = yield* spaces.get(worktreeSpaceId);\n\t\t\tif (Option.isNone(project) || Option.isNone(space)) {\n\t\t\t\treturn yield* Effect.die(new Error(`Project.resolveOrCreate: registration vanished for ${worktree}`));\n\t\t\t}\n\n\t\t\tconst resolved: Resolved = {\n\t\t\t\tproject: toInfo(project.value, vcs),\n\t\t\t\tspace: space.value,\n\t\t\t\tdirectory: location,\n\t\t\t\tisDefault: space.value.kind === \"primary\" || space.value.kind === \"plain\",\n\t\t\t};\n\t\t\treturn resolved;\n\t\t}, lock.withPermits(1));\n\n\t\treturn Service.of({ resolveOrCreate, get, list });\n\t}),\n);\n\n/** Takes an assembled sandbox — local or remote — not a local backend. */\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) =>\n\tlayer.pipe(\n\t\tLayer.provide(Layer.mergeAll(Repo.layer, Worktree.layer, Space.layer)),\n\t\tLayer.provide(Git.layer),\n\t\tLayer.provide(sandbox),\n\t\tLayer.provide(Database.defaultLayer),\n\t);\n\nexport const defaultLayer = (path: string) => layerWith(Sandbox.defaultLayer(path));\n\nexport * as Project from \"./project.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { Database } from \"../db/db.ts\";\nimport { Git } from \"../git/git.ts\";\nimport { Project } from \"../project/project.ts\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { Repo } from \"../repo/repo.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\nimport { SpaceSchema } from \"../space/schema.ts\";\nimport { Space } from \"../space/space.ts\";\nimport { Worktree } from \"../worktree/worktree.ts\";\nexport { DirectoryNotFoundError, NotDirectoryError, type Error } from \"./error.ts\";\n\n/**\n * Where work happens: a directory inside a space.\n *\n * The pair (space, directory) is the key. A path alone does not name a place —\n * `/app/repo` on the host and `/app/repo` inside a remote sandbox are different\n * trees wearing the same spelling — so the space carries the env and the\n * root it lives under (`space.location`), and `directory` is the absolute cwd\n * equal to or beneath that root. Sessions sharing a space share the project;\n * worktree relationships stay a Project concern beneath it.\n *\n * **Both halves come from the mount, so `Ref` is overrides and nothing else.**\n * A Location is a directory *within* a mounted namespace — the mount has to be\n * resolved first, the way a volume is mounted before any path on it means\n * anything — and once it is, the namespace and the working directory are already\n * in scope. Re-declaring them would be two spellings of one value, free to drift;\n * a Location pointing somewhere its own shell is not becomes unrepresentable\n * rather than merely avoided by discipline.\n */\nexport const Ref = Schema.Struct({\n\t/** Defaults to the mount's cwd. Set it to work in a subdirectory of the mount. */\n\tdirectory: Schema.optional(AbsolutePath),\n}).annotate({ identifier: \"Location.Ref\" });\nexport type Ref = typeof Ref.Type;\n\nexport class Info extends Schema.Class<Info>(\"Location.Info\")({\n\t/** The absolute cwd tools run in; `space.location` is the root it lives under. */\n\tdirectory: AbsolutePath,\n\tspace: SpaceSchema.Info,\n\tproject: ProjectSchema.Info,\n}) {}\n\nexport interface Interface extends Info {}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/location/location/Service\") {}\n\n// `SandboxIO.Current` in the requirements is what makes \"mount first\" a\n// type-level fact rather than a convention: this Layer cannot be built outside a\n// mount, so there is never a Location without one underneath.\nexport const layer = (ref: Ref = {}) =>\n\tLayer.effect(\n\t\tService,\n\t\tEffect.gen(function* () {\n\t\t\tconst instance = yield* SandboxIO.Current;\n\t\t\tconst directory = AbsolutePath.make(ref.directory ?? instance.cwd);\n\t\t\tconst project = yield* Project.Service;\n\t\t\tconst resolved = yield* project.resolveOrCreate(directory);\n\t\t\treturn Service.of(\n\t\t\t\tnew Info({ directory: resolved.directory, space: resolved.space, project: resolved.project }),\n\t\t\t);\n\t\t}),\n\t);\n\n/**\n * `layer` with the whole resolution stack (Project, Space, Repo, Worktree, Git)\n * folded in. What remains is exactly the mount and the database — for callers\n * that already hold both, such as the runner and `Session.create`.\n */\nexport const layerMounted = (ref: Ref = {}) =>\n\tlayer(ref).pipe(\n\t\tLayer.provide(\n\t\t\tProject.layer.pipe(\n\t\t\t\tLayer.provide(Layer.mergeAll(Repo.layer, Worktree.layer, Space.layer)),\n\t\t\t\tLayer.provide(Git.layer),\n\t\t\t),\n\t\t),\n\t);\n\nexport const layerWith = <E, RIn>(ref: Ref, sandbox: Sandbox.Sandbox<E, RIn>) =>\n\tlayerMounted(ref).pipe(Layer.provide(sandbox), Layer.provide(Database.defaultLayer));\n\nexport const defaultLayer = (ref: Ref, path: string) => layerWith(ref, Sandbox.defaultLayer(path));\n\nexport * as Location from \"./location.ts\";\n","/*\n * @file Defines API for actual run implementation (contract)\n * Typically drain wraps the run to be then drained by the coordinator.\n */\n\nimport { Context, Effect, Schema } from \"effect\";\nimport type { ContextDecodeError, ContextEncodeError } from \"../context/errors.ts\";\nimport { Location } from \"../location/location.ts\";\nimport type { SandboxMountError } from \"../sandbox/errors.ts\";\nimport { SandboxFileSystem } from \"../sandbox/fs/filesystem.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { optional } from \"../schema.ts\";\nimport type { Settings } from \"../settings/settings.ts\";\nimport type { ID as SessionId } from \"../session/schema.ts\";\nimport type { SessionLinkedSpaceNotFoundError, SessionNotFoundError } from \"../session/session.ts\";\nimport type { State } from \"../state/state.ts\";\n\nexport class SandboxDirectoryNotFoundError extends Schema.TaggedError<SandboxDirectoryNotFoundError>()(\n\t\"Runner.SandboxDirectoryNotFoundError\",\n\t{\n\t\tsessionId: Schema.String,\n\t\tsandboxInstanceId: SandboxInstance.ID,\n\t\tdirectory: Schema.String,\n\t},\n) {\n\toverride get message(): string {\n\t\treturn `sandbox directory not found: ${this.directory}`;\n\t}\n}\n\nconst ProviderFailureFields = {\n\tmessage: Schema.String,\n\tisRetryable: Schema.Boolean,\n\tstatus: optional(Schema.Finite),\n\tcode: optional(Schema.String),\n\trequestId: optional(Schema.String),\n\tretryAfter: optional(Schema.Duration),\n};\n\nexport class ProviderAuthenticationError extends Schema.TaggedError<ProviderAuthenticationError>()(\n\t\"Runner.ProviderAuthenticationError\",\n\t{\n\t\tauthentication: Schema.Literals([\"missing\", \"invalid\", \"expired\"]),\n\t\t...ProviderFailureFields,\n\t},\n) {}\n\nexport class ProviderConfigurationError extends Schema.TaggedError<ProviderConfigurationError>()(\n\t\"Runner.ProviderConfigurationError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderAuthorizationError extends Schema.TaggedError<ProviderAuthorizationError>()(\n\t\"Runner.ProviderAuthorizationError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderModelUnavailableError extends Schema.TaggedError<ProviderModelUnavailableError>()(\n\t\"Runner.ProviderModelUnavailableError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderRateLimitError extends Schema.TaggedError<ProviderRateLimitError>()(\n\t\"Runner.ProviderRateLimitError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderQuotaError extends Schema.TaggedError<ProviderQuotaError>()(\n\t\"Runner.ProviderQuotaError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderInvalidRequestError extends Schema.TaggedError<ProviderInvalidRequestError>()(\n\t\"Runner.ProviderInvalidRequestError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderContentPolicyError extends Schema.TaggedError<ProviderContentPolicyError>()(\n\t\"Runner.ProviderContentPolicyError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderTimeoutError extends Schema.TaggedError<ProviderTimeoutError>()(\n\t\"Runner.ProviderTimeoutError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderTransportError extends Schema.TaggedError<ProviderTransportError>()(\n\t\"Runner.ProviderTransportError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderUnavailableError extends Schema.TaggedError<ProviderUnavailableError>()(\n\t\"Runner.ProviderUnavailableError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderInvalidResponseError extends Schema.TaggedError<ProviderInvalidResponseError>()(\n\t\"Runner.ProviderInvalidResponseError\",\n\tProviderFailureFields,\n) {}\n\nexport class ProviderUnknownError extends Schema.TaggedError<ProviderUnknownError>()(\n\t\"Runner.ProviderUnknownError\",\n\tProviderFailureFields,\n) {}\n\nexport const ProviderFailureReason = Schema.Union([\n\tProviderAuthenticationError,\n\tProviderConfigurationError,\n\tProviderAuthorizationError,\n\tProviderModelUnavailableError,\n\tProviderRateLimitError,\n\tProviderQuotaError,\n\tProviderInvalidRequestError,\n\tProviderContentPolicyError,\n\tProviderTimeoutError,\n\tProviderTransportError,\n\tProviderUnavailableError,\n\tProviderInvalidResponseError,\n\tProviderUnknownError,\n]);\nexport type ProviderFailureReason = Schema.Schema.Type<typeof ProviderFailureReason>;\n\n/** Stable provider boundary for SDK and RPC consumers; inspect `reason._tag` for the category. */\nexport class ProviderError extends Schema.TaggedError<ProviderError>()(\"Runner.ProviderError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n\treason: ProviderFailureReason,\n}) {\n\toverride readonly cause = this.reason;\n\n\toverride get message(): string {\n\t\treturn `${this.provider}/${this.model}: ${this.reason.message}`;\n\t}\n\n\tget isRetryable(): boolean {\n\t\treturn this.reason.isRetryable;\n\t}\n}\n\nexport class ModelCatalogError extends Schema.TaggedError<ModelCatalogError>()(\"Runner.ModelCatalogError\", {\n\tpath: Schema.String,\n\treason: Schema.Literals([\"missing\", \"unreadable\", \"empty\", \"invalid\"]),\n\tdetail: Schema.String,\n}) {\n\toverride get message(): string {\n\t\treturn this.detail;\n\t}\n}\n\nexport class ModelNotFoundError extends Schema.TaggedError<ModelNotFoundError>()(\"Runner.ModelNotFoundError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n}) {\n\toverride get message(): string {\n\t\treturn `model \"${this.model}\" is not present for provider \"${this.provider}\" in the model catalog`;\n\t}\n}\n\nexport class LLMStreamError extends Schema.TaggedError<LLMStreamError>()(\"Runner.LLMStreamError\", {\n\tsessionId: Schema.String,\n\treason: Schema.String,\n}) {\n\toverride get message(): string {\n\t\treturn `invalid provider event stream: ${this.reason}`;\n\t}\n}\n\nexport type RunError =\n\t| ModelCatalogError\n\t| ModelNotFoundError\n\t| ProviderError\n\t| LLMStreamError\n\t| ContextDecodeError\n\t| ContextEncodeError\n\t| SessionNotFoundError\n\t| SessionLinkedSpaceNotFoundError\n\t| Settings.SettingsError\n\t| State.SnapshotError\n\t| SandboxDirectoryNotFoundError\n\t| SandboxMountError\n\t| SandboxFileSystem.FileSystemError;\n\nexport interface Interface {\n\t/** Drains eligible durable work. Explicit runs perform one provider attempt even when no work is eligible. */\n\treadonly run: (input: {\n\t\treadonly sessionId: SessionId;\n\t\treadonly force: boolean;\n\t}) => Effect.Effect<void, RunError, SandboxIO.Provides | Location.Service>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/runner/run/Service\") {}\n\nexport * as Runner from \"./run.ts\";\n","/*\n * @file Execution provides the drain implementation to be processed.\n * The coordinator then handles the drain fork run.\n */\n\nimport { Context, Effect, Layer } from \"effect\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { Runner } from \"./run.ts\";\n\nexport interface Interface {\n\t/** Snapshots active execution owned by this process. */\n\treadonly active: Effect.Effect<ReadonlySet<SessionSchema.ID>>;\n\t/** Starts execution while idle or joins the active execution. */\n\treadonly resume: (sessionId: SessionSchema.ID) => Effect.Effect<void, Runner.RunError>;\n\t/** Registers newly recorded work. Repeated wakeups may coalesce. */\n\treadonly wake: (sessionId: SessionSchema.ID) => Effect.Effect<void>;\n\t/**\n\t * Accepts interruption of active work. Idle interruption returns false.\n\t * `awaitSettlement` waits for the interrupted execution's cleanup only.\n\t */\n\treadonly interrupt: (\n\t\tsessionId: SessionSchema.ID,\n\t\treason?: SessionSchema.InterruptReason,\n\t\toptions?: { readonly awaitSettlement?: boolean },\n\t) => Effect.Effect<boolean>;\n\t/** Waits until this process owns no execution for the session. */\n\treadonly awaitIdle: (sessionId: SessionSchema.ID) => Effect.Effect<void>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/runner/execution/Service\") {}\n\n// Low-level compatibility layer for callers that only need durable session.\nexport const noopLayer = Layer.succeed(\n\tService,\n\tService.of({\n\t\tactive: Effect.succeed(new Set()),\n\t\tresume: () => Effect.void,\n\t\twake: () => Effect.void,\n\t\tinterrupt: () => Effect.succeed(false),\n\t\tawaitIdle: () => Effect.void,\n\t}),\n);\n\nexport * as RunnerExecution from \"./execution.ts\";\n","import { Schema } from \"effect\";\nimport { DateTimeUtcFromMillis, NonNegativeInt, optional } from \"../../schema.ts\";\nimport { Delivery, Prompt } from \"../prompt/schema.ts\";\nimport { SessionSchema } from \"../schema.ts\";\nimport { SessionMessageSchema } from \"../message/schema.ts\";\n\nexport const Admitted = Schema.Struct({\n\tadmittedSeq: NonNegativeInt,\n\tid: SessionMessageSchema.ID,\n\tsessionId: SessionSchema.ID,\n\tprompt: Prompt,\n\tdelivery: Delivery,\n\ttimeCreated: DateTimeUtcFromMillis,\n\tpromotedSeq: NonNegativeInt.pipe(optional),\n}).annotate({ identifier: \"SessionInput.Admitted\" });\nexport interface Admitted extends Schema.Schema.Type<typeof Admitted> {}\n","import { DateTime, Effect, Option, Schema } from \"effect\";\nimport { VariantSchema } from \"effect/unstable/schema\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { SessionInputRow } from \"../../db/schema.sql.ts\";\nimport { Event } from \"../../event/event.ts\";\nimport { EventList } from \"../../event/list.ts\";\nimport { SessionMessageSchema } from \"../message/schema.ts\";\nimport { Delivery, Prompt } from \"../prompt/schema.ts\";\nimport { SessionSchema } from \"../schema.ts\";\nimport { Admitted } from \"./schema.ts\";\n\n/**\n * Raised when a durable input is already past the lifecycle point being\n * projected -- a second admission of the same id, or a second promotion.\n *\n * It is a defect, not an error: projectors run inside the event commit, so\n * raising it rolls the event back and leaves the store untouched. `admit` and\n * `promote*` then recover by reading the row that won.\n */\nexport class LifecycleConflict extends Schema.TaggedError<LifecycleConflict>()(\"SessionInput.LifecycleConflict\", {\n\tid: SessionMessageSchema.ID,\n}) {}\n\nconst isLifecycleConflict = Schema.is(LifecycleConflict);\n\nconst fromRow = (row: SessionInputRow): Admitted =>\n\tAdmitted.make({\n\t\tadmittedSeq: row.admittedSeq,\n\t\tid: SessionMessageSchema.ID.make(row.id),\n\t\tsessionId: SessionSchema.ID.make(row.sessionId),\n\t\tprompt: row.prompt,\n\t\tdelivery: row.delivery,\n\t\ttimeCreated: row.createdAt,\n\t\t...(Option.isNone(row.promotedSeq) ? {} : { promotedSeq: row.promotedSeq.value }),\n\t});\n\n/**\n * Whether a stored input carries the prompt the caller believes it admitted.\n * A retry that reuses an id with different content is a conflict, not an\n * idempotent replay.\n */\nexport const equivalent = (\n\tinput: Admitted,\n\texpected: {\n\t\treadonly sessionId: SessionSchema.ID;\n\t\treadonly prompt: Prompt;\n\t\treadonly delivery: Delivery;\n\t},\n) =>\n\tinput.delivery === expected.delivery &&\n\tinput.sessionId === expected.sessionId &&\n\tPrompt.equivalence(input.prompt, expected.prompt);\n\nconst matchesProjection = (\n\tinput: Admitted,\n\texpected: {\n\t\treadonly sessionId: SessionSchema.ID;\n\t\treadonly prompt: Prompt;\n\t\treadonly delivery: Delivery;\n\t\treadonly timeCreated: DateTime.Utc;\n\t},\n) =>\n\tequivalent(input, expected) &&\n\tDateTime.toEpochMillis(input.timeCreated) === DateTime.toEpochMillis(expected.timeCreated);\n\nexport interface AdmitInput {\n\treadonly id: SessionMessageSchema.ID;\n\treadonly sessionId: SessionSchema.ID;\n\treadonly prompt: Prompt;\n\treadonly delivery: Delivery;\n}\n\nexport interface ProjectAdmittedInput extends AdmitInput {\n\treadonly admittedSeq: number;\n\treadonly timeCreated: DateTime.Utc;\n}\n\nexport interface ProjectPromptedInput extends AdmitInput {\n\treadonly promotedSeq: number;\n\treadonly timeCreated: DateTime.Utc;\n}\n\nexport interface Interface {\n\treadonly find: (id: SessionMessageSchema.ID) => Effect.Effect<Option.Option<Admitted>>;\n\t/** Records a prompt durably. Re-admitting the same id returns the stored row. */\n\treadonly admit: (input: AdmitInput) => Effect.Effect<Admitted>;\n\t/** Projector for `PromptAdmitted`. Runs inside the event commit. */\n\treadonly projectAdmitted: (input: ProjectAdmittedInput) => Effect.Effect<void>;\n\t/** Projector for `Prompted`. Runs inside the event commit. */\n\treadonly projectPrompted: (input: ProjectPromptedInput) => Effect.Effect<void>;\n\t/** Whether the lane holds an input that has not been promoted yet. */\n\treadonly hasPending: (sessionId: SessionSchema.ID, delivery: Delivery) => Effect.Effect<boolean>;\n\t/**\n\t * Promotes every pending steer admitted at or before `cutoff`, in admission\n\t * order. The cutoff keeps a steer that lands mid-promotion out of a request\n\t * that is already being assembled.\n\t *\n\t * Counts promotions *this* caller won. A row another drainer promoted first\n\t * is not counted: callers treat a positive count as new work to answer, and\n\t * counting a promotion someone else committed would have two workers answer\n\t * one prompt.\n\t */\n\treadonly promoteSteers: (sessionId: SessionSchema.ID, cutoff: number) => Effect.Effect<number>;\n\t/**\n\t * Promotes the single oldest pending follow-up, if any. One per run, unlike\n\t * steers, which is what makes the follow-up lane strictly turn-at-a-time.\n\t * False when there was none, or when another caller promoted it first.\n\t */\n\treadonly promoteFollowUp: (sessionId: SessionSchema.ID) => Effect.Effect<boolean>;\n}\n\nexport const make = Effect.gen(function* () {\n\tconst sql = yield* SqlClient.SqlClient;\n\tconst events = yield* Event.Service;\n\n\tconst findRow = SqlSchema.findOneOption({\n\t\tRequest: Schema.String,\n\t\tResult: SessionInputRow,\n\t\texecute: (id) => sql`SELECT * FROM session_input WHERE id = ${id}`,\n\t});\n\n\t// RETURNING distinguishes \"inserted\" from \"already there\" without a\n\t// preceding read, so the conflict is detected by the write itself.\n\tconst insertRow = SqlSchema.findAll({\n\t\tRequest: SessionInputRow.insert,\n\t\tResult: Schema.Struct({ id: Schema.String }),\n\t\texecute: (row) => sql`\n INSERT INTO session_input ${sql.insert(row)}\n ON CONFLICT(id) DO NOTHING\n RETURNING id\n `,\n\t});\n\n\t// `promoted_seq IS NULL` is the guard: it makes promotion a compare-and-set,\n\t// so a second promotion updates nothing instead of silently re-delivering.\n\tconst promoteRow = SqlSchema.findAll({\n\t\tRequest: Schema.Struct({\n\t\t\tid: Schema.String,\n\t\t\tsessionId: Schema.String,\n\t\t\tpromotedSeq: Schema.Int,\n\t\t}),\n\t\tResult: SessionInputRow,\n\t\texecute: ({ id, sessionId, promotedSeq }) => sql`\n UPDATE session_input SET promoted_seq = ${promotedSeq}\n WHERE id = ${id} AND session_id = ${sessionId} AND promoted_seq IS NULL\n RETURNING *\n `,\n\t});\n\n\t// An input id becomes the entry id once the Loop materializes it, so an\n\t// existing entry means this input has already graduated out of the queue.\n\tconst selectEntry = SqlSchema.findAll({\n\t\tRequest: Schema.String,\n\t\tResult: Schema.Struct({ id: Schema.String }),\n\t\texecute: (id) => sql`SELECT id FROM session_entry WHERE id = ${id}`,\n\t});\n\n\tconst selectPendingOne = SqlSchema.findAll({\n\t\tRequest: Schema.Struct({ sessionId: Schema.String, delivery: Delivery }),\n\t\tResult: Schema.Struct({ id: Schema.String }),\n\t\texecute: ({ sessionId, delivery }) => sql`\n SELECT id FROM session_input\n WHERE session_id = ${sessionId} AND promoted_seq IS NULL AND delivery = ${delivery}\n LIMIT 1\n `,\n\t});\n\n\tconst selectPendingSteers = SqlSchema.findAll({\n\t\tRequest: Schema.Struct({ sessionId: Schema.String, cutoff: Schema.Int }),\n\t\tResult: SessionInputRow,\n\t\texecute: ({ sessionId, cutoff }) => sql`\n SELECT * FROM session_input\n WHERE session_id = ${sessionId}\n AND promoted_seq IS NULL\n AND delivery = 'steer'\n AND admitted_seq <= ${cutoff}\n ORDER BY admitted_seq\n `,\n\t});\n\n\tconst selectPendingFollowUp = SqlSchema.findAll({\n\t\tRequest: Schema.String,\n\t\tResult: SessionInputRow,\n\t\texecute: (sessionId) => sql`\n SELECT * FROM session_input\n WHERE session_id = ${sessionId} AND promoted_seq IS NULL AND delivery = 'followUp'\n ORDER BY admitted_seq\n LIMIT 1\n `,\n\t});\n\n\tconst find = Effect.fn(\"SessionInput.find\")(function* (id: SessionMessageSchema.ID) {\n\t\treturn yield* findRow(id).pipe(Effect.map(Option.map(fromRow)));\n\t}, Effect.orDie);\n\n\tconst admit = Effect.fn(\"SessionInput.admit\")(function* (input: AdmitInput) {\n\t\t// Read before publishing, never inside it: the commit transaction must open\n\t\t// with a write, and a stored row makes re-admission a no-op anyway.\n\t\tconst existing = yield* find(input.id);\n\t\tif (Option.isSome(existing)) return existing.value;\n\t\tconst timestamp = yield* DateTime.now;\n\t\treturn yield* events\n\t\t\t.publish(EventList.PromptAdmitted, {\n\t\t\t\tmessageId: input.id,\n\t\t\t\tsessionId: input.sessionId,\n\t\t\t\ttimestamp,\n\t\t\t\tprompt: input.prompt,\n\t\t\t\tdelivery: input.delivery,\n\t\t\t})\n\t\t\t.pipe(\n\t\t\t\tEffect.flatMap((event) =>\n\t\t\t\t\tevent.durable === undefined\n\t\t\t\t\t\t? Effect.die(\"Prompt admission event is missing aggregate sequence\")\n\t\t\t\t\t\t: Effect.succeed(\n\t\t\t\t\t\t\t\tAdmitted.make({\n\t\t\t\t\t\t\t\t\tadmittedSeq: event.durable.seq,\n\t\t\t\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\t\t\t\tsessionId: input.sessionId,\n\t\t\t\t\t\t\t\t\tprompt: input.prompt,\n\t\t\t\t\t\t\t\t\tdelivery: input.delivery,\n\t\t\t\t\t\t\t\t\ttimeCreated: timestamp,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\t// Two admissions of one id race: the loser's projector conflicts, its\n\t\t\t\t// event rolls back, and it adopts the winner's row.\n\t\t\t\tEffect.catchDefect((defect) =>\n\t\t\t\t\tfind(input.id).pipe(\n\t\t\t\t\t\tEffect.flatMap(\n\t\t\t\t\t\t\tOption.match({\n\t\t\t\t\t\t\t\tonNone: () => Effect.die(defect),\n\t\t\t\t\t\t\t\tonSome: (stored: Admitted) => Effect.succeed(stored),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t});\n\n\tconst projectAdmitted = Effect.fn(\"SessionInput.projectAdmitted\")(function* (input: ProjectAdmittedInput) {\n\t\t// Safe to read first here: the commit transaction already opened with the\n\t\t// event's sequence bump, so this cannot upgrade a read lock.\n\t\tconst entry = yield* selectEntry(input.id);\n\t\tif (entry.length > 0) return yield* Effect.die(new LifecycleConflict({ id: input.id }));\n\t\tconst stored = yield* insertRow({\n\t\t\tid: input.id,\n\t\t\tsessionId: input.sessionId,\n\t\t\tprompt: input.prompt,\n\t\t\tdelivery: input.delivery,\n\t\t\tadmittedSeq: input.admittedSeq,\n\t\t\tpromotedSeq: Option.none(),\n\t\t\tcreatedAt: VariantSchema.Override(input.timeCreated),\n\t\t});\n\t\tif (stored.length === 0) return yield* Effect.die(new LifecycleConflict({ id: input.id }));\n\t}, Effect.orDie);\n\n\tconst projectPrompted = Effect.fn(\"SessionInput.projectPrompted\")(function* (input: ProjectPromptedInput) {\n\t\tconst updated = yield* promoteRow({\n\t\t\tid: input.id,\n\t\t\tsessionId: input.sessionId,\n\t\t\tpromotedSeq: input.promotedSeq,\n\t\t});\n\t\tconst promoted = updated[0];\n\t\tif (promoted) {\n\t\t\tif (!matchesProjection(fromRow(promoted), input))\n\t\t\t\treturn yield* Effect.die(new LifecycleConflict({ id: input.id }));\n\t\t\treturn;\n\t\t}\n\n\t\t// Nothing moved: either this exact promotion is being replayed, or the row\n\t\t// is already promoted at a different sequence, which is a conflict.\n\t\tconst stored = yield* find(input.id);\n\t\tif (Option.isSome(stored)) {\n\t\t\tif (!matchesProjection(stored.value, input) || stored.value.promotedSeq !== input.promotedSeq)\n\t\t\t\treturn yield* Effect.die(new LifecycleConflict({ id: input.id }));\n\t\t\treturn;\n\t\t}\n\n\t\t// Promotion of an input this store never admitted -- replayed onto an empty\n\t\t// projection. Both sequences collapse onto the promotion.\n\t\tyield* insertRow({\n\t\t\tid: input.id,\n\t\t\tsessionId: input.sessionId,\n\t\t\tprompt: input.prompt,\n\t\t\tdelivery: input.delivery,\n\t\t\tadmittedSeq: input.promotedSeq,\n\t\t\tpromotedSeq: Option.some(input.promotedSeq),\n\t\t\tcreatedAt: VariantSchema.Override(input.timeCreated),\n\t\t});\n\t}, Effect.orDie);\n\n\t// Publishing `Prompted` is what promotes: the projector stamps promoted_seq\n\t// with that event's own sequence, so delivery order lives in the same space\n\t// as the rest of the session's history.\n\t// TODO(sanchitrk): revisit\n\tconst publishPrompted = Effect.fn(\"SessionInput.publishPrompted\")(function* (\n\t\tsessionId: SessionSchema.ID,\n\t\trows: ReadonlyArray<SessionInputRow>,\n\t) {\n\t\tlet promoted = 0;\n\t\tfor (const row of rows) {\n\t\t\tconst id = SessionMessageSchema.ID.make(row.id);\n\t\t\tconst won = yield* events\n\t\t\t\t.publish(EventList.Prompted, {\n\t\t\t\t\tsessionId,\n\t\t\t\t\ttimestamp: row.createdAt,\n\t\t\t\t\tmessageId: id,\n\t\t\t\t\tprompt: row.prompt,\n\t\t\t\t\tdelivery: row.delivery,\n\t\t\t\t})\n\t\t\t\t.pipe(\n\t\t\t\t\tEffect.as(true),\n\t\t\t\t\t// Someone else promoted this row first. That is the intended outcome\n\t\t\t\t\t// so long as it really is promoted now -- but it is their promotion,\n\t\t\t\t\t// not ours, so it does not count as work for this caller.\n\t\t\t\t\tEffect.catchDefect((defect) =>\n\t\t\t\t\t\tisLifecycleConflict(defect)\n\t\t\t\t\t\t\t? find(id).pipe(\n\t\t\t\t\t\t\t\t\tEffect.flatMap((stored) =>\n\t\t\t\t\t\t\t\t\t\tOption.isSome(stored) && stored.value.promotedSeq !== undefined\n\t\t\t\t\t\t\t\t\t\t\t? Effect.succeed(false)\n\t\t\t\t\t\t\t\t\t\t\t: Effect.die(defect),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: Effect.die(defect),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\tif (won) promoted += 1;\n\t\t}\n\t\treturn promoted;\n\t});\n\n\tconst hasPending = Effect.fn(\"SessionInput.hasPending\")(function* (sessionId: SessionSchema.ID, delivery: Delivery) {\n\t\tconst rows = yield* selectPendingOne({ sessionId, delivery });\n\t\treturn rows.length > 0;\n\t}, Effect.orDie);\n\n\tconst promoteSteers = Effect.fn(\"SessionInput.promoteSteers\")(function* (\n\t\tsessionId: SessionSchema.ID,\n\t\tcutoff: number,\n\t) {\n\t\tconst rows = yield* selectPendingSteers({ sessionId, cutoff }).pipe(Effect.orDie);\n\t\treturn yield* publishPrompted(sessionId, rows);\n\t});\n\n\tconst promoteFollowUp = Effect.fn(\"SessionInput.promoteFollowUp\")(function* (sessionId: SessionSchema.ID) {\n\t\tconst rows = yield* selectPendingFollowUp(sessionId).pipe(Effect.orDie);\n\t\tif (rows.length === 0) return false;\n\t\treturn (yield* publishPrompted(sessionId, rows)) > 0;\n\t});\n\n\treturn {\n\t\tfind,\n\t\tadmit,\n\t\tprojectAdmitted,\n\t\tprojectPrompted,\n\t\thasPending,\n\t\tpromoteSteers,\n\t\tpromoteFollowUp,\n\t} satisfies Interface;\n});\n\nexport * as SessionInput from \"./input.ts\";\n","/*\n * @file The control plane: the commands that start, join, and stop work on a\n * session.\n *\n * Session storage records what happened. Control decides whether, when, and for\n * how long a session runs. Keeping the two apart is what lets `Session.Service`\n * stay a repository — it never learns that a process manager exists, so nothing\n * below this file can reach up into fiber ownership.\n *\n * `prompt` lives here rather than on the session because admitting a prompt is\n * only half a command: the durable record is inert unless something is told to\n * drain it, and that telling is process state, not storage. Putting the pair\n * here also keeps the dependency arrows pointing one way — control depends on\n * execution and on storage, and neither depends back.\n */\n\nimport { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport { RunnerExecution } from \"./runner/execution.ts\";\nimport type { Runner } from \"./runner/run.ts\";\nimport { SessionInput } from \"./session/input/input.ts\";\nimport type { Admitted } from \"./session/input/schema.ts\";\nimport { SessionMessageSchema } from \"./session/message/schema.ts\";\nimport type { Delivery, Prompt } from \"./session/prompt/schema.ts\";\nimport { SessionSchema } from \"./session/schema.ts\";\nimport { Session } from \"./session/session.ts\";\n\n/**\n * The prompt could not be admitted under the id it was given: either that id\n * already carries different content, or it has already left the inbox. Typed\n * rather than a defect — a client that retried with a reused id can act on it.\n */\nexport class PromptConflictError extends Schema.TaggedError<PromptConflictError>()(\"PromptConflictError\", {\n\tsessionId: Schema.String,\n\tmessageId: Schema.String,\n}) {}\n\nexport interface PromptInput {\n\treadonly sessionId: SessionSchema.ID;\n\treadonly prompt: Prompt;\n\t/** Supply to make the call idempotent across retries; minted when omitted. */\n\treadonly id?: SessionMessageSchema.ID;\n\t/** Defaults to \"steer\": join the running turn rather than waiting for the next. */\n\treadonly delivery?: Delivery;\n}\n\nexport interface Interface {\n\t/**\n\t * Records a prompt in the session's durable inbox, then wakes its drain.\n\t *\n\t * Returns once the prompt is stored, not once it is answered, and not once it\n\t * is in the conversation: an admitted prompt enters the transcript at\n\t * promotion, which the runner performs at the start of a turn. Between the\n\t * two the inbox is the only durable record, which is what makes a crash in\n\t * that window recoverable rather than a user message nothing ever answered.\n\t */\n\treadonly prompt: (input: PromptInput) => Effect.Effect<Admitted, Session.SessionNotFoundError | PromptConflictError>;\n\t/** Records a prompt, wakes execution, and waits until the session is idle. */\n\treadonly run: (input: PromptInput) => Effect.Effect<Admitted, Session.SessionNotFoundError | PromptConflictError>;\n\t/** Waits until the session is idle without starting work. */\n\treadonly wait: (sessionId: SessionSchema.ID) => Effect.Effect<void, Session.SessionNotFoundError>;\n\t/** Starts a drain while the session is idle, or joins the one already running. */\n\treadonly resume: (\n\t\tsessionId: SessionSchema.ID,\n\t) => Effect.Effect<void, Session.SessionNotFoundError | Runner.RunError>;\n\t/**\n\t * Stops work owned by this process. Idle is a no-op. Resolves once the\n\t * interruption is accepted and returns whether there was work to accept it;\n\t * `awaitSettlement` additionally waits for that execution's cleanup, without\n\t * following work another caller admits in the meantime.\n\t */\n\treadonly interrupt: (\n\t\tsessionId: SessionSchema.ID,\n\t\toptions?: { readonly reason?: SessionSchema.InterruptReason; readonly awaitSettlement?: boolean },\n\t) => Effect.Effect<boolean>;\n\t/** Sessions this process is currently draining. */\n\treadonly active: Effect.Effect<ReadonlySet<SessionSchema.ID>>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/control/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sessions = yield* Session.Service;\n\t\tconst inputs = yield* SessionInput.make;\n\t\tconst execution = yield* RunnerExecution.Service;\n\t\tconst isLifecycleConflict = Schema.is(SessionInput.LifecycleConflict);\n\n\t\t/**\n\t\t * Uninterruptible end to end: a client that disconnects mid-call must not\n\t\t * leave a prompt half-admitted. Everything durable happens inside `admit`,\n\t\t * which is idempotent on the id, so a retry converges rather than\n\t\t * duplicating.\n\t\t */\n\t\tconst admit = Effect.fn(\"Control.admit\")(function* (input: PromptInput) {\n\t\t\tconst session = yield* sessions.get(input.sessionId);\n\t\t\tif (Option.isNone(session)) {\n\t\t\t\treturn yield* new Session.SessionNotFoundError({ sessionId: input.sessionId });\n\t\t\t}\n\n\t\t\tconst messageId = input.id ?? SessionMessageSchema.ID.create();\n\t\t\tconst delivery = input.delivery ?? \"steer\";\n\t\t\tconst admitted = yield* inputs\n\t\t\t\t.admit({ id: messageId, sessionId: input.sessionId, prompt: input.prompt, delivery })\n\t\t\t\t.pipe(\n\t\t\t\t\t// The id already left the inbox for the conversation. That is a\n\t\t\t\t\t// conflict the caller can see, not a broken invariant.\n\t\t\t\t\tEffect.catchDefect((defect) =>\n\t\t\t\t\t\tisLifecycleConflict(defect)\n\t\t\t\t\t\t\t? new PromptConflictError({ sessionId: input.sessionId, messageId })\n\t\t\t\t\t\t\t: Effect.die(defect),\n\t\t\t\t\t),\n\t\t\t\t);\n\n\t\t\t// A retry that reuses an id but changes the prompt is not the same\n\t\t\t// request. The stored row wins, and the caller is told.\n\t\t\tif (!SessionInput.equivalent(admitted, { sessionId: input.sessionId, prompt: input.prompt, delivery })) {\n\t\t\t\treturn yield* new PromptConflictError({ sessionId: input.sessionId, messageId });\n\t\t\t}\n\n\t\t\treturn admitted;\n\t\t});\n\n\t\tconst prompt = Effect.fn(\"Control.prompt\")((input: PromptInput) =>\n\t\t\tEffect.uninterruptible(admit(input).pipe(Effect.tap((admitted) => execution.wake(admitted.sessionId)))),\n\t\t);\n\n\t\tconst run = Effect.fn(\"Control.run\")((input: PromptInput) =>\n\t\t\tEffect.uninterruptibleMask((restore) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst admitted = yield* admit(input);\n\t\t\t\t\tyield* execution.wake(admitted.sessionId);\n\t\t\t\t\tyield* restore(execution.awaitIdle(admitted.sessionId));\n\t\t\t\t\treturn admitted;\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\n\t\tconst wait = Effect.fn(\"Control.wait\")(function* (sessionId: SessionSchema.ID) {\n\t\t\tconst session = yield* sessions.get(sessionId);\n\t\t\tif (Option.isNone(session)) return yield* new Session.SessionNotFoundError({ sessionId });\n\t\t\tyield* execution.awaitIdle(sessionId);\n\t\t});\n\n\t\tconst resume = Effect.fn(\"Control.resume\")(function* (sessionId: SessionSchema.ID) {\n\t\t\tconst session = yield* sessions.get(sessionId);\n\t\t\tif (Option.isNone(session)) return yield* new Session.SessionNotFoundError({ sessionId });\n\t\t\tyield* execution.resume(sessionId);\n\t\t});\n\n\t\tconst interrupt = Effect.fn(\"Control.interrupt\")(\n\t\t\t(\n\t\t\t\tsessionId: SessionSchema.ID,\n\t\t\t\toptions?: { readonly reason?: SessionSchema.InterruptReason; readonly awaitSettlement?: boolean },\n\t\t\t) => Effect.uninterruptible(execution.interrupt(sessionId, options?.reason ?? \"user\", options)),\n\t\t);\n\n\t\treturn Service.of({ prompt, run, wait, resume, interrupt, active: execution.active });\n\t}),\n);\n\nexport * as Control from \"./control.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport type { Plugin } from \"../plugin/plugin.ts\";\nimport { EventList } from \"./list.ts\";\nimport { EventSchema } from \"./schema.ts\";\n\n/**\n * Every event definition this harness knows: the kernel's, plus whatever the\n * configured plugins registered. Built once at boot, because a definition that\n * arrives after the first publish cannot be validated against the ones already\n * in flight.\n */\nexport interface Interface {\n\treadonly definitions: ReadonlyArray<EventSchema.Definition>;\n\t/** The latest definition for a type, or `undefined` when nothing declares it. */\n\treadonly get: (type: string) => EventSchema.Definition | undefined;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/event/registry/Service\") {}\n\nexport class EventRegistrationError extends Schema.TaggedError<EventRegistrationError>()(\"EventRegistrationError\", {\n\tpluginId: Schema.String,\n\ttype: Schema.String,\n\treason: Schema.String,\n}) {}\n\n/** Plugin types are namespaced, which makes a collision with anything else structurally impossible. */\nconst namespace = (pluginId: string) => `plugin.${pluginId}.`;\n\nconst kernel = new Set<string>(EventList.Definitions.map((definition) => definition.type));\n\n/**\n * Collects plugin event definitions into one set with the kernel's.\n *\n * Every rule fails the boot rather than resolving silently: a plugin that\n * shadows a kernel type or another plugin has a bug, and first-loaded-wins would\n * hide it behind plugin ordering.\n */\nexport const flatten = Effect.fn(\"EventRegistry.flatten\")(function* (plugins: ReadonlyArray<Plugin>) {\n\tconst registered = new Map<string, string>();\n\tconst definitions: EventSchema.Definition[] = [];\n\tfor (const plugin of plugins) {\n\t\tconst prefix = namespace(plugin.id);\n\t\tfor (const definition of plugin.events ?? []) {\n\t\t\tif (kernel.has(definition.type))\n\t\t\t\treturn yield* new EventRegistrationError({\n\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\ttype: definition.type,\n\t\t\t\t\treason: \"this is a kernel event type\",\n\t\t\t\t});\n\t\t\tconst owner = registered.get(definition.type);\n\t\t\tif (owner !== undefined)\n\t\t\t\treturn yield* new EventRegistrationError({\n\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\ttype: definition.type,\n\t\t\t\t\treason: `plugin ${owner} already registers this type`,\n\t\t\t\t});\n\t\t\tif (!definition.type.startsWith(prefix))\n\t\t\t\treturn yield* new EventRegistrationError({\n\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\ttype: definition.type,\n\t\t\t\t\treason: `plugin event types must start with \"${prefix}\"`,\n\t\t\t\t});\n\t\t\tregistered.set(definition.type, plugin.id);\n\t\t\tdefinitions.push(definition);\n\t\t}\n\t}\n\treturn [...EventList.Definitions, ...definitions] as ReadonlyArray<EventSchema.Definition>;\n});\n\nexport const layer = (definitions: ReadonlyArray<EventSchema.Definition> = EventList.Definitions) =>\n\tLayer.sync(Service, () => {\n\t\tconst latest = EventSchema.latest(definitions);\n\t\treturn Service.of({ definitions, get: (type) => latest.get(type) });\n\t});\n\nexport * as EventRegistry from \"./registry.ts\";\n","import { Predicate } from \"effect\";\n\n/**\n * A plain string-keyed record: what a settings patch merges, and what a plugin's `options` block\n * has to be. A Map, a typed array or a class instance is an object to `typeof` and not one of\n * these — `Object.freeze` alone does not tell them apart, and it throws on some of them.\n */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n\tPredicate.isObject(value) &&\n\t!Array.isArray(value) &&\n\t(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst copy = (value: unknown): unknown => {\n\tif (Array.isArray(value)) return value.map(copy);\n\treturn isRecord(value) ? merge({}, value) : value;\n};\n\n/** Null/undefined properties are absent, objects merge, and arrays replace. Never mutates inputs. */\nexport function merge<T extends object>(base: T, ...patches: ReadonlyArray<object | undefined>): T {\n\tconst result = new Map<string, unknown>();\n\tfor (const patch of [base, ...patches]) {\n\t\tif (patch === undefined) continue;\n\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\tif (value === null || value === undefined) continue;\n\t\t\tconst previous = result.get(key);\n\t\t\tresult.set(key, isRecord(previous) && isRecord(value) ? merge(previous, value) : copy(value));\n\t\t}\n\t}\n\t// Callers merge validated partial patches or typed runtime options onto a complete base.\n\treturn Object.fromEntries(result) as T;\n}\n\n/** Normalize nullable properties before schema validation, without changing array positions. */\nexport const normalize = copy;\n","/*!\n * Adapted from OpenCode packages/util/src/runtime/import.node.ts.\n *\n * MIT License\n *\n * Copyright (c) 2025 opencode\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n/* oxlint-disable effecttsgo/async-function -- Native module loading exposes a Promise-based importer contract. */\n// Resolution hooks cannot yield to Effect; existence checks must stay synchronous.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport { statSync } from \"node:fs\";\nimport { registerHooks } from \"node:module\";\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { Script, constants } from \"node:vm\";\n\n/** Use Node's main loader even when the caller runs inside a bundler or test VM. */\nexport async function importModule(specifier: string): Promise<unknown> {\n\tconst imported: unknown = await new Script(`import(${JSON.stringify(specifier)})`, {\n\t\timportModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,\n\t}).runInThisContext();\n\tif (typeof imported !== \"object\" || imported === null) return imported;\n\tconst module = imported as Record<string, unknown>;\n\tconst exports = module[\"module.exports\"];\n\tif (exports !== module.default || (typeof exports !== \"object\" && typeof exports !== \"function\") || exports === null)\n\t\treturn imported;\n\treturn Object.assign({}, module, exports);\n}\n\n/** Node resolution scoped synchronously to the caller. */\nexport function resolveModule(specifier: string, directory: string, conditions?: ReadonlyArray<string>): string {\n\tconst hook = registerHooks({\n\t\tresolve(target, context, nextResolve) {\n\t\t\treturn nextResolve(target, {\n\t\t\t\t...context,\n\t\t\t\tparentURL: pathToFileURL(path.join(directory, \"package.json\")).href,\n\t\t\t\t...(conditions === undefined ? {} : { conditions: [...new Set([...context.conditions, ...conditions])] }),\n\t\t\t});\n\t\t},\n\t});\n\ttry {\n\t\tconst resolve = (target: string) => {\n\t\t\tconst resolved = import.meta.resolve(path.isAbsolute(target) ? pathToFileURL(target).href : target);\n\t\t\tif (resolved.startsWith(\"file:\")) statSync(new URL(resolved));\n\t\t\treturn resolved;\n\t\t};\n\t\ttry {\n\t\t\treturn resolve(specifier);\n\t\t} catch (error) {\n\t\t\tif (path.extname(specifier) || !missing(error)) throw error;\n\t\t\tfor (const extension of [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\", \".cts\", \".cjs\"]) {\n\t\t\t\ttry {\n\t\t\t\t\treturn resolve(specifier + extension);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tif (!missing(cause)) throw cause;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t} finally {\n\t\thook.deregister();\n\t}\n}\n\nfunction missing(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t\"code\" in error &&\n\t\t[\"ENOENT\", \"ENOTDIR\", \"ERR_MODULE_NOT_FOUND\"].includes(String(error.code))\n\t);\n}\n","\"use strict\";var j=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports);var I=j(O=>{\"use strict\";Object.defineProperty(O,\"__esModule\",{value:!0});O.tracing=O.metrics=void 0;var U=require(\"node:diagnostics_channel\");O.metrics=(0,U.channel)(\"lru-cache:metrics\");O.tracing=(0,U.tracingChannel)(\"lru-cache\")});var P=j(R=>{\"use strict\";Object.defineProperty(R,\"__esModule\",{value:!0});R.defaultPerf=void 0;R.defaultPerf=typeof performance==\"object\"&&performance&&typeof performance.now==\"function\"?performance:Date});Object.defineProperty(exports,\"__esModule\",{value:!0});exports.LRUCache=void 0;var g=I(),N=P(),C=()=>g.metrics.hasSubscribers||g.tracing.hasSubscribers,k=new Set,G=typeof process==\"object\"&&process?process:{},V=(u,t,e,i)=>{typeof G.emitWarning==\"function\"?G.emitWarning(u,t,e,i):console.error(`[${e}] ${t}: ${u}`)},q=u=>!k.has(u);var T=u=>!!u&&u===Math.floor(u)&&u>0&&isFinite(u),H=u=>T(u)?u<=Math.pow(2,8)?Uint8Array:u<=Math.pow(2,16)?Uint16Array:u<=Math.pow(2,32)?Uint32Array:u<=Number.MAX_SAFE_INTEGER?W:null:null,W=class extends Array{constructor(t){super(t),this.fill(0)}},L=class u{heap;length;static#o=!1;static create(t){let e=H(t);if(!e)return[];u.#o=!0;let i=new u(t,e);return u.#o=!1,i}constructor(t,e){if(!u.#o)throw new TypeError(\"instantiate Stack using Stack.create(n)\");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},M=class u{#o;#c;#m;#W;#S;#x;#j;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;backgroundFetchSize;#n;#b;#s;#i;#t;#l;#u;#a;#h;#_;#r;#y;#F;#d;#g;#T;#U;#f;#R;static unsafeExposeInternals(t){return{starts:t.#F,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#l,prev:t.#u,get head(){return t.#a},get tail(){return t.#h},free:t.#_,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,n)=>t.#G(e,i,s,n),moveToTail:e=>t.#M(e),indexes:e=>t.#A(e),rindexes:e=>t.#z(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#b}get size(){return this.#n}get fetchMethod(){return this.#x}get memoMethod(){return this.#j}get dispose(){return this.#m}get onInsert(){return this.#W}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:n,updateAgeOnGet:o,updateAgeOnHas:l,allowStale:h,dispose:r,onInsert:c,disposeAfter:w,noDisposeOnSet:y,noUpdateTTL:d,maxSize:p=0,maxEntrySize:f=0,sizeCalculation:_,fetchMethod:a,memoMethod:S,noDeleteOnFetchRejection:F,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:A,ignoreFetchAbort:z,backgroundFetchSize:x=1,perf:v}=t;if(this.backgroundFetchSize=x,v!==void 0&&typeof v?.now!=\"function\")throw new TypeError(\"perf option must have a now() method if specified\");if(this.#w=v??N.defaultPerf,e!==0&&!T(e))throw new TypeError(\"max option must be a nonnegative integer\");let E=e?H(e):Array;if(!E)throw new Error(\"invalid max value: \"+e);if(this.#o=e,this.#c=p,this.maxEntrySize=f||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError(\"cannot set sizeCalculation without setting maxSize or maxEntrySize\");if(typeof this.sizeCalculation!=\"function\")throw new TypeError(\"sizeCalculation set to non-function\")}if(S!==void 0&&typeof S!=\"function\")throw new TypeError(\"memoMethod must be a function if defined\");if(this.#j=S,a!==void 0&&typeof a!=\"function\")throw new TypeError(\"fetchMethod must be a function if specified\");if(this.#x=a,this.#U=!!a,this.#s=new Map,this.#i=Array.from({length:e}).fill(void 0),this.#t=Array.from({length:e}).fill(void 0),this.#l=new E(e),this.#u=new E(e),this.#a=0,this.#h=0,this.#_=L.create(e),this.#n=0,this.#b=0,typeof r==\"function\"&&(this.#m=r),typeof c==\"function\"&&(this.#W=c),typeof w==\"function\"?(this.#S=w,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#m,this.#R=!!this.#W,this.#f=!!this.#S,this.noDisposeOnSet=!!y,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!F,this.allowStaleOnFetchRejection=!!m,this.allowStaleOnFetchAbort=!!A,this.ignoreFetchAbort=!!z,this.maxEntrySize!==0){if(this.#c!==0&&!T(this.#c))throw new TypeError(\"maxSize must be a positive integer if specified\");if(!T(this.maxEntrySize))throw new TypeError(\"maxEntrySize must be a positive integer if specified\");this.#X()}if(this.allowStale=!!h,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!l,this.ttlResolution=T(s)||s===0?s:1,this.ttlAutopurge=!!n,this.ttl=i||0,this.ttl){if(!T(this.ttl))throw new TypeError(\"ttl must be a positive integer if specified\");this.#k()}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError(\"At least one of max, maxSize, or ttl is required\");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let D=\"LRU_CACHE_UNBOUNDED\";q(D)&&(k.add(D),V(\"TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.\",\"UnboundedCacheWarning\",D,u))}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#k(){let t=new W(this.#o),e=new W(this.#o);this.#d=t,this.#F=e;let i=this.ttlAutopurge?Array.from({length:this.#o}):void 0;this.#g=i,this.#H=(h,r,c=this.#w.now())=>{e[h]=r!==0?c:0,t[h]=r,s(h,r)},this.#D=h=>{e[h]=t[h]!==0?this.#w.now():0,s(h,t[h])};let s=this.ttlAutopurge?(h,r)=>{if(i?.[h]&&(clearTimeout(i[h]),i[h]=void 0),r&&r!==0&&i){let c=setTimeout(()=>{this.#p(h)?(this.#v(this.#i[h],\"expire\"),i[h]=void 0):s(h,l(h))},r+1);c.unref&&c.unref(),i[h]=c}}:()=>{};this.#E=(h,r)=>{if(t[r]){let c=t[r],w=e[r];if(!c||!w)return;h.ttl=c,h.start=w,h.now=n||o();let y=h.now-w;h.remainingTTL=c-y}};let n=0,o=()=>{let h=this.#w.now();if(this.ttlResolution>0){n=h;let r=setTimeout(()=>n=0,this.ttlResolution);r.unref&&r.unref()}return h};this.getRemainingTTL=h=>{let r=this.#s.get(h);return r===void 0?0:l(r)};let l=h=>{let r=t[h],c=e[h];if(!r||!c)return 1/0;let w=(n||o())-c;return r-w};this.#p=h=>{let r=e[h],c=t[h];return!!c&&!!r&&(n||o())-r>c}}#D=()=>{};#E=()=>{};#H=()=>{};#p=()=>!1;#X(){let t=new W(this.#o);this.#b=0,this.#y=t,this.#C=e=>{this.#b-=t[e],t[e]=0},this.#N=(e,i,s,n)=>{if(!T(s)){if(this.#e(i))return this.backgroundFetchSize;if(n){if(typeof n!=\"function\")throw new TypeError(\"sizeCalculation must be a function\");if(s=n(i,e),!T(s))throw new TypeError(\"sizeCalculation return invalid (expect positive integer)\")}else throw new TypeError(\"invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.\")}return s},this.#I=(e,i,s)=>{if(t[e]=i,this.#c){let n=this.#c-t[e];for(;this.#b>n;)this.#P(!0)}this.#b+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#b)}}#C=t=>{};#I=(t,e,i)=>{};#N=(t,e,i,s)=>{if(i||s)throw new TypeError(\"cannot set size without setting maxSize or maxEntrySize on cache\");return 0};*#A({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#a);)e=this.#u[e]}*#z({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#a;this.#V(e)&&((t||!this.#p(e))&&(yield e),e!==this.#h);)e=this.#l[e]}#V(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#A())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*rentries(){for(let t of this.#z())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield[this.#i[t],this.#t[t]])}*keys(){for(let t of this.#A()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*rkeys(){for(let t of this.#z()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e)}}*values(){for(let t of this.#A())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}*rvalues(){for(let t of this.#z())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=\"LRUCache\";find(t,e={}){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;if(n!==void 0&&t(n,this.#i[i],this))return this.#L(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#A()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}rforEach(t,e=this){for(let i of this.#z()){let s=this.#t[i],n=this.#e(s)?s.__staleWhileFetching:s;n!==void 0&&t.call(e,n,this.#i[i],this)}}purgeStale(){let t=!1;for(let e of this.#z({allowStale:!0}))this.#p(e)&&(this.#v(this.#i[e],\"expire\"),t=!0);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let n={value:s};if(this.#d&&this.#F){let o=this.#d[e],l=this.#F[e];if(o&&l){let h=o-(this.#w.now()-l);n.ttl=h,n.start=Date.now()}}return this.#y&&(n.size=this.#y[e]),n}dump(){let t=[];for(let e of this.#A({allowStale:!0})){let i=this.#i[e],s=this.#t[e],n=this.#e(s)?s.__staleWhileFetching:s;if(n===void 0||i===void 0)continue;let o={value:n};if(this.#d&&this.#F){o.ttl=this.#d[e];let l=this.#w.now()-this.#F[e];o.start=Math.floor(Date.now()-l)}this.#y&&(o.size=this.#y[e]),t.unshift([i,o])}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#w.now()-s}this.#O(e,i.value,i)}}set(t,e,i={}){let{status:s=g.metrics.hasSubscribers?{}:void 0}=i;i.status=s,s&&(s.op=\"set\",s.key=t,e!==void 0&&(s.value=e),s.cache=this);let n=this.#O(t,e,i);return s&&g.metrics.hasSubscribers&&g.metrics.publish(s),n}#O(t,e,i,s){let{ttl:n=this.ttl,start:o,noDisposeOnSet:l=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:r}=i,c=this.#e(e);if(e===void 0)return r&&(r.set=\"deleted\"),this.delete(t),this;let{noUpdateTTL:w=this.noUpdateTTL}=i;r&&!c&&(r.value=e);let y=this.#N(t,e,i.size||0,h,r);if(this.maxEntrySize&&y>this.maxEntrySize)return this.#v(t,\"set\"),r&&(r.set=\"miss\",r.maxEntrySizeExceeded=!0),this;let d=this.#n===0?void 0:this.#s.get(t);if(d===void 0)d=this.#n===0?this.#h:this.#_.length!==0?this.#_.pop():this.#n===this.#o?this.#P(!1):this.#n,this.#i[d]=t,this.#t[d]=e,this.#s.set(t,d),this.#l[this.#h]=d,this.#u[d]=this.#h,this.#h=d,this.#n++,this.#I(d,y,r),r&&(r.set=\"add\"),w=!1,this.#R&&!c&&this.#W?.(e,t,\"add\");else{this.#M(d);let p=this.#t[d];if(e!==p){if(!l)if(this.#e(p)){p!==s&&p.__abortController.abort(new Error(\"replaced\"));let{__staleWhileFetching:f}=p;f!==void 0&&f!==e&&(this.#T&&this.#m?.(f,t,\"set\"),this.#f&&this.#r?.push([f,t,\"set\"]))}else this.#T&&this.#m?.(p,t,\"set\"),this.#f&&this.#r?.push([p,t,\"set\"]);if(this.#C(d),this.#I(d,y,r),this.#t[d]=e,!c){let f=p&&this.#e(p)?p.__staleWhileFetching:p,_=f===void 0?\"add\":e!==f?\"replace\":\"update\";r&&(r.set=_,f!==void 0&&(r.oldValue=f)),this.#R&&this.onInsert?.(e,t,_)}}else c||(r&&(r.set=\"update\"),this.#R&&this.onInsert?.(e,t,\"update\"))}if(n!==0&&!this.#d&&this.#k(),this.#d&&(w||this.#H(d,n,o),r&&this.#E(r,d)),!l&&this.#f&&this.#r){let p=this.#r,f;for(;f=p?.shift();)this.#S?.(...f)}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#a];if(this.#P(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e)}}}#P(t){let e=this.#a,i=this.#i[e],s=this.#t[e],n=this.#e(s);n&&s.__abortController.abort(new Error(\"evicted\"));let o=n?s.__staleWhileFetching:s;return(this.#T||this.#f)&&o!==void 0&&(this.#T&&this.#m?.(o,i,\"evict\"),this.#f&&this.#r?.push([o,i,\"evict\"])),this.#C(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#_.push(e)),this.#n===1?(this.#a=this.#h=0,this.#_.length=0):this.#a=this.#l[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op=\"has\",i.key=t,i.cache=this);let s=this.#Y(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Y(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,n=this.#s.get(t);if(n!==void 0){let o=this.#t[n];if(this.#e(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(n))s&&(s.has=\"stale\",this.#E(s,n));else return i&&this.#D(n),s&&(s.has=\"hit\",this.#E(s,n)),!0}else s&&(s.has=\"miss\");return!1}peek(t,e={}){let{status:i=C()?{}:void 0}=e;i&&(i.op=\"peek\",i.key=t,i.cache=this),e.status=i;let s=this.#J(t,e);return g.metrics.hasSubscribers&&g.metrics.publish(i),s}#J(t,e){let{status:i,allowStale:s=this.allowStale}=e,n=this.#s.get(t);if(n===void 0||!s&&this.#p(n)){i&&(i.peek=n===void 0?\"miss\":\"stale\");return}let o=this.#t[n],l=this.#e(o)?o.__staleWhileFetching:o;return i&&(l!==void 0?(i.peek=\"hit\",i.value=l):i.peek=\"miss\"),l}#G(t,e,i,s){let n=e===void 0?void 0:this.#t[e];if(this.#e(n))return n;let o=new AbortController,{signal:l}=i;l?.addEventListener(\"abort\",()=>o.abort(l.reason),{signal:o.signal});let h={signal:o.signal,options:i,context:s},r=(f,_=!1)=>{let{aborted:a}=o.signal,S=i.ignoreFetchAbort&&f!==void 0,F=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&f!==void 0);if(i.status&&(a&&!_?(i.status.fetchAborted=!0,i.status.fetchError=o.signal.reason,S&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),a&&!S&&!_)return w(o.signal.reason,F);let b=d,m=this.#t[e];return(m===d||m===void 0&&S&&_)&&(f===void 0?b.__staleWhileFetching!==void 0?this.#t[e]=b.__staleWhileFetching:this.#v(t,\"fetch\"):(i.status&&(i.status.fetchUpdated=!0),this.#O(t,f,h.options,b))),f},c=f=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=f),w(f,!1)),w=(f,_)=>{let{aborted:a}=o.signal,S=a&&i.allowStaleOnFetchAbort,F=S||i.allowStaleOnFetchRejection,b=F||i.noDeleteOnFetchRejection,m=d;if(this.#t[e]===d&&(!b||!_&&m.__staleWhileFetching===void 0?this.#v(t,\"fetch\"):S||(this.#t[e]=m.__staleWhileFetching)),F)return i.status&&m.__staleWhileFetching!==void 0&&(i.status.returnedStale=!0),m.__staleWhileFetching;if(m.__returned===m)throw f},y=(f,_)=>{let a=this.#x?.(t,n,h);o.signal.addEventListener(\"abort\",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(f(void 0),i.allowStaleOnFetchAbort&&(f=S=>r(S,!0)))}),a&&a instanceof Promise?a.then(S=>f(S===void 0?void 0:S),_):a!==void 0&&f(a)};i.status&&(i.status.fetchDispatched=!0);let d=new Promise(y).then(r,c),p=Object.assign(d,{__abortController:o,__staleWhileFetching:n,__returned:void 0});return e===void 0?(this.#O(t,p,{...h.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=p,p}#e(t){if(!this.#U)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty(\"__staleWhileFetching\")&&e.__abortController instanceof AbortController}fetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#q(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#q(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:h=0,sizeCalculation:r=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:w=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:d=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:_=!1,status:a,signal:S}=e;if(a&&(a.op=\"fetch\",a.key=t,_&&(a.forceRefresh=!0),a.cache=this),!this.#U)return a&&(a.fetch=\"get\"),this.#L(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,status:a});let F={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:n,ttl:o,noDisposeOnSet:l,size:h,sizeCalculation:r,noUpdateTTL:c,noDeleteOnFetchRejection:w,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:p,ignoreFetchAbort:d,status:a,signal:S},b=this.#s.get(t);if(b===void 0){a&&(a.fetch=\"miss\");let m=this.#G(t,b,F,f);return m.__returned=m}else{let m=this.#t[b];if(this.#e(m)){let E=i&&m.__staleWhileFetching!==void 0;return a&&(a.fetch=\"inflight\",E&&(a.returnedStale=!0)),E?m.__staleWhileFetching:m.__returned=m}let A=this.#p(b);if(!_&&!A)return a&&(a.fetch=\"hit\"),this.#M(b),s&&this.#D(b),a&&this.#E(a,b),m;let z=this.#G(t,b,F,f),v=z.__staleWhileFetching!==void 0&&i;return a&&(a.fetch=A?\"stale\":\"refresh\",v&&A&&(a.returnedStale=!0)),v?z.__staleWhileFetching:z.__returned=z}}forceFetch(t,e={}){let i=g.tracing.hasSubscribers,{status:s=C()?{}:void 0}=e;e.status=s,s&&e.context&&(s.context=e.context);let n=this.#K(t,e);return s&&i&&(s.trace=!0,g.tracing.tracePromise(()=>n,s).catch(()=>{})),n}async#K(t,e={}){let i=await this.#q(t,e);if(i===void 0)throw new Error(\"fetch() returned undefined\");return i}memo(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op=\"memo\",i.key=t,e.context&&(i.context=e.context),i.cache=this);let s=this.#Q(t,e);return i&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i),s}#Q(t,e={}){let i=this.#j;if(!i)throw new Error(\"no memoMethod provided to constructor\");let{context:s,status:n,forceRefresh:o,...l}=e;n&&o&&(n.forceRefresh=!0);let h=this.#L(t,l),r=o||h===void 0;if(n&&(n.memo=r?\"miss\":\"hit\",r||(n.value=h)),!r)return h;let c=i(t,h,{options:l,context:s});return n&&(n.value=c),this.#O(t,c,l),c}get(t,e={}){let{status:i=g.metrics.hasSubscribers?{}:void 0}=e;e.status=i,i&&(i.op=\"get\",i.key=t,i.cache=this);let s=this.#L(t,e);return i&&(s!==void 0&&(i.value=s),g.metrics.hasSubscribers&&g.metrics.publish(i)),s}#L(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:o}=e,l=this.#s.get(t);if(l===void 0){o&&(o.get=\"miss\");return}let h=this.#t[l],r=this.#e(h);return o&&this.#E(o,l),this.#p(l)?r?(o&&(o.get=\"stale-fetching\"),i&&h.__staleWhileFetching!==void 0?(o&&(o.returnedStale=!0),h.__staleWhileFetching):void 0):(n||this.#v(t,\"expire\"),o&&(o.get=\"stale\"),i?(o&&(o.returnedStale=!0),h):void 0):(o&&(o.get=r?\"fetching\":\"hit\"),this.#M(l),s&&this.#D(l),r?h.__staleWhileFetching:h)}#B(t,e){this.#u[e]=t,this.#l[t]=e}#M(t){t!==this.#h&&(t===this.#a?this.#a=this.#l[t]:this.#B(this.#u[t],this.#l[t]),this.#B(this.#h,t),this.#h=t)}delete(t){return this.#v(t,\"delete\")}#v(t,e){g.metrics.hasSubscribers&&g.metrics.publish({op:\"delete\",delete:e,key:t,cache:this});let i=!1;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g[s]),this.#g[s]=void 0),i=!0,this.#n===1)this.#$(e);else{this.#C(s);let n=this.#t[s];if(this.#e(n)?n.__abortController.abort(new Error(\"deleted\")):(this.#T||this.#f)&&(this.#T&&this.#m?.(n,t,e),this.#f&&this.#r?.push([n,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#a)this.#a=this.#l[s];else{let o=this.#u[s];this.#l[o]=this.#l[s];let l=this.#l[s];this.#u[l]=this.#u[s]}this.#n--,this.#_.push(s)}}if(this.#f&&this.#r?.length){let s=this.#r,n;for(;n=s?.shift();)this.#S?.(...n)}return i}clear(){return this.#$(\"delete\")}#$(t){for(let e of this.#z({allowStale:!0})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error(\"deleted\"));else{let s=this.#i[e];this.#T&&this.#m?.(i,s,t),this.#f&&this.#r?.push([i,s,t])}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#F){this.#d.fill(0),this.#F.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0)}if(this.#y&&this.#y.fill(0),this.#a=0,this.#h=0,this.#_.length=0,this.#b=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i)}}};exports.LRUCache=M;\n//# sourceMappingURL=index.min.js.map\n","/* eslint-disable max-len */\n\n'use strict'\n\nconst maybeJoin = (...args) => args.every(arg => arg) ? args.join('') : ''\nconst maybeEncode = (arg) => arg ? encodeURIComponent(arg) : ''\nconst formatHashFragment = (f) => f.toLowerCase()\n .replace(/^\\W+/g, '') // strip leading non-characters\n .replace(/(?<!\\W)\\W+$/, '') // strip trailing non-characters\n .replace(/\\//g, '') // strip all slashes\n .replace(/\\W+/g, '-') // replace remaining non-characters with '-'\n\nconst defaults = {\n sshtemplate: ({ domain, user, project, committish }) =>\n `git@${domain}:${user}/${project}.git${maybeJoin('#', committish)}`,\n sshurltemplate: ({ domain, user, project, committish }) =>\n `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin('#', committish)}`,\n edittemplate: ({ domain, user, project, committish, editpath, path }) =>\n `https://${domain}/${user}/${project}${maybeJoin('/', editpath, '/', maybeEncode(committish || 'HEAD'), '/', path)}`,\n browsetemplate: ({ domain, user, project, committish, treepath }) =>\n `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}`,\n browsetreetemplate: ({ domain, user, project, committish, treepath, path, fragment, hashformat }) =>\n `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`,\n browseblobtemplate: ({ domain, user, project, committish, blobpath, path, fragment, hashformat }) =>\n `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || 'HEAD')}/${path}${maybeJoin('#', hashformat(fragment || ''))}`,\n docstemplate: ({ domain, user, project, treepath, committish }) =>\n `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish))}#readme`,\n httpstemplate: ({ auth, domain, user, project, committish }) =>\n `git+https://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`,\n filetemplate: ({ domain, user, project, committish, path }) =>\n `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || 'HEAD')}/${path}`,\n shortcuttemplate: ({ type, user, project, committish }) =>\n `${type}:${user}/${project}${maybeJoin('#', committish)}`,\n pathtemplate: ({ user, project, committish }) =>\n `${user}/${project}${maybeJoin('#', committish)}`,\n bugstemplate: ({ domain, user, project }) =>\n `https://${domain}/${user}/${project}/issues`,\n hashformat: formatHashFragment,\n}\n\nconst hosts = {}\nhosts.github = {\n // First two are insecure and generally shouldn't be used any more, but\n // they are still supported.\n protocols: ['git:', 'http:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'],\n domain: 'github.com',\n treepath: 'tree',\n blobpath: 'blob',\n editpath: 'edit',\n filetemplate: ({ auth, user, project, committish, path }) =>\n `https://${maybeJoin(auth, '@')}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || 'HEAD')}/${path}`,\n gittemplate: ({ auth, domain, user, project, committish }) =>\n `git://${maybeJoin(auth, '@')}${domain}/${user}/${project}.git${maybeJoin('#', committish)}`,\n tarballtemplate: ({ domain, user, project, committish }) =>\n `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`,\n extract: (url) => {\n let [, user, project, type, committish] = url.pathname.split('/', 5)\n if (type && type !== 'tree') {\n return\n }\n\n if (!type) {\n committish = url.hash.slice(1)\n }\n\n if (project && project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n if (!user || !project) {\n return\n }\n\n return { user, project, committish }\n },\n}\n\nhosts.bitbucket = {\n protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'],\n domain: 'bitbucket.org',\n treepath: 'src',\n blobpath: 'src',\n editpath: '?mode=edit',\n edittemplate: ({ domain, user, project, committish, treepath, path, editpath }) =>\n `https://${domain}/${user}/${project}${maybeJoin('/', treepath, '/', maybeEncode(committish || 'HEAD'), '/', path, editpath)}`,\n tarballtemplate: ({ domain, user, project, committish }) =>\n `https://${domain}/${user}/${project}/get/${maybeEncode(committish || 'HEAD')}.tar.gz`,\n extract: (url) => {\n let [, user, project, aux] = url.pathname.split('/', 4)\n if (['get'].includes(aux)) {\n return\n }\n\n if (project && project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n if (!user || !project) {\n return\n }\n\n return { user, project, committish: url.hash.slice(1) }\n },\n}\n\nhosts.gitlab = {\n protocols: ['git+ssh:', 'git+https:', 'ssh:', 'https:'],\n domain: 'gitlab.com',\n treepath: 'tree',\n blobpath: 'tree',\n editpath: '-/edit',\n tarballtemplate: ({ domain, user, project, committish }) =>\n `https://${domain}/api/v4/projects/${maybeEncode(user + '/' + project)}/repository/archive.tar.gz?sha=${maybeEncode(committish || 'HEAD')}`,\n extract: (url) => {\n const path = url.pathname.slice(1)\n if (path.includes('/-/') || path.includes('/archive.tar.gz')) {\n return\n }\n\n const segments = path.split('/')\n let project = segments.pop()\n if (project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n const user = segments.join('/')\n if (!user || !project) {\n return\n }\n\n return { user, project, committish: url.hash.slice(1) }\n },\n}\n\nhosts.gist = {\n protocols: ['git:', 'git+ssh:', 'git+https:', 'ssh:', 'https:'],\n domain: 'gist.github.com',\n editpath: 'edit',\n sshtemplate: ({ domain, project, committish }) =>\n `git@${domain}:${project}.git${maybeJoin('#', committish)}`,\n sshurltemplate: ({ domain, project, committish }) =>\n `git+ssh://git@${domain}/${project}.git${maybeJoin('#', committish)}`,\n edittemplate: ({ domain, user, project, committish, editpath }) =>\n `https://${domain}/${user}/${project}${maybeJoin('/', maybeEncode(committish))}/${editpath}`,\n browsetemplate: ({ domain, project, committish }) =>\n `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`,\n browsetreetemplate: ({ domain, project, committish, path, hashformat }) =>\n `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`,\n browseblobtemplate: ({ domain, project, committish, path, hashformat }) =>\n `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}${maybeJoin('#', hashformat(path))}`,\n docstemplate: ({ domain, project, committish }) =>\n `https://${domain}/${project}${maybeJoin('/', maybeEncode(committish))}`,\n httpstemplate: ({ domain, project, committish }) =>\n `git+https://${domain}/${project}.git${maybeJoin('#', committish)}`,\n filetemplate: ({ user, project, committish, path }) =>\n `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin('/', maybeEncode(committish))}/${path}`,\n shortcuttemplate: ({ type, project, committish }) =>\n `${type}:${project}${maybeJoin('#', committish)}`,\n pathtemplate: ({ project, committish }) =>\n `${project}${maybeJoin('#', committish)}`,\n bugstemplate: ({ domain, project }) =>\n `https://${domain}/${project}`,\n gittemplate: ({ domain, project, committish }) =>\n `git://${domain}/${project}.git${maybeJoin('#', committish)}`,\n tarballtemplate: ({ project, committish }) =>\n `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || 'HEAD')}`,\n extract: (url) => {\n let [, user, project, aux] = url.pathname.split('/', 4)\n if (aux === 'raw') {\n return\n }\n\n if (!project) {\n if (!user) {\n return\n }\n\n project = user\n user = null\n }\n\n if (project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n return { user, project, committish: url.hash.slice(1) }\n },\n hashformat: function (fragment) {\n return fragment && 'file-' + formatHashFragment(fragment)\n },\n}\n\nhosts.sourcehut = {\n protocols: ['git+ssh:', 'https:'],\n domain: 'git.sr.ht',\n treepath: 'tree',\n blobpath: 'tree',\n filetemplate: ({ domain, user, project, committish, path }) =>\n `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || 'HEAD'}/${path}`,\n httpstemplate: ({ domain, user, project, committish }) =>\n `https://${domain}/${user}/${project}${maybeJoin('#', committish)}`,\n tarballtemplate: ({ domain, user, project, committish }) =>\n `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || 'HEAD'}.tar.gz`,\n bugstemplate: () => null,\n extract: (url) => {\n let [, user, project, aux] = url.pathname.split('/', 4)\n\n // tarball url\n if (['archive'].includes(aux)) {\n return\n }\n\n if (project && project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n if (!user || !project) {\n return\n }\n\n return { user, project, committish: url.hash.slice(1) }\n },\n}\n\nfor (const [name, host] of Object.entries(hosts)) {\n hosts[name] = Object.assign({}, defaults, host)\n}\n\nmodule.exports = hosts\n","const lastIndexOfBefore = (str, char, beforeChar) => {\n const startPosition = str.indexOf(beforeChar)\n return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity)\n}\n\nconst safeUrl = (u) => {\n try {\n return new URL(u)\n } catch {\n // this fn should never throw\n }\n}\n\n// accepts input like git:github.com:user/repo and inserts the // after the first :\nconst correctProtocol = (arg, protocols) => {\n const firstColon = arg.indexOf(':')\n const proto = arg.slice(0, firstColon + 1)\n if (Object.prototype.hasOwnProperty.call(protocols, proto)) {\n return arg\n }\n\n if (arg.substr(firstColon, 3) === '://') {\n // If arg is given as <foo>://<bar>, then this is already a valid URL.\n return arg\n }\n\n const firstAt = arg.indexOf('@')\n if (firstAt > -1) {\n if (firstAt > firstColon) {\n // URL has the form of <foo>:<bar>@<baz>. Assume this is a git+ssh URL.\n return `git+ssh://${arg}`\n } else {\n // URL has the form 'git@github.com:npm/hosted-git-info.git'.\n return arg\n }\n }\n\n // Correct <foo>:<bar> to <foo>://<bar>\n return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}`\n}\n\n// attempt to correct an scp style url so that it will parse with `new URL()`\nconst correctUrl = (giturl) => {\n // ignore @ that come after the first hash since the denotes the start\n // of a committish which can contain @ characters\n const firstAt = lastIndexOfBefore(giturl, '@', '#')\n // ignore colons that come after the hash since that could include colons such as:\n // git@github.com:user/package-2#semver:^1.0.0\n const lastColonBeforeHash = lastIndexOfBefore(giturl, ':', '#')\n\n if (lastColonBeforeHash > firstAt) {\n // the last : comes after the first @ (or there is no @)\n // like it would in:\n // proto://hostname.com:user/repo\n // username@hostname.com:user/repo\n // :password@hostname.com:user/repo\n // username:password@hostname.com:user/repo\n // proto://username@hostname.com:user/repo\n // proto://:password@hostname.com:user/repo\n // proto://username:password@hostname.com:user/repo\n // then we replace the last : with a / to create a valid path\n giturl = giturl.slice(0, lastColonBeforeHash) + '/' + giturl.slice(lastColonBeforeHash + 1)\n }\n\n if (lastIndexOfBefore(giturl, ':', '#') === -1 && giturl.indexOf('//') === -1) {\n // we have no : at all\n // as it would be in:\n // username@hostname.com/user/repo\n // then we prepend a protocol\n giturl = `git+ssh://${giturl}`\n }\n\n return giturl\n}\n\nmodule.exports = (giturl, protocols) => {\n const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl\n return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol))\n}\n","'use strict'\n\nconst parseUrl = require('./parse-url')\n\n// look for github shorthand inputs, such as npm/cli\nconst isGitHubShorthand = (arg) => {\n // it cannot contain whitespace before the first #\n // it cannot start with a / because that's probably an absolute file path\n // but it must include a slash since repos are username/repository\n // it cannot start with a . because that's probably a relative file path\n // it cannot start with an @ because that's a scoped package if it passes the other tests\n // it cannot contain a : before a # because that tells us that there's a protocol\n // a second / may not exist before a #\n const firstHash = arg.indexOf('#')\n const firstSlash = arg.indexOf('/')\n const secondSlash = arg.indexOf('/', firstSlash + 1)\n const firstColon = arg.indexOf(':')\n const firstSpace = /\\s/.exec(arg)\n const firstAt = arg.indexOf('@')\n\n const spaceOnlyAfterHash = !firstSpace || (firstHash > -1 && firstSpace.index > firstHash)\n const atOnlyAfterHash = firstAt === -1 || (firstHash > -1 && firstAt > firstHash)\n const colonOnlyAfterHash = firstColon === -1 || (firstHash > -1 && firstColon > firstHash)\n const secondSlashOnlyAfterHash = secondSlash === -1 || (firstHash > -1 && secondSlash > firstHash)\n const hasSlash = firstSlash > 0\n // if a # is found, what we really want to know is that the character\n // immediately before # is not a /\n const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== '/' : !arg.endsWith('/')\n const doesNotStartWithDot = !arg.startsWith('.')\n\n return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash &&\n doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash &&\n secondSlashOnlyAfterHash\n}\n\nmodule.exports = (giturl, opts, { gitHosts, protocols }) => {\n if (!giturl) {\n return\n }\n\n const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl\n const parsed = parseUrl(correctedUrl, protocols)\n if (!parsed) {\n return\n }\n\n const gitHostShortcut = gitHosts.byShortcut[parsed.protocol]\n const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith('www.')\n ? parsed.hostname.slice(4)\n : parsed.hostname]\n const gitHostName = gitHostShortcut || gitHostDomain\n if (!gitHostName) {\n return\n }\n\n const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain]\n let auth = null\n if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) {\n auth = `${parsed.username}${parsed.password ? ':' + parsed.password : ''}`\n }\n\n let committish = null\n let user = null\n let project = null\n let defaultRepresentation = null\n\n try {\n if (gitHostShortcut) {\n let pathname = parsed.pathname.startsWith('/') ? parsed.pathname.slice(1) : parsed.pathname\n const firstAt = pathname.indexOf('@')\n // we ignore auth for shortcuts, so just trim it out\n if (firstAt > -1) {\n pathname = pathname.slice(firstAt + 1)\n }\n\n const lastSlash = pathname.lastIndexOf('/')\n if (lastSlash > -1) {\n user = decodeURIComponent(pathname.slice(0, lastSlash))\n // we want nulls only, never empty strings\n if (!user) {\n user = null\n }\n project = decodeURIComponent(pathname.slice(lastSlash + 1))\n } else {\n project = decodeURIComponent(pathname)\n }\n\n if (project.endsWith('.git')) {\n project = project.slice(0, -4)\n }\n\n if (parsed.hash) {\n committish = decodeURIComponent(parsed.hash.slice(1))\n }\n\n defaultRepresentation = 'shortcut'\n } else {\n if (!gitHostInfo.protocols.includes(parsed.protocol)) {\n return\n }\n\n const segments = gitHostInfo.extract(parsed)\n if (!segments) {\n return\n }\n\n user = segments.user && decodeURIComponent(segments.user)\n project = decodeURIComponent(segments.project)\n committish = decodeURIComponent(segments.committish)\n defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1)\n }\n } catch (err) {\n /* istanbul ignore else */\n if (err instanceof URIError) {\n return\n } else {\n throw err\n }\n }\n\n return [gitHostName, user, auth, project, committish, defaultRepresentation, opts]\n}\n","'use strict'\n\nconst { LRUCache } = require('lru-cache')\nconst hosts = require('./hosts.js')\nconst fromUrl = require('./from-url.js')\nconst parseUrl = require('./parse-url.js')\n\nconst cache = new LRUCache({ max: 1000 })\n\nfunction unknownHostedUrl (url) {\n try {\n const {\n protocol,\n hostname,\n pathname,\n } = new URL(url)\n\n if (!hostname) {\n return null\n }\n\n const proto = /(?:git\\+)http:$/.test(protocol) ? 'http:' : 'https:'\n const path = pathname.replace(/\\.git$/, '')\n return `${proto}//${hostname}${path}`\n } catch {\n return null\n }\n}\n\nclass GitHost {\n constructor (type, user, auth, project, committish, defaultRepresentation, opts = {}) {\n Object.assign(this, GitHost.#gitHosts[type], {\n type,\n user,\n auth,\n project,\n committish,\n default: defaultRepresentation,\n opts,\n })\n }\n\n static #gitHosts = { byShortcut: {}, byDomain: {} }\n static #protocols = {\n 'git+ssh:': { name: 'sshurl' },\n 'ssh:': { name: 'sshurl' },\n 'git+https:': { name: 'https', auth: true },\n 'git:': { auth: true },\n 'http:': { auth: true },\n 'https:': { auth: true },\n 'git+http:': { auth: true },\n }\n\n static addHost (name, host) {\n GitHost.#gitHosts[name] = host\n GitHost.#gitHosts.byDomain[host.domain] = name\n GitHost.#gitHosts.byShortcut[`${name}:`] = name\n GitHost.#protocols[`${name}:`] = { name }\n }\n\n static fromUrl (giturl, opts) {\n if (typeof giturl !== 'string') {\n return\n }\n\n const key = giturl + JSON.stringify(opts || {})\n\n if (!cache.has(key)) {\n const hostArgs = fromUrl(giturl, opts, {\n gitHosts: GitHost.#gitHosts,\n protocols: GitHost.#protocols,\n })\n cache.set(key, hostArgs ? new GitHost(...hostArgs) : undefined)\n }\n\n return cache.get(key)\n }\n\n static fromManifest (manifest, opts = {}) {\n if (!manifest || typeof manifest !== 'object') {\n return\n }\n\n const r = manifest.repository\n // TODO: look into also checking the `bugs`/`homepage` URLs\n\n const rurl = r && (\n typeof r === 'string'\n ? r\n : typeof r === 'object' && typeof r.url === 'string'\n ? r.url\n : null\n )\n\n if (!rurl) {\n throw new Error('no repository')\n }\n\n const info = (rurl && GitHost.fromUrl(rurl.replace(/^git\\+/, ''), opts)) || null\n if (info) {\n return info\n }\n const unk = unknownHostedUrl(rurl)\n return GitHost.fromUrl(unk, opts) || unk\n }\n\n static parseUrl (url) {\n return parseUrl(url)\n }\n\n #fill (template, opts) {\n if (typeof template !== 'function') {\n return null\n }\n\n const options = { ...this, ...this.opts, ...opts }\n\n // the path should always be set so we don't end up with 'undefined' in urls\n if (!options.path) {\n options.path = ''\n }\n\n // template functions will insert the leading slash themselves\n if (options.path.startsWith('/')) {\n options.path = options.path.slice(1)\n }\n\n if (options.noCommittish) {\n options.committish = null\n }\n\n const result = template(options)\n return options.noGitPlus && result.startsWith('git+') ? result.slice(4) : result\n }\n\n hash () {\n return this.committish ? `#${this.committish}` : ''\n }\n\n ssh (opts) {\n return this.#fill(this.sshtemplate, opts)\n }\n\n sshurl (opts) {\n return this.#fill(this.sshurltemplate, opts)\n }\n\n browse (path, ...args) {\n // not a string, treat path as opts\n if (typeof path !== 'string') {\n return this.#fill(this.browsetemplate, path)\n }\n\n if (typeof args[0] !== 'string') {\n return this.#fill(this.browsetreetemplate, { ...args[0], path })\n }\n\n return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path })\n }\n\n // If the path is known to be a file, then browseFile should be used. For some hosts\n // the url is the same as browse, but for others like GitHub a file can use both `/tree/`\n // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/`\n // path will redirect to a specific commit. Using the `/blob/` path avoids this and\n // does not redirect to a different commit.\n browseFile (path, ...args) {\n if (typeof args[0] !== 'string') {\n return this.#fill(this.browseblobtemplate, { ...args[0], path })\n }\n\n return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path })\n }\n\n docs (opts) {\n return this.#fill(this.docstemplate, opts)\n }\n\n bugs (opts) {\n return this.#fill(this.bugstemplate, opts)\n }\n\n https (opts) {\n return this.#fill(this.httpstemplate, opts)\n }\n\n git (opts) {\n return this.#fill(this.gittemplate, opts)\n }\n\n shortcut (opts) {\n return this.#fill(this.shortcuttemplate, opts)\n }\n\n path (opts) {\n return this.#fill(this.pathtemplate, opts)\n }\n\n tarball (opts) {\n return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false })\n }\n\n file (path, opts) {\n return this.#fill(this.filetemplate, { ...opts, path })\n }\n\n edit (path, opts) {\n return this.#fill(this.edittemplate, { ...opts, path })\n }\n\n getDefaultRepresentation () {\n return this.default\n }\n\n toString (opts) {\n if (this.default && typeof this[this.default] === 'function') {\n return this[this.default](opts)\n }\n\n return this.sshurl(opts)\n }\n}\n\nfor (const [name, host] of Object.entries(hosts)) {\n GitHost.addHost(name, host)\n}\n\nmodule.exports = GitHost\n","'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n","'use strict'\n\nconst debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","'use strict'\n\nconst {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n","'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n if (typeof a === 'number' && typeof b === 'number') {\n return a === b ? 0 : a < b ? -1 : 1\n }\n\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n","'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n const identifiers = identifier.split('.')\n if (identifiers.length > prerelease.length) {\n return false\n }\n\n for (let i = 0; i < identifiers.length; i++) {\n if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n return false\n }\n }\n\n return true\n}\n\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n if (this.major < other.major) {\n return -1\n }\n if (this.major > other.major) {\n return 1\n }\n if (this.minor < other.minor) {\n return -1\n }\n if (this.minor > other.minor) {\n return 1\n }\n if (this.patch < other.patch) {\n return -1\n }\n if (this.patch > other.patch) {\n return 1\n }\n return 0\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n const prereleaseBase = this.prerelease[identifier.split('.').length]\n if (isNaN(prereleaseBase)) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n","'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n","'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n","'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n","'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are prereleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n","'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n","'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n","'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","'use strict'\n\nconst parse = require('./parse')\nconst constants = require('../internal/constants')\nconst SemVer = require('../classes/semver')\n\nconst truncate = (version, truncation, options) => {\n if (!constants.RELEASE_TYPES.includes(truncation)) {\n return null\n }\n\n const clonedVersion = cloneInputVersion(version, options)\n return clonedVersion && doTruncation(clonedVersion, truncation)\n}\n\nconst cloneInputVersion = (version, options) => {\n const versionStringToParse = (\n version instanceof SemVer ? version.version : version\n )\n\n return parse(versionStringToParse, options)\n}\n\nconst doTruncation = (version, truncation) => {\n if (isPrerelease(truncation)) {\n return version.version\n }\n\n version.prerelease = []\n\n switch (truncation) {\n case 'major':\n version.minor = 0\n version.patch = 0\n break\n case 'minor':\n version.patch = 0\n break\n }\n\n return version.format()\n}\n\nconst isPrerelease = (type) => {\n return type.startsWith('pre')\n}\n\nmodule.exports = truncate\n","'use strict'\n\nclass LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n","'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // strip build metadata so it can't bleed into the version\n range = range.replace(BUILDSTRIPRE, '')\n\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n src,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n comp = comp.replace(re[t.BUILD], '')\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n (isX(M) && !isX(m)) ||\n (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n // if we're including prereleases in the match, then the lower bound is\n // -0, the lowest possible prerelease value, just like x-ranges and carets.\n // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n if (invalidXRangeOrder(M, m, p)) {\n return comp\n }\n\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n","'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n","'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n","'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n","'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n","'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n","'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If LT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !c.test(gt.semver)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !c.test(lt.semver)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n","'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst truncate = require('./functions/truncate')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n truncate,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n","","'use strict'\nconst builtins = require('./builtin-modules.json')\n\nvar scopedPackagePattern = new RegExp('^(?:@([^/]+?)[/])?([^/]+?)$')\nvar exclusionList = [\n 'node_modules',\n 'favicon.ico',\n]\n\nfunction validate (name) {\n var warnings = []\n var errors = []\n\n if (name === null) {\n errors.push('name cannot be null')\n return done(warnings, errors)\n }\n\n if (name === undefined) {\n errors.push('name cannot be undefined')\n return done(warnings, errors)\n }\n\n if (typeof name !== 'string') {\n errors.push('name must be a string')\n return done(warnings, errors)\n }\n\n if (!name.length) {\n errors.push('name length must be greater than zero')\n }\n\n if (name.startsWith('.')) {\n errors.push('name cannot start with a period')\n }\n\n if (name.startsWith('-')) {\n errors.push('name cannot start with a hyphen')\n }\n\n if (name.match(/^_/)) {\n errors.push('name cannot start with an underscore')\n }\n\n if (name.trim() !== name) {\n errors.push('name cannot contain leading or trailing spaces')\n }\n\n // No funny business\n exclusionList.forEach(function (excludedName) {\n if (name.toLowerCase() === excludedName) {\n errors.push(excludedName + ' is not a valid package name')\n }\n })\n\n // Generate warnings for stuff that used to be allowed\n\n // core module names like http, events, util, etc\n if (builtins.includes(name.toLowerCase())) {\n warnings.push(name + ' is a core module name')\n }\n\n if (name.length > 214) {\n warnings.push('name can no longer contain more than 214 characters')\n }\n\n // mIxeD CaSe nAMEs\n if (name.toLowerCase() !== name) {\n warnings.push('name can no longer contain capital letters')\n }\n\n if (/[~'!()*]/.test(name.split('/').slice(-1)[0])) {\n warnings.push('name can no longer contain special characters (\"~\\'!()*\")')\n }\n\n if (encodeURIComponent(name) !== name) {\n // Maybe it's a scoped package name, like @user/package\n var nameMatch = name.match(scopedPackagePattern)\n if (nameMatch) {\n var user = nameMatch[1]\n var pkg = nameMatch[2]\n\n if (pkg.startsWith('.')) {\n errors.push('name cannot start with a period')\n }\n\n if (encodeURIComponent(user) === user && encodeURIComponent(pkg) === pkg) {\n return done(warnings, errors)\n }\n }\n\n errors.push('name can only contain URL-friendly characters')\n }\n\n return done(warnings, errors)\n}\n\nvar done = function (warnings, errors) {\n var result = {\n validForNewPackages: errors.length === 0 && warnings.length === 0,\n validForOldPackages: errors.length === 0,\n warnings: warnings,\n errors: errors,\n }\n if (!result.warnings.length) {\n delete result.warnings\n }\n if (!result.errors.length) {\n delete result.errors\n }\n return result\n}\n\nmodule.exports = validate\n","const META = Symbol('proc-log.meta')\nmodule.exports = {\n META: META,\n output: {\n LEVELS: [\n 'standard',\n 'error',\n 'buffer',\n 'flush',\n ],\n KEYS: {\n standard: 'standard',\n error: 'error',\n buffer: 'buffer',\n flush: 'flush',\n },\n standard: function (...args) {\n return process.emit('output', 'standard', ...args)\n },\n error: function (...args) {\n return process.emit('output', 'error', ...args)\n },\n buffer: function (...args) {\n return process.emit('output', 'buffer', ...args)\n },\n flush: function (...args) {\n return process.emit('output', 'flush', ...args)\n },\n },\n log: {\n LEVELS: [\n 'notice',\n 'error',\n 'warn',\n 'info',\n 'verbose',\n 'http',\n 'silly',\n 'timing',\n 'pause',\n 'resume',\n ],\n KEYS: {\n notice: 'notice',\n error: 'error',\n warn: 'warn',\n info: 'info',\n verbose: 'verbose',\n http: 'http',\n silly: 'silly',\n timing: 'timing',\n pause: 'pause',\n resume: 'resume',\n },\n error: function (...args) {\n return process.emit('log', 'error', ...args)\n },\n notice: function (...args) {\n return process.emit('log', 'notice', ...args)\n },\n warn: function (...args) {\n return process.emit('log', 'warn', ...args)\n },\n info: function (...args) {\n return process.emit('log', 'info', ...args)\n },\n verbose: function (...args) {\n return process.emit('log', 'verbose', ...args)\n },\n http: function (...args) {\n return process.emit('log', 'http', ...args)\n },\n silly: function (...args) {\n return process.emit('log', 'silly', ...args)\n },\n timing: function (...args) {\n return process.emit('log', 'timing', ...args)\n },\n pause: function () {\n return process.emit('log', 'pause')\n },\n resume: function () {\n return process.emit('log', 'resume')\n },\n },\n time: {\n LEVELS: [\n 'start',\n 'end',\n ],\n KEYS: {\n start: 'start',\n end: 'end',\n },\n start: function (name, fn) {\n process.emit('time', 'start', name)\n function end () {\n return process.emit('time', 'end', name)\n }\n if (typeof fn === 'function') {\n const res = fn()\n if (res && res.finally) {\n return res.finally(end)\n }\n end()\n return res\n }\n return end\n },\n end: function (name) {\n return process.emit('time', 'end', name)\n },\n },\n input: {\n LEVELS: [\n 'start',\n 'end',\n 'read',\n ],\n KEYS: {\n start: 'start',\n end: 'end',\n read: 'read',\n },\n start: function (...args) {\n // Support callback for backwards compatibility and pass additional args to event\n let fn\n if (typeof args[0] === 'function') {\n fn = args.shift()\n }\n process.emit('input', 'start', ...args)\n function end () {\n return process.emit('input', 'end', ...args)\n }\n if (typeof fn === 'function') {\n const res = fn()\n if (res && res.finally) {\n return res.finally(end)\n }\n end()\n return res\n }\n return end\n },\n end: function (...args) {\n return process.emit('input', 'end', ...args)\n },\n read: function (...args) {\n let resolve, reject\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve\n reject = _reject\n })\n process.emit('input', 'read', resolve, reject, ...args)\n return promise\n },\n },\n}\n","'use strict'\n\nconst isWindows = process.platform === 'win32'\n\nconst { URL } = require('node:url')\n// We need to use path/win32 so that we get consistent results in tests, but this also means we need to manually convert backslashes to forward slashes when generating file: urls with paths.\nconst path = isWindows ? require('node:path/win32') : require('node:path')\nconst { homedir } = require('node:os')\nconst HostedGit = require('hosted-git-info')\nconst semver = require('semver')\nconst validatePackageName = require('validate-npm-package-name')\nconst { log } = require('proc-log')\n\nconst hasSlashes = isWindows ? /\\\\|[/]/ : /[/]/\nconst isURL = /^(?:git[+])?[a-z]+:/i\nconst isGit = /^[^@]+@[^:.]+\\.[^:]+:.+$/i\nconst isFileType = /[.](?:tgz|tar\\.gz|tar)$/i\nconst isPortNumber = /:[0-9]+(\\/|$)/i\nconst isWindowsFile = /^(?:[.]|~[/]|[/\\\\]|[a-zA-Z]:)/\nconst isPosixFile = /^(?:[.]|~[/]|[/]|[a-zA-Z]:)/\nconst defaultRegistry = 'https://registry.npmjs.org'\n\nfunction npa (arg, where) {\n let name\n let spec\n if (typeof arg === 'object') {\n if (arg instanceof Result && (!where || where === arg.where)) {\n return arg\n } else if (arg.name && arg.rawSpec) {\n return npa.resolve(arg.name, arg.rawSpec, where || arg.where)\n } else {\n return npa(arg.raw, where || arg.where)\n }\n }\n const nameEndsAt = arg.indexOf('@', 1) // Skip possible leading @\n const namePart = nameEndsAt > 0 ? arg.slice(0, nameEndsAt) : arg\n if (isURL.test(arg)) {\n spec = arg\n } else if (isGit.test(arg)) {\n spec = `git+ssh://${arg}`\n // eslint-disable-next-line max-len\n } else if (!namePart.startsWith('@') && (hasSlashes.test(namePart) || isFileType.test(namePart))) {\n spec = arg\n } else if (nameEndsAt > 0) {\n name = namePart\n spec = arg.slice(nameEndsAt + 1) || '*'\n } else {\n const valid = validatePackageName(arg)\n if (valid.validForOldPackages) {\n name = arg\n spec = '*'\n } else {\n spec = arg\n }\n }\n return resolve(name, spec, where, arg)\n}\n\nfunction isFileSpec (spec) {\n if (!spec) {\n return false\n }\n if (spec.toLowerCase().startsWith('file:')) {\n return true\n }\n if (isWindows) {\n return isWindowsFile.test(spec)\n }\n return isPosixFile.test(spec)\n}\n\nfunction isAliasSpec (spec) {\n if (!spec) {\n return false\n }\n return spec.toLowerCase().startsWith('npm:')\n}\n\nfunction resolve (name, spec, where, arg) {\n const res = new Result({\n raw: arg,\n name: name,\n rawSpec: spec,\n fromArgument: arg != null,\n })\n\n if (name) {\n res.name = name\n }\n\n if (!where) {\n where = process.cwd()\n }\n\n if (isFileSpec(spec)) {\n return fromFile(res, where)\n } else if (isAliasSpec(spec)) {\n return fromAlias(res, where)\n }\n\n const hosted = HostedGit.fromUrl(spec, {\n noGitPlus: true,\n noCommittish: true,\n })\n if (hosted) {\n return fromHostedGit(res, hosted)\n } else if (spec && isURL.test(spec)) {\n return fromURL(res)\n } else if (spec && (hasSlashes.test(spec) || isFileType.test(spec))) {\n return fromFile(res, where)\n } else {\n return fromRegistry(res)\n }\n}\n\nfunction toPurl (arg, reg = defaultRegistry) {\n const res = npa(arg)\n\n if (res.type !== 'version') {\n throw invalidPurlType(res.type, res.raw)\n }\n\n // URI-encode leading @ of scoped packages\n let purl = 'pkg:npm/' + res.name.replace(/^@/, '%40') + '@' + res.rawSpec\n if (reg !== defaultRegistry) {\n purl += '?repository_url=' + reg\n }\n\n return purl\n}\n\nfunction invalidPackageName (name, valid, raw) {\n // eslint-disable-next-line max-len\n const err = new Error(`Invalid package name \"${name}\" of package \"${raw}\": ${valid.errors.join('; ')}.`)\n err.code = 'EINVALIDPACKAGENAME'\n return err\n}\n\nfunction invalidTagName (name, raw) {\n // eslint-disable-next-line max-len\n const err = new Error(`Invalid tag name \"${name}\" of package \"${raw}\": Tags may not have any characters that encodeURIComponent encodes.`)\n err.code = 'EINVALIDTAGNAME'\n return err\n}\n\nfunction invalidPurlType (type, raw) {\n // eslint-disable-next-line max-len\n const err = new Error(`Invalid type \"${type}\" of package \"${raw}\": Purl can only be generated for \"version\" types.`)\n err.code = 'EINVALIDPURLTYPE'\n return err\n}\n\nclass Result {\n constructor (opts) {\n this.type = opts.type\n this.registry = opts.registry\n this.where = opts.where\n if (opts.raw == null) {\n this.raw = opts.name ? `${opts.name}@${opts.rawSpec}` : opts.rawSpec\n } else {\n this.raw = opts.raw\n }\n this.name = undefined\n this.escapedName = undefined\n this.scope = undefined\n this.rawSpec = opts.rawSpec || ''\n this.saveSpec = opts.saveSpec\n this.fetchSpec = opts.fetchSpec\n if (opts.name) {\n this.setName(opts.name)\n }\n this.gitRange = opts.gitRange\n this.gitCommittish = opts.gitCommittish\n this.gitSubdir = opts.gitSubdir\n this.hosted = opts.hosted\n }\n\n // TODO move this to a getter/setter in a semver major\n setName (name) {\n const valid = validatePackageName(name)\n if (!valid.validForOldPackages) {\n throw invalidPackageName(name, valid, this.raw)\n }\n\n this.name = name\n this.scope = name[0] === '@' ? name.slice(0, name.indexOf('/')) : undefined\n // scoped packages in couch must have slash url-encoded, e.g. @foo%2Fbar\n this.escapedName = name.replace('/', '%2f')\n return this\n }\n\n toString () {\n const full = []\n if (this.name != null && this.name !== '') {\n full.push(this.name)\n }\n const spec = this.saveSpec || this.fetchSpec || this.rawSpec\n if (spec != null && spec !== '') {\n full.push(spec)\n }\n return full.length ? full.join('@') : this.raw\n }\n\n toJSON () {\n const result = Object.assign({}, this)\n delete result.hosted\n return result\n }\n}\n\n// sets res.gitCommittish, res.gitRange, and res.gitSubdir\nfunction setGitAttrs (res, committish) {\n if (!committish) {\n res.gitCommittish = null\n return\n }\n\n // for each :: separated item:\n for (const part of committish.split('::')) {\n // if the item has no : the n it is a commit-ish\n if (!part.includes(':')) {\n if (res.gitRange) {\n throw new Error('cannot override existing semver range with a committish')\n }\n if (res.gitCommittish) {\n throw new Error('cannot override existing committish with a second committish')\n }\n res.gitCommittish = part\n continue\n }\n // split on name:value\n const [name, value] = part.split(':')\n // if name is semver do semver lookup of ref or tag\n if (name === 'semver') {\n if (res.gitCommittish) {\n throw new Error('cannot override existing committish with a semver range')\n }\n if (res.gitRange) {\n throw new Error('cannot override existing semver range with a second semver range')\n }\n res.gitRange = decodeURIComponent(value)\n continue\n }\n if (name === 'path') {\n if (res.gitSubdir) {\n throw new Error('cannot override existing path with a second path')\n }\n res.gitSubdir = `/${value}`\n continue\n }\n log.warn('npm-package-arg', `ignoring unknown key \"${name}\"`)\n }\n}\n\n// Taken from: EncodePathChars and lookup_table in src/node_url.cc\n// url.pathToFileURL only returns absolute references. We can't use it to encode paths.\n// encodeURI mangles windows paths. We can't use it to encode paths.\n// Under the hood, url.pathToFileURL does a limited set of encoding, with an extra windows step, and then calls path.resolve.\n// The encoding node does without path.resolve is not available outside of the source, so we are recreating it here.\nconst encodedPathChars = new Map([\n ['\\0', '%00'],\n ['\\t', '%09'],\n ['\\n', '%0A'],\n ['\\r', '%0D'],\n [' ', '%20'],\n ['\"', '%22'],\n ['#', '%23'],\n ['%', '%25'],\n ['?', '%3F'],\n ['[', '%5B'],\n ['\\\\', isWindows ? '/' : '%5C'],\n [']', '%5D'],\n ['^', '%5E'],\n ['|', '%7C'],\n ['~', '%7E'],\n])\n\nfunction pathToFileURL (str) {\n let result = ''\n for (let i = 0; i < str.length; i++) {\n result = `${result}${encodedPathChars.get(str[i]) ?? str[i]}`\n }\n if (result.startsWith('file:')) {\n return result\n }\n return `file:${result}`\n}\n\nfunction fromFile (res, where) {\n res.type = isFileType.test(res.rawSpec) ? 'file' : 'directory'\n res.where = where\n\n let rawSpec = pathToFileURL(res.rawSpec)\n\n if (rawSpec.startsWith('file:/')) {\n // XXX backwards compatibility lack of compliance with RFC 8089\n\n // turn file://path into file:/path\n if (/^file:\\/\\/[^/]/.test(rawSpec)) {\n rawSpec = `file:/${rawSpec.slice(5)}`\n }\n\n // turn file:/../path into file:../path\n // for 1 or 3 leading slashes (2 is already ruled out from handling file:// explicitly above)\n if (/^\\/{1,3}\\.\\.?(\\/|$)/.test(rawSpec.slice(5))) {\n rawSpec = rawSpec.replace(/^file:\\/{1,3}/, 'file:')\n }\n }\n\n let resolvedUrl\n let specUrl\n try {\n // always put the '/' on \"where\", or else file:foo from /path/to/bar goes to /path/to/foo, when we want it to be /path/to/bar/foo\n resolvedUrl = new URL(rawSpec, `${pathToFileURL(path.resolve(where))}/`)\n specUrl = new URL(rawSpec)\n } catch (originalError) {\n const er = new Error('Invalid file: URL, must comply with RFC 8089')\n throw Object.assign(er, {\n raw: res.rawSpec,\n spec: res,\n where,\n originalError,\n })\n }\n\n // turn /C:/blah into just C:/blah on windows\n let specPath = decodeURIComponent(specUrl.pathname)\n let resolvedPath = decodeURIComponent(resolvedUrl.pathname)\n if (isWindows) {\n specPath = specPath.replace(/^\\/+([a-z]:\\/)/i, '$1')\n resolvedPath = resolvedPath.replace(/^\\/+([a-z]:\\/)/i, '$1')\n }\n\n // replace ~ with homedir, but keep the ~ in the saveSpec\n // otherwise, make it relative to where param\n if (/^\\/~(\\/|$)/.test(specPath)) {\n res.saveSpec = `file:${specPath.substr(1)}`\n resolvedPath = path.resolve(homedir(), specPath.substr(3))\n } else if (!path.isAbsolute(rawSpec.slice(5))) {\n res.saveSpec = `file:${path.relative(where, resolvedPath)}`\n } else {\n res.saveSpec = `file:${path.resolve(resolvedPath)}`\n }\n\n res.fetchSpec = path.resolve(where, resolvedPath)\n // re-normalize the slashes in saveSpec due to node:path/win32 behavior in windows\n res.saveSpec = res.saveSpec.split('\\\\').join('/')\n // Ignoring because this only happens in windows\n /* istanbul ignore next */\n if (res.saveSpec.startsWith('file://')) {\n // normalization of \\\\win32\\root paths can cause a double / which we don't want\n res.saveSpec = `file:/${res.saveSpec.slice(7)}`\n }\n return res\n}\n\nfunction fromHostedGit (res, hosted) {\n res.type = 'git'\n res.hosted = hosted\n res.saveSpec = hosted.toString({ noGitPlus: false, noCommittish: false })\n res.fetchSpec = hosted.getDefaultRepresentation() === 'shortcut' ? null : hosted.toString()\n setGitAttrs(res, hosted.committish)\n return res\n}\n\nfunction unsupportedURLType (protocol, spec) {\n const err = new Error(`Unsupported URL Type \"${protocol}\": ${spec}`)\n err.code = 'EUNSUPPORTEDPROTOCOL'\n return err\n}\n\nfunction fromURL (res) {\n let rawSpec = res.rawSpec\n res.saveSpec = rawSpec\n if (rawSpec.startsWith('git+ssh:')) {\n // git ssh specifiers are overloaded to also use scp-style git\n // specifiers, so we have to parse those out and treat them special.\n // They are NOT true URIs, so we can't hand them to URL.\n\n // This regex looks for things that look like:\n // git+ssh://git@my.custom.git.com:username/project.git#deadbeef\n // ...and various combinations. The username in the beginning is *required*.\n const matched = rawSpec.match(/^git\\+ssh:\\/\\/([^:#]+:[^#]+(?:\\.git)?)(?:#(.*))?$/i)\n // Filter out all-number \"usernames\" which are really port numbers\n // They can either be :1234 :1234/ or :1234/path but not :12abc\n if (matched && !matched[1].match(isPortNumber)) {\n res.type = 'git'\n setGitAttrs(res, matched[2])\n res.fetchSpec = matched[1]\n return res\n }\n } else if (rawSpec.startsWith('git+file://')) {\n // URL can't handle windows paths\n rawSpec = rawSpec.replace(/\\\\/g, '/')\n }\n const parsedUrl = new URL(rawSpec)\n // check the protocol, and then see if it's git or not\n switch (parsedUrl.protocol) {\n case 'git:':\n case 'git+http:':\n case 'git+https:':\n case 'git+rsync:':\n case 'git+ftp:':\n case 'git+file:':\n case 'git+ssh:':\n res.type = 'git'\n setGitAttrs(res, parsedUrl.hash.slice(1))\n if (parsedUrl.protocol === 'git+file:' && /^git\\+file:\\/\\/[a-z]:/i.test(rawSpec)) {\n // URL can't handle drive letters on windows file paths, the host can't contain a :\n res.fetchSpec = `git+file://${parsedUrl.host.toLowerCase()}:${parsedUrl.pathname}`\n } else {\n parsedUrl.hash = ''\n res.fetchSpec = parsedUrl.toString()\n }\n if (res.fetchSpec.startsWith('git+')) {\n res.fetchSpec = res.fetchSpec.slice(4)\n }\n break\n case 'http:':\n case 'https:':\n res.type = 'remote'\n res.fetchSpec = res.saveSpec\n break\n\n default:\n throw unsupportedURLType(parsedUrl.protocol, rawSpec)\n }\n\n return res\n}\n\nfunction fromAlias (res, where) {\n const subSpec = npa(res.rawSpec.substr(4), where)\n if (subSpec.type === 'alias') {\n throw new Error('nested aliases not supported')\n }\n\n if (!subSpec.registry) {\n throw new Error('aliases only work for registry deps')\n }\n\n if (!subSpec.name) {\n throw new Error('aliases must have a name')\n }\n\n res.subSpec = subSpec\n res.registry = true\n res.type = 'alias'\n res.saveSpec = null\n res.fetchSpec = null\n return res\n}\n\nfunction fromRegistry (res) {\n res.registry = true\n const spec = res.rawSpec.trim()\n // no save spec for registry components as we save based on the fetched\n // version, not on the argument so this can't compute that.\n res.saveSpec = null\n res.fetchSpec = spec\n const version = semver.valid(spec, true)\n const range = semver.validRange(spec, true)\n if (version) {\n res.type = 'version'\n } else if (range) {\n res.type = 'range'\n } else {\n if (encodeURIComponent(spec) !== spec) {\n throw invalidTagName(spec, res.raw)\n }\n res.type = 'tag'\n }\n return res\n}\n\nmodule.exports = npa\nmodule.exports.resolve = resolve\nmodule.exports.toPurl = toPurl\nmodule.exports.Result = Result\n","import { NodeChildProcessSpawner, NodeFileSystem, NodePath } from \"@effect/platform-node\";\nimport { Duration, Effect, Encoding, Layer, Option, Ref, Schedule, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { resolveModule } from \"../util/module.ts\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport npa from \"npm-package-arg\";\nimport { crypto, fileSystem as fs, hostPath as path } from \"../host.ts\";\n\nexport interface Request {\n\treadonly name: string;\n\treadonly spec: string;\n}\n\nexport const parse = (source: string): Request => {\n\tconst parsed = npa(source);\n\tif (!parsed.name || ![\"version\", \"range\", \"tag\"].includes(parsed.type)) {\n\t\tthrow new Error(`Unsupported plugin package source: ${source}`);\n\t}\n\t// npa turns a trailing bare `@` into the `*` range, which would give \"no version\" a second\n\t// cache key. An explicit `plugin@*` keeps its own meaning.\n\tconst omitted = parsed.raw === parsed.name || parsed.raw === `${parsed.name}@`;\n\treturn { name: parsed.name, spec: `${parsed.name}@${omitted ? \"latest\" : parsed.rawSpec}` };\n};\n\nconst Manifest = Schema.Struct({ version: Schema.String });\nconst Cached = Schema.Struct({ version: Schema.String, spec: Schema.String, entrypoint: Schema.String });\n\nexport interface Installed {\n\treadonly url: string;\n\treadonly version: string;\n}\n\n/** Runs inside the isolated staging directory. Override only for deterministic tests. */\nexport class InstallError extends Schema.TaggedError<InstallError>()(\"PluginInstallError\", {\n\tcause: Schema.Defect(),\n}) {}\nexport type Runner = (request: Request, directory: string) => Effect.Effect<void, InstallError>;\n\nconst run: Runner = Effect.fn(\"PluginPackage.run\")(\n\tfunction* (request, directory) {\n\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\tconst process = yield* spawner.spawn(\n\t\t\tChildProcess.make(\"pnpm\", [\"add\", \"--ignore-scripts\", \"--ignore-workspace\", \"--save-exact\", request.spec], {\n\t\t\t\tcwd: directory,\n\t\t\t\tstdout: \"ignore\",\n\t\t\t\tstderr: \"inherit\",\n\t\t\t}),\n\t\t);\n\t\tconst code = yield* process.exitCode;\n\t\tif (code !== 0)\n\t\t\treturn yield* new InstallError({ cause: new Error(`pnpm installation failed with exit code ${code}`) });\n\t},\n\tEffect.scoped,\n\tEffect.provide(NodeChildProcessSpawner.layer.pipe(Layer.provide(Layer.merge(NodeFileSystem.layer, NodePath.layer)))),\n\tEffect.mapError((cause) => (Schema.is(InstallError)(cause) ? cause : new InstallError({ cause }))),\n);\n\n/** How long to wait for another installer of the same spec before giving up. */\nconst LOCK_TIMEOUT = Duration.minutes(2);\n/** The holder refreshes the lock's mtime this often; a lock not refreshed for the timeout is abandoned. */\nconst LOCK_HEARTBEAT = Duration.seconds(15);\n\n/**\n * A lock whose holder stopped refreshing it was left by a crashed installer. Staleness is\n * measured from the heartbeat, not the install's start, so a slow but live install is never\n * stolen from.\n */\nconst abandoned = (directory: string) =>\n\tEffect.gen(function* () {\n\t\tconst info = yield* fs.stat(directory);\n\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\treturn Option.exists(info.mtime, (mtime) => now - mtime.getTime() > Duration.toMillis(LOCK_TIMEOUT));\n\t}).pipe(Effect.orElseSucceed(() => false));\n\nconst heartbeat = (directory: string) =>\n\tEffect.clockWith((clock) => clock.currentTimeMillis).pipe(\n\t\tEffect.flatMap((now) => fs.utimes(directory, now, now)),\n\t\tEffect.ignore,\n\t\tEffect.repeat(Schedule.spaced(LOCK_HEARTBEAT)),\n\t);\n\n/**\n * Claims `directory` by creating it, polling while another process holds it.\n *\n * One finalizer for the whole wait, registered before the first attempt: retrying inside\n * `acquireRelease` would add a finalizer per poll. A crashed installer leaves its lock\n * behind; an abandoned one is reclaimed rather than waited on forever, and the wait itself\n * is bounded. While held, the lock is heartbeated so waiters can tell live from dead.\n */\nconst lock = Effect.fn(\"PluginPackage.lock\")(function* (directory: string) {\n\tconst held = yield* Ref.make(false);\n\tyield* Effect.acquireRelease(Effect.void, () =>\n\t\tRef.get(held).pipe(\n\t\t\tEffect.flatMap((owned) => (owned ? fs.remove(directory, { recursive: true, force: true }) : Effect.void)),\n\t\t\tEffect.orDie,\n\t\t),\n\t);\n\t// One attempt is uninterruptible so `mkdir` and recording ownership cannot be split: an\n\t// interrupt between them would leave a lock the finalizer does not know to remove.\n\tconst attempt = fs.makeDirectory(directory).pipe(\n\t\tEffect.andThen(Ref.set(held, true)),\n\t\tEffect.as(true),\n\t\tEffect.catchIf(\n\t\t\t(error) => error.reason._tag === \"AlreadyExists\",\n\t\t\t() =>\n\t\t\t\tabandoned(directory).pipe(\n\t\t\t\t\tEffect.flatMap((stale) =>\n\t\t\t\t\t\tstale\n\t\t\t\t\t\t\t? fs.remove(directory, { recursive: true, force: true }).pipe(Effect.as(false))\n\t\t\t\t\t\t\t: Effect.succeed(false),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t),\n\t\tEffect.uninterruptible,\n\t);\n\tconst acquired = yield* attempt.pipe(\n\t\tEffect.repeat({ schedule: Schedule.spaced(\"50 millis\"), until: (owned) => owned }),\n\t\tEffect.timeoutOrElse({ duration: LOCK_TIMEOUT, orElse: () => Effect.succeed(false) }),\n\t);\n\tif (!acquired)\n\t\treturn yield* new InstallError({\n\t\t\tcause: new Error(`Timed out waiting for another plugin installation to release ${directory}`),\n\t\t});\n\t// Scoped to the install: the heartbeat dies with the scope, before the lock is removed.\n\tyield* Effect.forkScoped(heartbeat(directory));\n});\n\nexport const install = Effect.fn(\"PluginPackage.install\")(\n\tfunction* (request: Request, cache: string, runner: Runner = run) {\n\t\tconst root = path.join(cache, \"plugins\");\n\t\tconst key = Encoding.encodeHex(yield* crypto.digest(\"SHA-256\", new TextEncoder().encode(request.spec)));\n\t\tconst directory = path.join(root, key);\n\t\tconst marker = path.join(directory, \".complete.json\");\n\t\tyield* fs.makeDirectory(root, { recursive: true });\n\t\t// A published entry is immutable, so reading one never contends with an installer.\n\t\t// mkdir is atomic across processes; the scoped release also runs on interruption.\n\t\tif (!(yield* fs.exists(marker))) yield* lock(`${directory}.lock`);\n\t\t// Re-check under the lock: the installer we waited for may have just published.\n\t\tif (!(yield* fs.exists(marker))) {\n\t\t\tconst staging = yield* Effect.acquireRelease(\n\t\t\t\tfs.makeTempDirectory({ directory: root, prefix: `${key}-` }),\n\t\t\t\t(staging) => fs.remove(staging, { recursive: true, force: true }).pipe(Effect.orDie),\n\t\t\t);\n\t\t\tyield* fs.writeFileString(path.join(staging, \"package.json\"), '{\"private\":true,\"type\":\"module\"}');\n\t\t\tyield* runner(request, staging);\n\t\t\tconst manifest = yield* fs.readFileString(path.join(staging, \"node_modules\", request.name, \"package.json\"));\n\t\t\tconst installed = yield* Schema.decodeEffect(Schema.fromJsonString(Manifest))(manifest);\n\t\t\t// Validate root resolution before marking this installation complete.\n\t\t\tconst entrypoint = yield* Effect.try(() => resolveModule(request.name, staging));\n\t\t\t// `resolve` realpaths its answer while `makeTempDirectory` does not, so relate the\n\t\t\t// two through the realpath or a symlinked cache root escapes the published entry.\n\t\t\tconst entry = path.relative(yield* fs.realPath(staging), fileURLToPath(entrypoint));\n\t\t\tif (entry.startsWith(\"..\") || path.isAbsolute(entry))\n\t\t\t\treturn yield* new InstallError({\n\t\t\t\t\tcause: new Error(`Plugin entrypoint escapes its installation: ${entry}`),\n\t\t\t\t});\n\t\t\tyield* fs.writeFileString(\n\t\t\t\tpath.join(staging, \".complete.json\"),\n\t\t\t\tyield* Schema.encodeEffect(Schema.fromJsonString(Cached))({\n\t\t\t\t\tspec: request.spec,\n\t\t\t\t\tversion: installed.version,\n\t\t\t\t\tentrypoint: entry,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (yield* fs.exists(directory)) yield* fs.remove(directory, { recursive: true });\n\t\t\tyield* fs.rename(staging, directory);\n\t\t}\n\t\tconst saved = yield* fs\n\t\t\t.readFileString(marker)\n\t\t\t.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Cached))));\n\t\tif (saved.spec !== request.spec)\n\t\t\treturn yield* new InstallError({ cause: new Error(\"Plugin package cache request mismatch\") });\n\t\tconst url = pathToFileURL(path.resolve(directory, saved.entrypoint)).href;\n\t\treturn { url, version: saved.version } satisfies Installed;\n\t},\n\tEffect.scoped,\n\tEffect.mapError((cause) => (Schema.is(InstallError)(cause) ? cause : new InstallError({ cause }))),\n);\n","import { Effect, Predicate, Schema } from \"effect\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { expandTilde } from \"../util/home.ts\";\nimport { importModule, resolveModule } from \"../util/module.ts\";\nimport { fileSystem as fs, hostPath as path } from \"../host.ts\";\nimport * as Package from \"./package.ts\";\nimport type { EventSchema } from \"../event/schema.ts\";\nimport type { Plugin } from \"./plugin.ts\";\n\n/** `vendor.domain.context`, exactly three segments — a fourth would shadow a package name. */\nexport const idPattern = /^[a-z0-9][a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*){2}$/;\nconst Id = Schema.String.check(Schema.isPattern(idPattern));\nconst Definition = Schema.Struct({\n\tid: Id,\n\t// Shape only. What the types mean -- namespace, collisions with the kernel or\n\t// another plugin -- is `EventRegistry.flatten`'s call, since it is the only\n\t// place that sees every plugin at once.\n\tevents: Schema.optional(\n\t\tSchema.Array(\n\t\t\tSchema.declare<EventSchema.Definition>(\n\t\t\t\t(value): value is EventSchema.Definition =>\n\t\t\t\t\tPredicate.hasProperty(value, \"type\") && Predicate.isString(value.type),\n\t\t\t),\n\t\t),\n\t),\n\tsetup: Schema.declare<Plugin[\"setup\"]>((value): value is Plugin[\"setup\"] => Predicate.isFunction(value)),\n});\n\nexport class PreparationError extends Schema.TaggedError<PreparationError>()(\"PluginPreparationError\", {\n\tphase: Schema.Literals([\"source\", \"install\", \"import\", \"definition\"]),\n\tindex: Schema.Finite,\n\treference: Schema.String,\n\tid: Schema.optional(Schema.String),\n\tcause: Schema.Defect(),\n}) {}\n\nexport interface Origin {\n\treadonly index: number;\n\treadonly reference: string;\n}\n\nexport const failure = (origin: Origin, phase: PreparationError[\"phase\"], cause: unknown, id?: string) =>\n\tnew PreparationError({ ...origin, phase, cause, ...(id === undefined ? {} : { id }) });\n\nexport const validate = Effect.fn(\"PluginLoader.validate\")(function* (input: unknown, origin: Origin, builtin = false) {\n\tyield* Schema.decodeUnknownEffect(Definition)(input).pipe(\n\t\tEffect.mapError((cause) => failure(origin, \"definition\", cause)),\n\t);\n\t// The author's own object, not the decoded copy: a `Struct` decode keeps only the\n\t// declared keys, which would strip a plugin's other properties and leave `this`\n\t// pointing at a clone inside the documented `setup() {}` shorthand.\n\tconst plugin = input as Plugin;\n\tif (!builtin && plugin.id.startsWith(\"codework.\")) {\n\t\treturn yield* failure(origin, \"definition\", new Error(\"codework namespace is reserved for builtins\"), plugin.id);\n\t}\n\treturn plugin;\n});\n\nexport type Source =\n\t| { readonly kind: \"local\"; readonly path: string }\n\t| { readonly kind: \"package\"; readonly request: Package.Request };\n\n/**\n * A reference is a source and nothing else: a path, a `file:` URL, or a package spec. IDs are\n * not spelled here — a bare `acme.tool.proc` is a package name, and the plugin it names is\n * addressed by `{ plugin: \"acme.tool.proc\" }`, which resolves against what is already registered.\n */\nexport const classify = (source: string, hostCwd: string): Source => {\n\tif (source.startsWith(\"file:\")) {\n\t\t// Both `new URL` and `fileURLToPath` silently read a relative `file:./x` as `/x`. A file\n\t\t// URL names an absolute path or it is not one.\n\t\tif (!source.startsWith(\"file:///\")) throw new Error(`not an absolute file URL: ${source}`);\n\t\treturn { kind: \"local\", path: fileURLToPath(source) };\n\t}\n\t// `~` before the package branch: npm names cannot start with it, and `npa` would otherwise\n\t// read `~` as a package and `~/x` as an unsupported spec, reporting a path as a bad package.\n\tconst expanded = expandTilde(source, path);\n\tif (expanded.startsWith(\"./\") || expanded.startsWith(\"../\") || path.isAbsolute(expanded)) {\n\t\treturn { kind: \"local\", path: path.resolve(hostCwd, expanded) };\n\t}\n\treturn { kind: \"package\", request: Package.parse(source) };\n};\n\nconst Manifest = Schema.Struct({\n\tname: Schema.optional(Schema.String),\n\texports: Schema.optional(Schema.Unknown),\n});\n\nconst localUrl = Effect.fn(\"PluginLoader.localUrl\")(function* (location: string, origin: Origin) {\n\tconst stat = yield* fs.stat(location);\n\tif (stat.type !== \"Directory\")\n\t\treturn { url: yield* Effect.try(() => resolveModule(location, path.dirname(location))) };\n\tconst manifestPath = path.join(location, \"package.json\");\n\tif (!(yield* fs.exists(manifestPath))) {\n\t\treturn { url: yield* Effect.try(() => resolveModule(\"./index\", location)) };\n\t}\n\tconst manifest = yield* fs\n\t\t.readFileString(manifestPath)\n\t\t.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest))));\n\tif (manifest.exports !== undefined) {\n\t\tconst name = manifest.name;\n\t\tif (!name)\n\t\t\treturn yield* failure(origin, \"source\", new Error(\"A local package with exports must declare its name\"));\n\t\tconst url = yield* Effect.try(() => resolveModule(name, location));\n\t\t// Compare real paths: a symlinked target (or root) can point outside while the\n\t\t// string paths still nest.\n\t\tconst resolved = yield* fs.realPath(fileURLToPath(url));\n\t\tif (path.relative(yield* fs.realPath(location), resolved).startsWith(\"..\"))\n\t\t\treturn yield* failure(origin, \"source\", new Error(\"Package export escapes its root\"));\n\t\treturn { url: pathToFileURL(resolved).href, name };\n\t}\n\tconst url = yield* Effect.try(() =>\n\t\tresolveModule(createRequire(pathToFileURL(manifestPath)).resolve(location), location),\n\t);\n\treturn manifest.name === undefined ? { url } : { url, name: manifest.name };\n});\n\nexport interface Options {\n\treadonly cache: string;\n\t/** The OS process's directory, that constructor-relative references resolve against. Never read here. */\n\treadonly hostCwd: string;\n\treadonly import?: (url: string) => Promise<unknown>;\n\treadonly install?: (\n\t\trequest: Package.Request,\n\t\tcache: string,\n\t) => Effect.Effect<Package.Installed, Package.InstallError>;\n}\n\nexport interface Loaded {\n\treadonly plugin: Plugin;\n\treadonly source: string;\n\treadonly version?: string;\n\t/** The package name a local package declared, registered as one of its aliases. */\n\treadonly name?: string;\n}\n\nexport const load = Effect.fn(\"PluginLoader.load\")(function* (\n\tsource: Extract<Source, { kind: \"local\" | \"package\" }>,\n\torigin: Origin,\n\toptions: Options,\n) {\n\tconst installed =\n\t\tsource.kind === \"package\"\n\t\t\t? yield* (options.install ?? Package.install)(source.request, options.cache).pipe(\n\t\t\t\t\tEffect.mapError((cause) => failure(origin, \"install\", cause)),\n\t\t\t\t)\n\t\t\t: yield* localUrl(source.path, origin).pipe(\n\t\t\t\t\t// `localUrl` already reports its own source failures; only platform errors\n\t\t\t\t\t// reaching here still need attribution.\n\t\t\t\t\tEffect.mapError((cause) =>\n\t\t\t\t\t\tSchema.is(PreparationError)(cause) ? cause : failure(origin, \"source\", cause),\n\t\t\t\t\t),\n\t\t\t\t);\n\tconst module = yield* Effect.tryPromise({\n\t\ttry: () => (options.import ?? importModule)(installed.url),\n\t\tcatch: (cause) => failure(origin, \"import\", cause),\n\t});\n\tconst plugin = yield* validate(\n\t\tPredicate.isObject(module) && \"default\" in module ? module.default : undefined,\n\t\torigin,\n\t);\n\treturn {\n\t\tplugin,\n\t\tsource: origin.reference,\n\t\t...(\"version\" in installed ? { version: installed.version } : {}),\n\t\t// A local package answers to the name it declares, so a path entry can be configured by\n\t\t// the package name its README documents.\n\t\t...(\"name\" in installed && installed.name !== undefined ? { name: installed.name } : {}),\n\t} satisfies Loaded;\n});\n","import { Effect, Predicate } from \"effect\";\nimport { isRecord } from \"../settings/merge.ts\";\nimport * as Loader from \"./loader.ts\";\nimport type { Plugin } from \"./plugin.ts\";\n\n/** Opaque to the harness: a plugin reads and validates its own block. */\nexport type PluginOptions = { readonly [key: string]: unknown };\n/** A module to load: a path, a `file:` URL, or a package spec. Definitions are passed directly. */\nexport type PluginSpec = Plugin | string;\ninterface PluginConfig {\n\t/** `false` drops the plugin from the selection. */\n\treadonly enabled?: boolean | undefined;\n\treadonly options?: PluginOptions | undefined;\n}\n/**\n * Configuration for a plugin something else already selected, naming it by ID (`plugin`) or by\n * the package it came from (`package`) — exactly one of the two. It loads nothing, so a name\n * matching nothing in the selection is ignored rather than fetched.\n */\nexport type PluginPatch =\n\t| (PluginConfig & { readonly plugin: string; readonly package?: never })\n\t| (PluginConfig & { readonly package: string; readonly plugin?: never });\nexport type PluginRef = PluginSpec | PluginPatch;\nexport interface Prepared {\n\treadonly plugin: Plugin;\n\treadonly options: PluginOptions;\n}\nexport interface Catalog {\n\treadonly add: (plugin: Plugin, source?: string, version?: string) => void;\n\treadonly get: (id: string) => Plugin | undefined;\n\treadonly has: (id: string) => boolean;\n}\n\n/** Catalogs belong to one harness configuration. Definitions never execute here. */\nexport const make = (): Catalog => {\n\tconst entries = new Map<string, { plugin: Plugin; source?: string; version?: string }>();\n\treturn {\n\t\tadd: (plugin, source, version) => {\n\t\t\tentries.set(plugin.id, {\n\t\t\t\tplugin,\n\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t});\n\t\t},\n\t\tget: (id) => entries.get(id)?.plugin,\n\t\thas: (id) => entries.has(id),\n\t};\n};\n\nexport interface Options extends Loader.Options {\n\treadonly builtins: ReadonlyArray<Plugin>;\n}\n\n/**\n * A definition carries `setup`; a patch carries `plugin` or `package` and no `setup`. Checking\n * `setup` first matters because `Plugin` permits extra properties, so a definition holding its\n * own `plugin` property must not be read as configuration.\n */\nconst isPatch = (reference: PluginRef): reference is PluginPatch =>\n\tPredicate.isObject(reference) &&\n\t!Predicate.isFunction(reference) &&\n\t!(\"setup\" in reference) &&\n\t(\"plugin\" in reference || \"package\" in reference);\n\n/**\n * Resolve every reference to the ordered selection the harness runs.\n *\n * An array entry is a **module** — a definition object, a path, a `file:` URL, or a package\n * spec. It is loaded if it is not already, and it takes the position it is written at, so\n * naming a module again moves it.\n *\n * An object entry is **configuration** for a plugin an earlier entry (or the built-in list)\n * already selected, addressed by its ID (`plugin`) or by the package it came from (`package`).\n * It never loads, installs or reorders anything, and a name matching nothing in the selection\n * is ignored rather than failing the boot — a typo costs a debug line, never a fetch.\n */\nexport const prepare = Effect.fn(\"PluginCatalog.prepare\")(function* (\n\treferences: ReadonlyArray<PluginRef>,\n\toptions: Options,\n) {\n\tconst catalog = make();\n\tconst hostCwd = options.hostCwd;\n\tfor (const builtin of options.builtins) {\n\t\tcatalog.add(yield* Loader.validate(builtin, { index: -1, reference: builtin.id }, true), \"builtin\");\n\t}\n\t/** Source metadata exists for diagnostics; a silent ID replacement is where it earns that. */\n\tconst note = (plugin: Plugin, source: string) =>\n\t\tcatalog.has(plugin.id)\n\t\t\t? Effect.logDebug(`plugin ${plugin.id} redefined by ${source}; the earlier definition is discarded`)\n\t\t\t: Effect.void;\n\t/**\n\t * Every name a loaded module answers to — its package name, the spec and path it came from,\n\t * and the reference as written — pointing at its ID. Built as the list is walked, so a\n\t * `package` entry can only address a module an earlier entry loaded.\n\t */\n\tconst aliases = new Map<string, string>();\n\tconst operations = new Map<string, { enabled: boolean; origin: Loader.Origin; options: PluginOptions }>();\n\tconst loaded = new Map<string, Loader.Loaded>();\n\t/**\n\t * An ID is a key: the last module to claim it owns it, and the configuration written against\n\t * it stays with the key rather than with whichever module is currently behind it. Two modules\n\t * exporting one ID is the author's conflict to resolve; the replacement is logged.\n\t */\n\tconst select = (id: string, origin: Loader.Origin) =>\n\t\toperations.set(id, { enabled: true, origin, options: operations.get(id)?.options ?? {} });\n\tfor (const [index, reference] of references.entries()) {\n\t\tif (isPatch(reference)) {\n\t\t\t// A settings file is decoded before it reaches here; an embedder's array is not, so the\n\t\t\t// entry shape is checked once for both. A contradictory entry is a mistake worth a\n\t\t\t// failure, unlike a name that simply matches nothing.\n\t\t\tconst named = reference.plugin ?? reference.package;\n\t\t\tconst origin = { index, reference: typeof named === \"string\" ? named : `<plugin entry #${index}>` };\n\t\t\tconst invalid =\n\t\t\t\treference.plugin !== undefined && reference.package !== undefined\n\t\t\t\t\t? \"names both `plugin` and `package`\"\n\t\t\t\t\t: typeof named !== \"string\" || named.length === 0\n\t\t\t\t\t\t? \"names neither `plugin` nor `package`\"\n\t\t\t\t\t\t: reference.enabled !== undefined && typeof reference.enabled !== \"boolean\"\n\t\t\t\t\t\t\t? \"`enabled` is not a boolean\"\n\t\t\t\t\t\t\t: reference.options !== undefined && !isRecord(reference.options)\n\t\t\t\t\t\t\t\t? \"`options` is not a plain object\"\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\tif (invalid !== undefined) {\n\t\t\t\treturn yield* Loader.failure(origin, \"definition\", new Error(`plugin entry ${invalid}`));\n\t\t\t}\n\t\t\t// `plugin` is an ID, `package` is a name a module was loaded under; both end at an ID.\n\t\t\tconst id = reference.plugin === undefined ? aliases.get(reference.package) : reference.plugin;\n\t\t\tconst operation = id === undefined ? undefined : operations.get(id);\n\t\t\tif (id === undefined || operation === undefined) {\n\t\t\t\t// Misspelled, not installed, or not shipped by this build: there is nothing to\n\t\t\t\t// configure, and an entry that loads nothing cannot be worth failing a boot over.\n\t\t\t\tyield* Effect.logDebug(`plugin configuration ignored: nothing selected under ${named}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toperations.set(id, {\n\t\t\t\tenabled: reference.enabled ?? operation.enabled,\n\t\t\t\t// Position stays with the entry that selected it: configuring never moves a plugin.\n\t\t\t\torigin: operation.origin,\n\t\t\t\t// The block is opaque, so the last entry owns it whole rather than merging into\n\t\t\t\t// values the harness cannot interpret.\n\t\t\t\toptions: reference.options ?? operation.options,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\t// An entry reaching here is unvalidated and may be anything a JavaScript caller passed,\n\t\t// including `null`: read an `id` off it only once it is known to have properties, or\n\t\t// `PreparationError.reference` throws instead of reporting the bad entry.\n\t\tconst declared =\n\t\t\ttypeof reference === \"string\" ? reference : Predicate.hasProperty(reference, \"id\") ? reference.id : undefined;\n\t\tconst origin = { index, reference: typeof declared === \"string\" ? declared : `<plugin object #${index}>` };\n\t\tif (typeof reference !== \"string\") {\n\t\t\t// The very definition the catalog already holds — a built-in named by the default\n\t\t\t// selection. Selecting one is not redefining it, so the reserved namespace stands.\n\t\t\tif (typeof declared === \"string\" && catalog.get(declared) === reference) {\n\t\t\t\tselect(declared, origin);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst plugin = yield* Loader.validate(reference, origin);\n\t\t\tyield* note(plugin, \"a supplied object\");\n\t\t\tcatalog.add(plugin, \"object\");\n\t\t\tselect(plugin.id, origin);\n\t\t\tcontinue;\n\t\t}\n\t\tconst source = yield* Effect.try({\n\t\t\ttry: () => Loader.classify(reference, hostCwd),\n\t\t\tcatch: (cause) => Loader.failure(origin, \"source\", cause),\n\t\t});\n\t\tconst key = source.kind === \"package\" ? source.request.spec : source.path;\n\t\tconst definition = loaded.get(key) ?? (yield* Loader.load(source, origin, options));\n\t\tloaded.set(key, definition);\n\t\tyield* note(definition.plugin, definition.version === undefined ? key : `${key}@${definition.version}`);\n\t\tcatalog.add(definition.plugin, definition.source, definition.version);\n\t\t// Every name this module can be configured by later: the reference as written, the package\n\t\t// name and spec, the path on disk, and a local package's own manifest name.\n\t\tconst names =\n\t\t\tsource.kind === \"package\"\n\t\t\t\t? [source.request.name, source.request.spec]\n\t\t\t\t: [source.path, ...(definition.name === undefined ? [] : [definition.name])];\n\t\tfor (const name of [reference, ...names]) aliases.set(name, definition.plugin.id);\n\t\tselect(definition.plugin.id, origin);\n\t}\n\tconst selection: Prepared[] = [];\n\tfor (const [id, operation] of [...operations].sort((a, b) => a[1].origin.index - b[1].origin.index)) {\n\t\t// Disabled by a configuration entry. Every other operation was recorded beside the\n\t\t// `catalog.add` that registered its definition, so the lookup below cannot miss.\n\t\tif (!operation.enabled) continue;\n\t\tconst plugin = catalog.get(id);\n\t\tif (plugin !== undefined) selection.push({ plugin, options: Object.freeze(operation.options) });\n\t}\n\treturn Object.freeze(selection);\n});\n","import type { Effect } from \"effect\";\nimport type { EventSchema } from \"../event/schema.ts\";\nimport type { Location } from \"../location/location.ts\";\nimport type { SandboxIO } from \"../sandbox/io.ts\";\nimport type { PluginOptions } from \"./catalog.ts\";\nimport type { SharedPluginContext } from \"./context.ts\";\n\nexport type Mount = SandboxIO.Provides | Location.Service;\nexport interface Plugin {\n\treadonly id: string;\n\t/**\n\t * Event definitions this plugin publishes. Declared rather than registered at\n\t * runtime so they are known before the event system builds, and so a bad type\n\t * fails the boot instead of the first publish. Types must be namespaced\n\t * `plugin.<id>.*`.\n\t */\n\treadonly events?: ReadonlyArray<EventSchema.Definition>;\n\t/**\n\t * `options` is this plugin's own configuration block, `{}` when its entry carried none.\n\t * Unvalidated: the harness never looks inside it, so a plugin checks whatever shape it\n\t * documents. It is a second argument rather than a context field so `ctx` stays one object\n\t * shared by every plugin in the exchange.\n\t */\n\treadonly setup: (\n\t\tctx: SharedPluginContext,\n\t\toptions: PluginOptions,\n\t) => void | Promise<void> | Effect.Effect<void, unknown, Mount>;\n}\n\nexport const define = (plugin: Plugin): Plugin => plugin;\n","/*\n * @file The built-in Prompt plugin: `codework.prompt.default`.\n *\n * Everything below `setup` is plugin-private. The Prompt domain stores one string\n * and imposes no shape, so this file — not the kernel — owns the foundation, the\n * tool index, the guideline dedupe and the working-directory line. A third party\n * that wants a different prompt omits this plugin or `set`s over it.\n */\n\nimport { Effect } from \"effect\";\nimport type { AnyToolDef } from \"../../../tool/tool.ts\";\nimport type { PromptResolver, SharedPluginContext } from \"../../context.ts\";\nimport { define } from \"../../plugin.ts\";\n\n/** The default coding-agent foundation, used unless `promptCustom` replaces it. */\nconst foundation = `You are an expert coding assistant operating inside codework, a coding agent harness.`;\n\n/**\n * Guidelines that hold regardless of which tools are registered.\n *\n * Kept short on purpose. Every line here is spent on every request, so a line\n * earns its place only if a model measurably behaves worse without it.\n */\nconst standingGuidelines: ReadonlyArray<string> = [\n\t\"Be concise. Report what you did and what you found, not what you are about to do.\",\n\t\"Quote exact paths and command output rather than paraphrasing them.\",\n\t\"If a command fails, read the error before retrying.\",\n];\n\n/** Collapse whitespace so two spellings of one guideline dedupe against each other. */\nconst normalize = (value: string): string => value.trim().replace(/\\s+/g, \" \");\n\n/**\n * Tool-contributed guidelines followed by the standing ones, normalized and\n * deduplicated with first occurrence winning.\n *\n * Tool order is bucket order, which is the same order the index renders in and the\n * same order the provider receives definitions in -- one ordering, not three.\n */\nconst guidelines = (tools: ReadonlyArray<AnyToolDef>): ReadonlyArray<string> => {\n\tconst seen = new Set<string>();\n\tconst collected: string[] = [];\n\tfor (const line of [...tools.flatMap((tool) => tool.promptGuidelines ?? []), ...standingGuidelines]) {\n\t\tconst normalized = normalize(line);\n\t\tif (normalized.length === 0 || seen.has(normalized)) continue;\n\t\tseen.add(normalized);\n\t\tcollected.push(normalized);\n\t}\n\treturn collected;\n};\n\n/**\n * The rendered tool index.\n *\n * `(none)` rather than an omitted section: a model told it has no tools behaves\n * better than one left to infer it from silence.\n */\nconst toolIndex = (tools: ReadonlyArray<AnyToolDef>): string => {\n\tconst listed = tools.filter((tool) => tool.promptSnippet !== undefined && tool.promptSnippet.length > 0);\n\tif (listed.length === 0) return \"(none)\";\n\treturn listed.map((tool) => `- ${tool.name}: ${tool.promptSnippet}`).join(\"\\n\");\n};\n\ninterface Input {\n\treadonly tools: ReadonlyArray<AnyToolDef>;\n\treadonly directory: string;\n\treadonly promptCustom?: string;\n\treadonly promptSystemAppend?: string;\n}\n\nconst assemble = (input: Input): string => {\n\tconst sections: string[] = [input.promptCustom ?? foundation];\n\n\tsections.push(`Available tools:\\n${toolIndex(input.tools)}`);\n\n\tconst lines = guidelines(input.tools);\n\tif (lines.length > 0) sections.push(`Guidelines:\\n${lines.map((line) => `- ${line}`).join(\"\\n\")}`);\n\n\tconst append = input.promptSystemAppend?.trim();\n\tif (append !== undefined && append.length > 0) sections.push(append);\n\n\tsections.push(`Current working directory: ${input.directory}`);\n\n\treturn sections.join(\"\\n\\n\");\n};\n\n/**\n * A caller slot, awaited lazily. A throw or rejection fails the snapshot, which the\n * host attributes to this plugin's id.\n */\nconst slot = (ctx: SharedPluginContext, resolver: PromptResolver | undefined) =>\n\tEffect.tryPromise(() => Promise.resolve(resolver?.(ctx)));\n\nexport const defaultPromptPlugin = define({\n\tid: \"codework.prompt.default\",\n\tsetup: Effect.fn(\"DefaultPromptPlugin.setup\")(function* (ctx) {\n\t\tconst custom = yield* slot(ctx, ctx.config.promptCustom);\n\t\tconst append = yield* slot(ctx, ctx.config.promptSystemAppend);\n\t\tctx.plugin.prompt.set(\n\t\t\tassemble({\n\t\t\t\t// Only tools registered by an earlier plugin are visible here.\n\t\t\t\ttools: ctx.plugin.tools.list(),\n\t\t\t\tdirectory: ctx.location.directory,\n\t\t\t\t...(custom === undefined ? {} : { promptCustom: custom }),\n\t\t\t\t...(append === undefined ? {} : { promptSystemAppend: append }),\n\t\t\t}),\n\t\t);\n\t}),\n});\n","/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits — whichever is hit first\n * wins: a line limit and a byte limit. Lines are never split (except the bash\n * tail edge case where a single line exceeds the byte limit).\n *\n * The bash tool uses {@link truncateTail} (keep the end — errors / final\n * results); file readers use {@link truncateHead} (keep the beginning).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\n\nexport interface TruncationResult {\n\t/** The truncated content. */\n\tcontent: string;\n\t/** Whether truncation occurred. */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated. */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content. */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content. */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output. */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output. */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation). */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation). */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied. */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied. */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: {@link DEFAULT_MAX_LINES}). */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: {@link DEFAULT_MAX_BYTES}). */\n\tmaxBytes?: number;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) {\n\t\tlines.pop();\n\t}\n\treturn lines;\n}\n\n/** Format bytes as a human-readable size. */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t}\n\tif (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t}\n\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n}\n\n/**\n * Truncate content from the head (keep the first N lines/bytes). Suitable for\n * file reads where the beginning matters. Never returns partial lines; if the\n * first line alone exceeds the byte limit, returns empty content with\n * `firstLineExceedsLimit = true`.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\tconst firstLineBytes = Buffer.byteLength(lines[0] ?? \"\", \"utf-8\");\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep the last N lines/bytes). Suitable for\n * bash output where the end matters (errors, final results). May return a\n * partial first line if the last line of the original content exceeds the byte\n * limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i] ?? \"\";\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// If we haven't added any lines yet and this one exceeds maxBytes,\n\t\t\t// keep the tail of the line (partial).\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = Buffer.byteLength(truncatedLine, \"utf-8\");\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end). Handles\n * multi-byte UTF-8 characters correctly (never splits a codepoint).\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tconst buf = Buffer.from(str, \"utf-8\");\n\tif (buf.length <= maxBytes) {\n\t\treturn str;\n\t}\n\n\t// Skip maxBytes back from the end, then advance to a valid UTF-8 boundary.\n\tlet start = buf.length - maxBytes;\n\twhile (start < buf.length && (buf[start]! & 0xc0) === 0x80) {\n\t\tstart++;\n\t}\n\n\treturn buf.subarray(start).toString(\"utf-8\");\n}\n","import { Effect, Encoding, type FileSystem, type Scope } from \"effect\";\nimport { tmpdir } from \"node:os\";\nimport { crypto, fileSystem } from \"../host.ts\";\nimport { posix } from \"../util/posix.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail, type TruncationResult } from \"./truncate.ts\";\n\n/**\n * Incrementally accumulates streaming output with bounded memory.\n * It decodes chunks with a streaming UTF-8 decoder,\n * keeps only a rolling decoded *tail* for snapshots, and spills the full output\n * to a temp file once it exceeds the display limits — so a multi-gigabyte stream\n * never sits in memory.\n *\n * It is a plain mutable class; the streaming bash handler runs it in an Effect\n * scope, so the spill file handle closes on completion, failure, or interrupt.\n */\n\nexport interface OutputAccumulatorOptions {\n\treadonly maxLines?: number;\n\treadonly maxBytes?: number;\n\treadonly tempFilePrefix?: string;\n}\n\nexport interface OutputSnapshot {\n\treadonly content: string;\n\treadonly truncation: TruncationResult;\n\treadonly fullOutputPath?: string;\n}\n\nfunction defaultTempFilePath(prefix: string, suffix: string): string {\n\treturn posix.join(tmpdir(), `${prefix}-${suffix}.log`);\n}\n\nfunction byteLength(text: string): number {\n\treturn Buffer.byteLength(text, \"utf-8\");\n}\n\nexport class Accumulator {\n\tprivate readonly maxLines: number;\n\tprivate readonly maxBytes: number;\n\tprivate readonly maxRollingBytes: number;\n\tprivate readonly tempFilePrefix: string;\n\tprivate readonly decoder = new TextDecoder();\n\n\tprivate rawChunks: Buffer[] = [];\n\tprivate tailText = \"\";\n\tprivate tailBytes = 0;\n\tprivate tailStartsAtLineBoundary = true;\n\tprivate totalRawBytes = 0;\n\tprivate totalDecodedBytes = 0;\n\tprivate completedLines = 0;\n\tprivate totalLines = 0;\n\tprivate currentLineBytes = 0;\n\tprivate hasOpenLine = false;\n\tprivate finished = false;\n\n\tprivate tempFilePath: string | undefined;\n\tprivate tempFile: FileSystem.File | undefined;\n\n\tconstructor(options: OutputAccumulatorOptions = {}) {\n\t\tthis.maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\t\tthis.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\t\tthis.maxRollingBytes = Math.max(this.maxBytes * 2, 1);\n\t\tthis.tempFilePrefix = options.tempFilePrefix ?? \"codework-output\";\n\t}\n\n\tappend(data: Buffer): Effect.Effect<void, never, Scope.Scope> {\n\t\treturn Effect.suspend(() => {\n\t\t\tif (this.finished) return Effect.die(new Error(\"cannot append to a finished output accumulator\"));\n\n\t\t\tthis.totalRawBytes += data.length;\n\t\t\tthis.appendDecodedText(this.decoder.decode(data, { stream: true }));\n\n\t\t\tif (this.tempFile !== undefined || this.shouldUseTempFile()) {\n\t\t\t\treturn Effect.gen({ self: this }, function* () {\n\t\t\t\t\tyield* this.ensureTempFile();\n\t\t\t\t\tyield* this.tempFile!.writeAll(data).pipe(Effect.orDie);\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (data.length > 0) this.rawChunks.push(data);\n\t\t\treturn Effect.void;\n\t\t});\n\t}\n\n\tfinish(): Effect.Effect<void, never, Scope.Scope> {\n\t\treturn Effect.suspend(() => {\n\t\t\tif (this.finished) return Effect.void;\n\t\t\tthis.finished = true;\n\t\t\tthis.appendDecodedText(this.decoder.decode());\n\t\t\treturn Effect.gen({ self: this }, function* () {\n\t\t\t\tif (this.shouldUseTempFile()) yield* this.ensureTempFile();\n\t\t\t\tif (this.tempFile !== undefined) yield* this.tempFile.sync.pipe(Effect.orDie);\n\t\t\t});\n\t\t});\n\t}\n\n\tsnapshot(): OutputSnapshot {\n\t\tconst tailTruncation = truncateTail(this.getSnapshotText(), {\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t});\n\t\tconst truncated = this.totalLines > this.maxLines || this.totalDecodedBytes > this.maxBytes;\n\t\tconst truncatedBy = truncated\n\t\t\t? (tailTruncation.truncatedBy ?? (this.totalDecodedBytes > this.maxBytes ? \"bytes\" : \"lines\"))\n\t\t\t: null;\n\t\tconst truncation: TruncationResult = {\n\t\t\t...tailTruncation,\n\t\t\ttruncated,\n\t\t\ttruncatedBy,\n\t\t\ttotalLines: this.totalLines,\n\t\t\ttotalBytes: this.totalDecodedBytes,\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t};\n\n\t\treturn {\n\t\t\tcontent: truncation.content,\n\t\t\ttruncation,\n\t\t\t...(this.tempFilePath === undefined ? {} : { fullOutputPath: this.tempFilePath }),\n\t\t};\n\t}\n\n\t/** Bytes in the final (possibly unterminated) line — for the partial-line footer. */\n\tgetLastLineBytes(): number {\n\t\treturn this.currentLineBytes;\n\t}\n\n\tprivate appendDecodedText(text: string): void {\n\t\tif (text.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst bytes = byteLength(text);\n\t\tthis.totalDecodedBytes += bytes;\n\t\tthis.tailText += text;\n\t\tthis.tailBytes += bytes;\n\t\tif (this.tailBytes > this.maxRollingBytes * 2) {\n\t\t\tthis.trimTail();\n\t\t}\n\n\t\tlet newlines = 0;\n\t\tlet lastNewline = -1;\n\t\tfor (let i = text.indexOf(\"\\n\"); i !== -1; i = text.indexOf(\"\\n\", i + 1)) {\n\t\t\tnewlines++;\n\t\t\tlastNewline = i;\n\t\t}\n\t\tif (newlines === 0) {\n\t\t\tthis.currentLineBytes += bytes;\n\t\t\tthis.hasOpenLine = true;\n\t\t} else {\n\t\t\tthis.completedLines += newlines;\n\t\t\tconst tail = text.slice(lastNewline + 1);\n\t\t\tthis.currentLineBytes = byteLength(tail);\n\t\t\tthis.hasOpenLine = tail.length > 0;\n\t\t}\n\t\tthis.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0);\n\t}\n\n\tprivate trimTail(): void {\n\t\tconst buffer = Buffer.from(this.tailText, \"utf-8\");\n\t\tif (buffer.length <= this.maxRollingBytes) {\n\t\t\tthis.tailBytes = buffer.length;\n\t\t\treturn;\n\t\t}\n\n\t\tlet start = buffer.length - this.maxRollingBytes;\n\t\twhile (start < buffer.length && (buffer[start]! & 0xc0) === 0x80) {\n\t\t\tstart++;\n\t\t}\n\n\t\tthis.tailStartsAtLineBoundary = start === 0 ? this.tailStartsAtLineBoundary : buffer[start - 1] === 0x0a;\n\t\tthis.tailText = buffer.subarray(start).toString(\"utf-8\");\n\t\tthis.tailBytes = byteLength(this.tailText);\n\t}\n\n\tprivate getSnapshotText(): string {\n\t\tif (this.tailStartsAtLineBoundary) {\n\t\t\treturn this.tailText;\n\t\t}\n\n\t\tconst firstNewline = this.tailText.indexOf(\"\\n\");\n\t\treturn firstNewline === -1 ? this.tailText : this.tailText.slice(firstNewline + 1);\n\t}\n\n\tprivate shouldUseTempFile(): boolean {\n\t\treturn (\n\t\t\tthis.totalRawBytes > this.maxBytes || this.totalDecodedBytes > this.maxBytes || this.totalLines > this.maxLines\n\t\t);\n\t}\n\n\tprivate ensureTempFile(): Effect.Effect<void, never, Scope.Scope> {\n\t\tif (this.tempFile !== undefined) return Effect.void;\n\t\treturn Effect.gen({ self: this }, function* () {\n\t\t\tconst suffix = Encoding.encodeHex(yield* crypto.randomBytes(8));\n\t\t\tthis.tempFilePath = defaultTempFilePath(this.tempFilePrefix, suffix);\n\t\t\tthis.tempFile = yield* fileSystem.open(this.tempFilePath, { flag: \"w\" });\n\t\t\tfor (const chunk of this.rawChunks) yield* this.tempFile.writeAll(chunk);\n\t\t\tthis.rawChunks = [];\n\t\t}).pipe(Effect.orDie);\n\t}\n}\n","import { Context, Effect, Layer } from \"effect\";\nimport type { ModelContent } from \"./tool.ts\";\n\n/**\n * `ToolProgress` — the side-channel a long-running tool (e.g. streaming bash)\n * writes interim output to, instead of an `onUpdate` callback.\n *\n * Most tools never call `report` and keep a clean `Effect<Success, Failure>`\n * signature. Throttling / coalescing lives in the Layer (the live one routes to\n * the run's event PubSub, tagged with the active callID); the handler just\n * reports.\n */\n\n/** Mirror of aikit's `Message.ToolRunningPartial` (kept structural to stay decoupled). */\nexport interface ToolProgressPartial {\n\treadonly content?: ModelContent;\n\treadonly details?: unknown;\n}\n\nexport interface IToolProgress {\n\treadonly report: (partial: ToolProgressPartial) => Effect.Effect<void>;\n}\n\nexport class ToolProgress extends Context.Service<ToolProgress, IToolProgress>()(\n\t\"@codeworksh/harness/tool/progress/ToolProgress\",\n) {}\n\n/** Build a `ToolProgress` Layer from a `report` implementation. */\nexport const make = (report: IToolProgress[\"report\"]): Layer.Layer<ToolProgress> =>\n\tLayer.succeed(ToolProgress, ToolProgress.of({ report }));\n\n/** Drops every update — the default until the executor wires a live event sink. */\nexport const noop: Layer.Layer<ToolProgress> = make(() => Effect.void);\n","import { Context, Duration, Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { Shell } from \"../sandbox/shell/shell.ts\";\n\n/**\n * `ToolShell` — the tool-owned, cancellable command-execution capability the bash tool depends on.\n *\n * It deliberately does **not** reuse `sandbox/Shell` directly: the local OS path\n * provides no `Shell` at all, and `sandbox/Shell` models neither cancellation\n * nor a timeout. `ToolShell` makes both part of the contract. Adapters honor the\n * mid-flight process kill where the SDK allows it (local, Vercel) and fall back\n * to the timeout where it does not (Daytona) — \"kill where it's easy\".\n *\n * Two modes, and Local has two variants:\n * - Local / full OS shell → {@link local} (default)\n * - Local / just-bash → {@link fromSandboxShell} over `EnvBash`\n * - Remote / provider → {@link fromSandboxShell} over `EnvDaytona` / `EnvVercel`\n */\n\n/** Infra/spawn failure — not model-actionable; handlers should treat it as a defect. */\nexport class ToolShellError extends Schema.TaggedError<ToolShellError>()(\"ToolShellError\", {\n\tcommand: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\n/** The command exceeded its deadline. Distinct so handlers can map it to a domain timeout. */\nexport class ToolShellTimeout extends Schema.TaggedError<ToolShellTimeout>()(\"ToolShellTimeout\", {\n\tcommand: Schema.String,\n\ttimeoutMillis: Schema.Finite,\n}) {}\n\nexport interface ToolShellResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number;\n}\n\nexport interface ToolShellExecOptions {\n\treadonly cwd?: string;\n\treadonly env?: Record<string, string>;\n\treadonly timeout?: Duration.Input;\n\t/**\n\t * Grace period before escalating SIGTERM → SIGKILL on cancel/timeout. Honored\n\t * by `ToolShell.local`; overrides the adapter's configured default for this\n\t * call. Other adapters ignore it.\n\t */\n\treadonly forceKillAfter?: Duration.Input;\n}\n\nconst widenExecError = <A>(\n\teffect: Effect.Effect<A, ToolShellError>,\n): Effect.Effect<A, ToolShellError | ToolShellTimeout> =>\n\teffect.pipe(Effect.mapError((error): ToolShellError | ToolShellTimeout => error));\n\n/**\n * A streamed shell event: interleaved output chunks, terminated by a single\n * `Exit` carrying the exit code. (A stream has no separate \"final value\", so the\n * exit rides as the last element.)\n */\nexport type ToolShellEvent =\n\t| { readonly _tag: \"Output\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"Exit\"; readonly exitCode: number };\n\nexport interface IToolShell {\n\t/**\n\t * Run a command to completion. Cancellable by contract: fiber interruption\n\t * returns control, and `timeout` bounds the command. Whether the underlying\n\t * process dies mid-flight depends on the adapter.\n\t */\n\treadonly exec: (\n\t\tcommand: string,\n\t\toptions?: ToolShellExecOptions,\n\t) => Effect.Effect<ToolShellResult, ToolShellError | ToolShellTimeout>;\n\t/**\n\t * Optional streaming output (variant B): combined stdout/stderr chunks then a\n\t * terminal `Exit`. Absent → the tool falls back to {@link exec}. Offered by\n\t * `ToolShell.local`. The process group is killed when the consuming scope\n\t * closes (interrupt / timeout), so the *consumer* owns the deadline and keeps\n\t * whatever output it accumulated.\n\t */\n\treadonly stream?: (command: string, options?: ToolShellExecOptions) => Stream.Stream<ToolShellEvent, ToolShellError>;\n}\n\nexport class ToolShell extends Context.Service<ToolShell, IToolShell>()(\"@codeworksh/harness/tool/shell/ToolShell\") {}\n\n/**\n * Bridge the existing `sandbox/Shell` into a `ToolShell`. Used for just-bash\n * (in-process) and remote providers.\n *\n * `cwd` and `env` both pass through to the backing `sandbox/Shell`, which\n * resolves a relative `cwd` against its mount. The buffered `exec`\n * timeout is enforced here with `Effect.timeoutOption` (interruption always\n * returns control; the underlying command is only truly killed mid-flight on\n * signal-aware backends, handled in the provider layer). When the backend exposes\n * `stream` (e.g. Vercel `Command.logs`), it is bridged to {@link IToolShell.stream}\n * so the bash tool streams over it too.\n */\nexport const fromSandboxShell: Layer.Layer<ToolShell, never, Shell> = Layer.effect(\n\tToolShell,\n\tEffect.gen(function* () {\n\t\tconst shell = yield* Shell;\n\n\t\tconst exec: IToolShell[\"exec\"] = (command, options) => {\n\t\t\tconst run = shell\n\t\t\t\t.exec(command, {\n\t\t\t\t\t...(options?.env ? { env: options.env } : {}),\n\t\t\t\t\t...(options?.cwd ? { cwd: options.cwd } : {}),\n\t\t\t\t})\n\t\t\t\t.pipe(Effect.mapError((cause) => new ToolShellError({ command, cause })));\n\n\t\t\tif (options?.timeout === undefined) return widenExecError(run);\n\n\t\t\tconst timeout = options.timeout;\n\t\t\treturn run.pipe(\n\t\t\t\tEffect.timeoutOption(timeout),\n\t\t\t\tEffect.flatMap(\n\t\t\t\t\tOption.match({\n\t\t\t\t\t\tonNone: () =>\n\t\t\t\t\t\t\tEffect.fail(new ToolShellTimeout({ command, timeoutMillis: Duration.toMillis(timeout) })),\n\t\t\t\t\t\tonSome: Effect.succeed,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t};\n\n\t\t// Bridge the backend's optional streaming (e.g. Vercel `Command.logs`) into\n\t\t// `ToolShell.stream`: stdout/stderr chunks fold into `Output`, `exit` into\n\t\t// `Exit`. The deadline for the streaming path is the consumer's (the bash tool).\n\t\tconst sandboxStream = shell.stream;\n\t\tconst stream: IToolShell[\"stream\"] = sandboxStream\n\t\t\t? (command, options) =>\n\t\t\t\t\tsandboxStream(command, {\n\t\t\t\t\t\t...(options?.env ? { env: options.env } : {}),\n\t\t\t\t\t\t...(options?.cwd ? { cwd: options.cwd } : {}),\n\t\t\t\t\t}).pipe(\n\t\t\t\t\t\tStream.map((chunk): ToolShellEvent =>\n\t\t\t\t\t\t\tchunk._tag === \"exit\"\n\t\t\t\t\t\t\t\t? { _tag: \"Exit\", exitCode: chunk.exitCode }\n\t\t\t\t\t\t\t\t: { _tag: \"Output\", bytes: chunk.bytes },\n\t\t\t\t\t\t),\n\t\t\t\t\t\tStream.mapError((cause) => new ToolShellError({ command, cause })),\n\t\t\t\t\t)\n\t\t\t: undefined;\n\n\t\treturn ToolShell.of(stream ? { exec, stream } : { exec });\n\t}),\n);\n\n/** Default shell used by {@link local}. */\nconst DEFAULT_SHELL = \"bash\";\n\n/**\n * Grace period before escalating SIGTERM → SIGKILL on cancel/timeout. Without\n * this, a command that traps or ignores SIGTERM (and whose children inherit that\n * `SIG_IGN`) would keep the cleanup waiting forever, so the per-call `timeout`\n * would not be a hard bound. One second gives well-behaved processes room to\n * exit cleanly while keeping cancellation snappy.\n */\nconst DEFAULT_FORCE_KILL_AFTER: Duration.Input = Duration.seconds(1);\n\nexport interface LocalConfig {\n\t/** Default working directory for commands that don't specify one. */\n\treadonly cwd?: string;\n\t/** Shell binary used to run commands (default: \"bash\"). */\n\treadonly shell?: string;\n\t/** Extra environment merged over `process.env` (a call's own `env` wins). */\n\treadonly env?: Record<string, string>;\n\t/**\n\t * How long to wait after SIGTERM before sending SIGKILL to the process group\n\t * (default 1s). Guarantees the timeout/interrupt is a hard bound even for\n\t * commands that ignore SIGTERM.\n\t */\n\treadonly forceKillAfter?: Duration.Input;\n}\n\n/**\n * `ToolShell.local` — the default, most-used backend: a real OS shell.\n *\n * Built on Effect's `ChildProcessSpawner` (the same spawner wired as\n * `Sandbox.Process.host`), which spawns detached — its own process group on Unix\n * — and group-kills (negative-pid on Unix, `taskkill /T` on Windows) when the\n * scope closes. But the spawner's cleanup sends SIGTERM and then *awaits exit*,\n * so a command that traps/ignores SIGTERM (its children inherit that `SIG_IGN`)\n * would hang the cleanup — and the timeout would not be a hard bound.\n *\n * So we add an explicit escalation finalizer: on scope close (timeout or interrupt) it\n * SIGTERMs the group and, if the process has not exited within\n * `forceKillAfter`, SIGKILLs it (SIGKILL cannot be trapped). It is registered\n * after the spawn, so it runs *before* the spawner's own release — which then\n * sees an exited process and returns at once. No manual `killProcessTree`, no\n * `AbortSignal` plumbing, no `try/finally`.\n *\n * Provide the spawner where the runtime is assembled, e.g.\n * `ToolShell.local({ cwd }).pipe(Layer.provide(Sandbox.Process.host))`.\n */\nexport const local = (config?: LocalConfig): Layer.Layer<ToolShell, never, ChildProcessSpawner.ChildProcessSpawner> =>\n\tLayer.effect(\n\t\tToolShell,\n\t\tEffect.gen(function* () {\n\t\t\t// Capture the spawner once so each call resolves to `R = never`.\n\t\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\t\tconst shell = config?.shell ?? DEFAULT_SHELL;\n\t\t\tconst configForceKillAfter = config?.forceKillAfter ?? DEFAULT_FORCE_KILL_AFTER;\n\n\t\t\t// Hard-bound cancellation. On scope close (timeout / interrupt), if the\n\t\t\t// process is still running, SIGTERM its group and escalate to SIGKILL after\n\t\t\t// the grace period. Registered after the spawn so it runs before the\n\t\t\t// spawner's own release — which would otherwise await exit and hang on a\n\t\t\t// SIGTERM-ignoring command. `handle.kill` targets the group, and the SIGTERM\n\t\t\t// kill awaits exit, so we bound it with `timeoutOption` and fall through to\n\t\t\t// the untrappable SIGKILL.\n\t\t\tconst escalateKill = (handle: ChildProcessSpawner.ChildProcessHandle, grace: Duration.Input) =>\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst running = yield* handle.isRunning.pipe(Effect.orElseSucceed(() => false));\n\t\t\t\t\tif (!running) return;\n\t\t\t\t\tyield* handle.kill({ killSignal: \"SIGTERM\" }).pipe(\n\t\t\t\t\t\tEffect.timeoutOption(grace),\n\t\t\t\t\t\tEffect.flatMap(\n\t\t\t\t\t\t\tOption.match({\n\t\t\t\t\t\t\t\tonSome: () => Effect.void,\n\t\t\t\t\t\t\t\tonNone: () => handle.kill({ killSignal: \"SIGKILL\" }),\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.ignore,\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\tconst exec: IToolShell[\"exec\"] = (command, options) => {\n\t\t\t\t// Per-call option wins, else the adapter default, else the built-in default.\n\t\t\t\tconst forceKillAfter = options?.forceKillAfter ?? configForceKillAfter;\n\t\t\t\tconst run = Effect.gen(function* () {\n\t\t\t\t\tconst handle = yield* ChildProcess.make(shell, [\"-c\", command], {\n\t\t\t\t\t\tcwd: options?.cwd ?? config?.cwd,\n\t\t\t\t\t\tenv: { ...config?.env, ...options?.env },\n\t\t\t\t\t\textendEnv: true,\n\t\t\t\t\t\tstdin: \"ignore\",\n\t\t\t\t\t\tstdout: \"pipe\",\n\t\t\t\t\t\tstderr: \"pipe\",\n\t\t\t\t\t});\n\t\t\t\t\tyield* Effect.addFinalizer(() => escalateKill(handle, forceKillAfter));\n\n\t\t\t\t\t// Drain both streams while waiting for exit.\n\t\t\t\t\tconst collected = yield* Effect.all(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),\n\t\t\t\t\t\t\tstderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),\n\t\t\t\t\t\t\texitCode: handle.exitCode,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ concurrency: \"unbounded\" },\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstdout: collected.stdout,\n\t\t\t\t\t\tstderr: collected.stderr,\n\t\t\t\t\t\texitCode: collected.exitCode,\n\t\t\t\t\t} satisfies ToolShellResult;\n\t\t\t\t}).pipe(\n\t\t\t\t\tEffect.scoped,\n\t\t\t\t\tEffect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n\t\t\t\t\tEffect.mapError((cause) => new ToolShellError({ command, cause })),\n\t\t\t\t);\n\n\t\t\t\tif (options?.timeout === undefined) return widenExecError(run);\n\n\t\t\t\tconst timeout = options.timeout;\n\t\t\t\treturn run.pipe(\n\t\t\t\t\tEffect.timeoutOption(timeout),\n\t\t\t\t\tEffect.flatMap(\n\t\t\t\t\t\tOption.match({\n\t\t\t\t\t\t\tonNone: () =>\n\t\t\t\t\t\t\t\tEffect.fail(new ToolShellTimeout({ command, timeoutMillis: Duration.toMillis(timeout) })),\n\t\t\t\t\t\t\tonSome: Effect.succeed,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t};\n\n\t\t\t// Streaming: combined stdout/stderr chunks then a terminal `Exit`. The\n\t\t\t// process group is killed (with escalation) when the consuming scope closes,\n\t\t\t// so an interrupted/timed-out consumer keeps whatever it accumulated.\n\t\t\t// Note: `options` attributes can be used when a direct ToolShell caller (or a future tool) wants per-call cwd/env/forceKillAfter.\n\t\t\t// Otherwise fallback to `config`\n\t\t\tconst stream: NonNullable<IToolShell[\"stream\"]> = (command, options) => {\n\t\t\t\tconst forceKillAfter = options?.forceKillAfter ?? configForceKillAfter;\n\t\t\t\t// `Stream.unwrap` ties the spawn's Scope to the stream's lifetime, so the\n\t\t\t\t// escalateKill finalizer runs when consumption ends or is interrupted.\n\t\t\t\treturn Stream.unwrap(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst handle = yield* ChildProcess.make(shell, [\"-c\", command], {\n\t\t\t\t\t\t\tcwd: options?.cwd ?? config?.cwd,\n\t\t\t\t\t\t\tenv: { ...config?.env, ...options?.env },\n\t\t\t\t\t\t\textendEnv: true,\n\t\t\t\t\t\t\tstdin: \"ignore\",\n\t\t\t\t\t\t\tstdout: \"pipe\",\n\t\t\t\t\t\t\tstderr: \"pipe\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tyield* Effect.addFinalizer(() => escalateKill(handle, forceKillAfter));\n\t\t\t\t\t\tconst output = handle.all.pipe(Stream.map((bytes): ToolShellEvent => ({ _tag: \"Output\", bytes })));\n\t\t\t\t\t\tconst exit = Stream.fromEffect(handle.exitCode).pipe(\n\t\t\t\t\t\t\tStream.map((exitCode): ToolShellEvent => ({ _tag: \"Exit\", exitCode })),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn Stream.concat(output, exit);\n\t\t\t\t\t}),\n\t\t\t\t).pipe(\n\t\t\t\t\tStream.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n\t\t\t\t\tStream.mapError((cause) => new ToolShellError({ command, cause })),\n\t\t\t\t);\n\t\t\t};\n\n\t\t\treturn ToolShell.of({ exec, stream });\n\t\t}),\n\t);\n","import { Schema } from \"effect\";\n\n/** A typed wrapper for a tool failure crossing the heterogeneous registry boundary. */\nexport class ToolExecutionError extends Schema.TaggedError<ToolExecutionError>()(\"ToolExecutionError\", {\n\ttoolName: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n","import type { Message } from \"@codeworksh/aikit\";\nimport { Effect, type Layer, Schema } from \"effect\";\nimport type { TSchema } from \"typebox\";\nimport { ToolExecutionError } from \"./error.ts\";\nimport type { ToolProgress } from \"./progress.ts\";\n\n/**\n * The tool definition + handler model.\n *\n * A tool definition is pure, serializable data: name, description, and Effect\n * Schema for parameters / success / failure. Execution is a separate `Handler`\n * — an `Effect` whose capability dependencies (e.g. `ToolShell`) live in its\n * requirements `R`, provided by a Layer at runtime. Separating the two is the\n * main testing win: assert on the definition as plain data, and run the handler\n * against a stub capability Layer.\n *\n * Effect Schema is the single source of truth. {@link toAikitTool} derives a\n * provider-safe JSON Schema object for the aikit wire view; the harness\n * decode/encodes arguments and results with Effect Schema natively (it does not\n * use aikit's Typebox validators).\n */\n\n/** What the model reads next turn (the `content` side of content/details). */\nexport type ModelContent = ReadonlyArray<Message.TextContent | Message.ImageContent>;\n\n/** Per-call metadata handed to a handler instead of positional args. */\nexport const ToolCallContext = Schema.Struct({\n\tcallID: Schema.String,\n\ttoolName: Schema.String,\n\trawArgs: Schema.Record(Schema.String, Schema.Unknown),\n});\nexport type ToolCallContext = typeof ToolCallContext.Type;\n\n/**\n * A pure tool definition. Parametrised over the *schema* instances so the\n * decoded parameter/success/failure types can be recovered via `[\"Type\"]`.\n */\nexport interface ToolDef<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\t/** Human-readable display label (kept from the previous `AgentTool`). */\n\treadonly label?: string;\n\t/**\n\t * A short one-line summary for compact tool listings (e.g. a system-prompt tool index),\n\t * distinct from the fuller `description`.\n\t */\n\treadonly promptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\treadonly promptGuidelines?: ReadonlyArray<string>;\n\treadonly parameters: Params;\n\treadonly success: Success;\n\t/** Declared, model-visible failures (typed). Omit for tools that cannot fail expectedly. */\n\treadonly failure?: Failure;\n\t/** Render success for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\t/** Render an expected failure for the model. Omit → executor falls back to JSON text. */\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n}\n\n/** A handler: validated params + context → typed success or typed failure. */\nexport type Handler<Params extends Schema.Top, Success extends Schema.Top, Failure extends Schema.Top, R = never> = (\n\tparams: Params[\"Type\"],\n\tctx: ToolCallContext,\n) => Effect.Effect<Success[\"Type\"], Failure[\"Type\"], R>;\n\n/** A definition paired with its handler (the unit the executor runs). */\nexport interface ToolImpl<\n\tName extends string = string,\n\tParams extends Schema.Top = Schema.Top,\n\tSuccess extends Schema.Top = Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n> {\n\treadonly definition: ToolDef<Name, Params, Success, Failure>;\n\treadonly handler: Handler<Params, Success, Failure, R>;\n}\n\n// Heterogeneous-collection aliases. `any` for the schema generics keeps handlers\n// of differing parameter types assignable into one array (the precise generics\n// live on the authoring helpers below).\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolDef = ToolDef<string, any, any, any>;\n// biome-ignore lint/suspicious/noExplicitAny: erased schema generics for storage\nexport type AnyToolImpl<R = never> = ToolImpl<string, any, any, any, R>;\n\ninterface DefineInput<\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n> {\n\treadonly name: Name;\n\treadonly description: string;\n\treadonly label?: string;\n\treadonly promptSnippet?: string;\n\treadonly parameters: Params;\n\treadonly success: Success;\n\treadonly failure?: Failure;\n\treadonly encodeContent?: (success: Success[\"Type\"]) => ModelContent;\n\treadonly encodeFailureContent?: (failure: Failure[\"Type\"]) => ModelContent;\n}\n\n/** Define a pure tool (handler attached later via {@link implement} or a toolkit). */\nexport const define = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure>,\n): ToolDef<Name, Params, Success, Failure> => ({\n\t...input,\n});\n\n/** Attach a handler to an existing definition (the testable def/exec split). */\nexport const implement = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR = never,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, R>,\n): ToolImpl<Name, Params, Success, Failure, R> => ({ definition, handler });\n\n/** Sugar for the co-located case: a definition with its handler in one object. */\nexport const make = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top = Schema.Top,\n\tR = never,\n>(\n\tinput: DefineInput<Name, Params, Success, Failure> & {\n\t\treadonly handler: Handler<Params, Success, Failure, R>;\n\t},\n): ToolImpl<Name, Params, Success, Failure, R> => {\n\tconst { handler, ...rest } = input;\n\treturn { definition: define(rest), handler };\n};\n\n/**\n * A tool ready to register: its capability requirements have been discharged, leaving only\n * the executor-provided {@link ToolProgress}. The registry and executor hold `RegisteredTool`s\n * and are non-generic (only `handle` is generic, over a progress sink's `RProgress`), so any\n * number of tools — built-in or\n * third-party/plugin — compose without a shared capability union\n */\nexport interface RegisteredTool {\n\treadonly definition: AnyToolDef;\n\treadonly handler: (\n\t\tparams: unknown,\n\t\tctx: ToolCallContext,\n\t) => Effect.Effect<unknown, ToolExecutionError, ToolProgress>;\n}\n\nconst toRegistered = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\tdefinition: ToolDef<Name, Params, Success, Failure>,\n\thandler: Handler<Params, Success, Failure, ToolProgress>,\n): RegisteredTool => ({\n\tdefinition,\n\t// The executor decodes with `definition.parameters` before invoking this\n\t// erased handler, so restoring the authored parameter type is safe here.\n\thandler: (params, ctx) =>\n\t\thandler(params as Params[\"Type\"], ctx).pipe(\n\t\t\tEffect.mapError((cause) => new ToolExecutionError({ toolName: definition.name, cause })),\n\t\t),\n});\n\n/** Register a tool whose only requirement is the executor-provided progress service. */\nexport const register = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, ToolProgress>,\n): RegisteredTool => toRegistered(impl.definition, impl.handler);\n\n/**\n * Discharge a tool's capability requirements into a {@link RegisteredTool}, erasing its `R`\n * (the executor still provides `ToolProgress`). This is the registration boundary: a\n * plugin/third-party tool provides its own fully-resolved capability Layer here, so the\n * registry never has to unify anyone's `R`.\n */\nexport const provide = <\n\tName extends string,\n\tParams extends Schema.Top,\n\tSuccess extends Schema.Top,\n\tFailure extends Schema.Top,\n\tR,\n>(\n\timpl: ToolImpl<Name, Params, Success, Failure, R | ToolProgress>,\n\tlayer: Layer.Layer<R>,\n): RegisteredTool =>\n\t// `Effect.provide` discharges `R`, leaving `ToolProgress`. TS can't simplify\n\t// `Exclude<ToolProgress, R>` for a generic `R`, so localize the cast before\n\t// crossing the registered-tool boundary.\n\ttoRegistered(impl.definition, ((params, ctx) => impl.handler(params, ctx).pipe(Effect.provide(layer))) as Handler<\n\t\tParams,\n\t\tSuccess,\n\t\tFailure,\n\t\tToolProgress\n\t>);\n\n/**\n * Derive a provider-safe JSON Schema object from an Effect Schema. This is the\n * single boundary that crosses into the provider wire; if a provider rejects a\n * construct, fix it here. Draft-07 inlines the root (no top-level `$ref`).\n */\nexport const toProviderJsonSchema = (schema: Schema.Top): Record<string, unknown> =>\n\tSchema.toStandardJSONSchemaV1(schema)[\"~standard\"].jsonSchema.input({ target: \"draft-07\" });\n\n/**\n * Build the aikit `Message.Tool` wire view from a definition. The derived JSON\n * Schema object satisfies aikit's `parameters` slot structurally at runtime; the\n * single localized cast keeps aikit untouched (decision 3-A).\n */\nexport const toAikitTool = (def: AnyToolDef): Message.Tool => ({\n\tname: def.name,\n\tdescription: def.description,\n\tparameters: toProviderJsonSchema(def.parameters) as unknown as TSchema,\n});\n","import { Duration, Effect, Encoding, Layer, Option, Ref, Schema, Stream } from \"effect\";\nimport { tmpdir } from \"node:os\";\nimport { crypto, fileSystem } from \"../../../host.ts\";\nimport { SandboxIO } from \"../../../sandbox/io.ts\";\nimport { Accumulator, type OutputSnapshot } from \"../../../tool/accumulator.ts\";\nimport { ToolProgress } from \"../../../tool/progress.ts\";\nimport { fromSandboxShell, type IToolShell, ToolShell } from \"../../../tool/shell.ts\";\nimport * as Tool from \"../../../tool/tool.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttruncateTail,\n\ttype TruncationResult,\n} from \"../../../tool/truncate.ts\";\nimport { posix } from \"../../../util/posix.ts\";\nimport { define } from \"../../plugin.ts\";\n\n/**\n * The self-contained bash plugin — a worked example for tool plugins. The definition is pure data;\n * the handler depends only on {@link ToolShell} / {@link ToolProgress}, never\n * `sandbox/Shell`, so the backend (local OS / just-bash / remote provider) is\n * swapped by changing the provided Layer with no change to the tool.\n *\n * Two execution paths, picked by capability:\n * - **variant A (buffered)** otherwise: `ToolShell.exec` returns the full output,\n * truncated once after completion.\n * - **variant B (streaming)** when the backend offers `ToolShell.stream`: output\n * flows through an {@link Accumulator} (bounded memory + temp-file spill)\n * and is reported live via {@link ToolProgress}; on timeout the partial output\n * produced so far is preserved.\n *\n * Success and failure carry the *same* structured shape\n * (`output`, `exitCode`, `truncated`, `fullOutputPath`)\n * — a non-zero exit is just `exitCode !== 0`, not a different kind of result.\n */\n\nconst BashParams = Schema.Struct({\n\tcommand: Schema.String.annotate({ description: \"The bash command to execute.\" }),\n\ttimeout: Schema.optional(\n\t\tSchema.Finite.check(Schema.isGreaterThan(0)).annotate({\n\t\t\tdescription: \"Optional timeout in seconds (must be greater than 0).\",\n\t\t}),\n\t),\n});\n\n// Shared structured fields, so a programmatic consumer reads truncation / the\n// full-output path the same way whether the command succeeded or failed.\nconst outputFields = {\n\t/** Combined stdout + stderr, truncated for display (full output is on disk when `truncated`). */\n\toutput: Schema.String,\n\ttruncated: Schema.Boolean,\n\tfullOutputPath: Schema.optional(Schema.String),\n};\n\nconst BashSuccess = Schema.Struct({ ...outputFields, exitCode: Schema.Finite });\n\n/** Non-zero exit — expected, model-visible. Carries the same shape as success. */\nclass BashFailed extends Schema.TaggedError<BashFailed>()(\"BashFailed\", {\n\t...outputFields,\n\texitCode: Schema.Finite,\n}) {}\n\n/** Deadline exceeded — expected, model-visible. Carries the partial output produced so far. */\nclass BashTimedOut extends Schema.TaggedError<BashTimedOut>()(\"BashTimedOut\", {\n\t...outputFields,\n\ttimeoutSeconds: Schema.Finite,\n}) {}\n\nconst BashFailure = Schema.Union([BashFailed, BashTimedOut]);\ntype BashFailureError = BashFailed | BashTimedOut;\n\nexport const bashDef = Tool.define({\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tpromptSnippet: \"Execute bash commands (ls, grep, find, etc.).\",\n\tdescription:\n\t\t\"Execute a bash command in the working directory and return its combined stdout/stderr output. \" +\n\t\t`Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES}KB (whichever is hit first); when truncated, the full ` +\n\t\t\"output is saved to a temp file. A non-zero exit code is reported as an error carrying the captured output.\",\n\tparameters: BashParams,\n\tsuccess: BashSuccess,\n\tfailure: BashFailure,\n\t// The model reads just the command output, not the JSON envelope.\n\tencodeContent: (success) => [{ type: \"text\", text: success.output }],\n\tencodeFailureContent: (failure) => [{ type: \"text\", text: failure.output }],\n});\n\n/** The structured, model-facing shape of a presented result (ready to spread). */\ninterface Presented {\n\treadonly output: string;\n\treadonly truncated: boolean;\n\treadonly fullOutputPath?: string;\n}\n\n/** Combine stdout and stderr into one stream of text, stderr after stdout. */\nconst combineOutput = (stdout: string, stderr: string): string => {\n\tif (stderr.length === 0) return stdout;\n\tif (stdout.length === 0) return stderr;\n\treturn `${stdout}\\n${stderr}`;\n};\n\n/** One-line footer appended to truncated, model-facing output. */\nconst footer = (t: TruncationResult, fullOutputPath: string | undefined, lastLineBytes?: number): string => {\n\tconst where = fullOutputPath ? ` Full output: ${fullOutputPath}` : \"\";\n\tconst startLine = t.totalLines - t.outputLines + 1;\n\tif (t.lastLinePartial) {\n\t\tconst lineSize = lastLineBytes !== undefined ? ` (line is ${formatSize(lastLineBytes)})` : \"\";\n\t\treturn `\\n\\n[showing last ${formatSize(t.outputBytes)} of line ${t.totalLines}${lineSize}.${where}]`;\n\t}\n\tif (t.truncatedBy === \"lines\") {\n\t\treturn `\\n\\n[showing lines ${startLine}-${t.totalLines} of ${t.totalLines}.${where}]`;\n\t}\n\treturn `\\n\\n[showing lines ${startLine}-${t.totalLines} of ${t.totalLines} (${formatSize(t.maxBytes)} limit).${where}]`;\n};\n\n/** Write full output to a host temp file (best-effort; undefined on failure). */\nconst spillToTempFile = (content: string): Effect.Effect<string | undefined> =>\n\tEffect.gen(function* () {\n\t\tconst suffix = Encoding.encodeHex(yield* crypto.randomBytes(6));\n\t\tconst path = posix.join(tmpdir(), `codework-bash-${suffix}.log`);\n\t\tyield* fileSystem.writeFileString(path, content);\n\t\treturn path;\n\t}).pipe(Effect.orElseSucceed(() => undefined));\n\n/** Variant A: truncate the buffered output once, spilling the full output if truncated. */\nconst presentBuffered = (combined: string): Effect.Effect<Presented> =>\n\tEffect.gen(function* () {\n\t\tconst t = truncateTail(combined);\n\t\tif (!t.truncated) return { output: t.content, truncated: false };\n\t\tconst fullOutputPath = yield* spillToTempFile(combined);\n\t\treturn {\n\t\t\toutput: t.content + footer(t, fullOutputPath),\n\t\t\ttruncated: true,\n\t\t\t...(fullOutputPath !== undefined ? { fullOutputPath } : {}),\n\t\t};\n\t});\n\n/** Variant B: present an accumulator snapshot (the temp file is spilled incrementally). */\nconst presentSnapshot = (snap: OutputSnapshot, lastLineBytes: number): Presented => {\n\tif (!snap.truncation.truncated) return { output: snap.content, truncated: false };\n\treturn {\n\t\toutput: snap.content + footer(snap.truncation, snap.fullOutputPath, lastLineBytes),\n\t\ttruncated: true,\n\t\t...(snap.fullOutputPath !== undefined ? { fullOutputPath: snap.fullOutputPath } : {}),\n\t};\n};\n\n/** Variant A — buffered: one `exec`, truncate after completion. No live progress. */\nconst runBuffered = (\n\tshell: IToolShell,\n\tparams: typeof BashParams.Type,\n): Effect.Effect<typeof BashSuccess.Type, BashFailureError> =>\n\tEffect.gen(function* () {\n\t\tconst result = yield* shell\n\t\t\t.exec(params.command, params.timeout !== undefined ? { timeout: Duration.seconds(params.timeout) } : undefined)\n\t\t\t.pipe(\n\t\t\t\t// A deadline becomes a model-visible BashTimedOut (no partial output is\n\t\t\t\t// available from a buffered exec); an infra/spawn failure is not\n\t\t\t\t// model-actionable, so it becomes a defect (run error).\n\t\t\t\tEffect.catchTags({\n\t\t\t\t\tToolShellTimeout: (timeout) =>\n\t\t\t\t\t\tEffect.fail(\n\t\t\t\t\t\t\tnew BashTimedOut({ timeoutSeconds: timeout.timeoutMillis / 1000, output: \"\", truncated: false }),\n\t\t\t\t\t\t),\n\t\t\t\t\tToolShellError: (cause) => Effect.die(cause),\n\t\t\t\t}),\n\t\t\t);\n\n\t\tconst present = yield* presentBuffered(combineOutput(result.stdout, result.stderr));\n\t\tif (result.exitCode !== 0) {\n\t\t\treturn yield* new BashFailed({ exitCode: result.exitCode, ...present });\n\t\t}\n\t\treturn { exitCode: result.exitCode, ...present } satisfies typeof BashSuccess.Type;\n\t});\n\n/** Variant B — streaming: accumulate output, report progress, keep partial output on timeout. */\nconst runStreaming = (\n\tstream: NonNullable<IToolShell[\"stream\"]>,\n\tparams: typeof BashParams.Type,\n): Effect.Effect<typeof BashSuccess.Type, BashFailureError, ToolProgress> =>\n\tEffect.scoped(\n\t\tEffect.gen(function* () {\n\t\t\tconst acc = new Accumulator({ tempFilePrefix: \"codework-bash\" });\n\t\t\tconst progress = yield* ToolProgress;\n\t\t\tconst exitCode = yield* Ref.make<number | null>(null);\n\t\t\t// executes command and streams output\n\t\t\tconst consume = stream(params.command).pipe(\n\t\t\t\tStream.runForEach((event) =>\n\t\t\t\t\tevent._tag === \"Exit\"\n\t\t\t\t\t\t? Ref.set(exitCode, event.exitCode)\n\t\t\t\t\t\t: // `gen` so the snapshot is read *after* the append runs (not eagerly\n\t\t\t\t\t\t\t// at pipeline-construction time, which would lag a chunk behind).\n\t\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\t\tyield* acc.append(Buffer.from(event.bytes));\n\t\t\t\t\t\t\t\tyield* progress.report({ content: [{ type: \"text\", text: acc.snapshot().content }] });\n\t\t\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\t// Infra/spawn failure → defect (run error), like variant A.\n\t\t\t\tEffect.catchTag(\"ToolShellError\", (cause) => Effect.die(cause)),\n\t\t\t);\n\n\t\t\t// Consume with the deadline; on timeout the accumulator keeps what arrived.\n\t\t\tlet timedOutAfter: number | undefined;\n\t\t\tif (params.timeout !== undefined) {\n\t\t\t\tconst finished = yield* consume.pipe(Effect.timeoutOption(Duration.seconds(params.timeout)));\n\t\t\t\tif (Option.isNone(finished)) timedOutAfter = params.timeout;\n\t\t\t} else {\n\t\t\t\tyield* consume;\n\t\t\t}\n\n\t\t\tyield* acc.finish();\n\t\t\tconst present = presentSnapshot(acc.snapshot(), acc.getLastLineBytes());\n\n\t\t\tif (timedOutAfter !== undefined) {\n\t\t\t\treturn yield* new BashTimedOut({ timeoutSeconds: timedOutAfter, ...present });\n\t\t\t}\n\t\t\tconst code = yield* Ref.get(exitCode);\n\t\t\t// No Exit event (e.g. killed before reporting one) → treat as a failure.\n\t\t\tif (code === null || code !== 0) {\n\t\t\t\treturn yield* new BashFailed({ exitCode: code ?? -1, ...present });\n\t\t\t}\n\t\t\treturn { exitCode: code, ...present } satisfies typeof BashSuccess.Type;\n\t\t}),\n\t);\n\nexport const bashHandler: Tool.Handler<\n\ttypeof BashParams,\n\ttypeof BashSuccess,\n\ttypeof BashFailure,\n\tToolShell | ToolProgress\n> = (params) =>\n\tEffect.gen(function* () {\n\t\tconst shell = yield* ToolShell;\n\t\t// Prefer streaming when the backend supports it; fall back to buffered exec.\n\t\treturn shell.stream !== undefined ? yield* runStreaming(shell.stream, params) : yield* runBuffered(shell, params);\n\t});\n\n/** The bash tool: definition + handler, wired the testable (def/exec split) way. */\nexport const bashTool = Tool.implement(bashDef, bashHandler);\n\nexport const bashPlugin = define({\n\tid: \"codework.tool.bash\",\n\tsetup: Effect.fn(\"BashPlugin.setup\")(function* (ctx) {\n\t\tconst shell = yield* SandboxIO.Shell;\n\t\tconst mounted = fromSandboxShell.pipe(Layer.provide(Layer.succeed(SandboxIO.Shell, shell)));\n\t\tctx.plugin.tools.add(Tool.provide(bashTool, mounted));\n\t}),\n});\n","import { defaultPromptPlugin } from \"./builtin/prompt/default.ts\";\nimport { bashPlugin } from \"./builtin/tool/bash.ts\";\n\n/**\n * Every plugin the harness ships, and the selection a caller who passes no `plugins` gets. Tool\n * contributors come first so the Prompt plugin that indexes them runs after they registered.\n */\nexport const builtins = Object.freeze([bashPlugin, defaultPromptPlugin]);\n","/*\n * @file Coordinator provides the execution process manager (fibers).\n * Handles process concurrency and coordination for the provided drain function.\n */\nimport { Deferred, Effect, Exit, Fiber, FiberSet, Scope } from \"effect\";\n\n/** Serializes execution for each key while allowing different keys to run concurrently. */\nexport interface Coordinator<Key, E, Reason = never> {\n\t/** Snapshots keys with an execution owned by this coordinator. */\n\treadonly active: Effect.Effect<ReadonlySet<Key>>;\n\t/** Starts an execution while idle, or joins the active execution and returns its exit. */\n\treadonly run: (key: Key) => Effect.Effect<void, E>;\n\t/** Rings the doorbell so newly recorded work is drained without waiting for it. */\n\treadonly wake: (key: Key) => Effect.Effect<void>;\n\t/**\n\t * Accepts interruption of active work. Resolves once the interruption is\n\t * accepted, not when cleanup settles; returns whether an active execution was\n\t * interrupted. `awaitSettlement` waits for this execution's cleanup and\n\t * settled hook only -- `awaitIdle` follows successors admitted during it.\n\t */\n\treadonly interrupt: (\n\t\tkey: Key,\n\t\treason?: Reason,\n\t\toptions?: { readonly awaitSettlement?: boolean },\n\t) => Effect.Effect<boolean>;\n\t/** Resolves once no execution is active for the key, successors included. Never starts work. */\n\treadonly awaitIdle: (key: Key) => Effect.Effect<void>;\n}\n\n/** One process-local busy period for a key. */\ntype Execution<E, Reason> = {\n\t// Completion is always successful; joiners explicitly replay the drain's exit.\n\t// Idle observers must not inherit its interruption while waiting in a finalizer.\n\treadonly done: Deferred.Deferred<Exit.Exit<void, E>>;\n\towner?: Fiber.Fiber<void>;\n\tpendingWake: boolean;\n\tstopping: boolean;\n\tinterruptionReason?: Reason;\n};\n\nexport const make = <Key, E, Reason = never>(options: {\n\t/** Actual work serialized by the coordinator. */\n\treadonly drain: (key: Key, force: boolean) => Effect.Effect<void, E>;\n\t/** Runs once when a busy period begins, before its first drain. */\n\treadonly started?: (key: Key) => Effect.Effect<void>;\n\t/** Runs after the final drain exits and before joiners are released. */\n\treadonly settled?: (key: Key, exit: Exit.Exit<void, E>, reason?: Reason) => Effect.Effect<void>;\n}): Effect.Effect<Coordinator<Key, E, Reason>, never, Scope.Scope> =>\n\tEffect.gen(function* () {\n\t\tconst executions = new Map<Key, Execution<E, Reason>>();\n\t\tconst fork = yield* FiberSet.makeRuntime<never, void, never>();\n\n\t\tconst loop = (key: Key, execution: Execution<E, Reason>, force: boolean): Effect.Effect<void, E> =>\n\t\t\tEffect.suspend(() => options.drain(key, force)).pipe(\n\t\t\t\tEffect.andThen(\n\t\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\t\tif (execution.stopping || !execution.pendingWake) return Effect.void;\n\t\t\t\t\t\texecution.pendingWake = false;\n\t\t\t\t\t\t// Trampoline so drains that complete synchronously cannot grow the stack.\n\t\t\t\t\t\treturn Effect.yieldNow.pipe(Effect.andThen(loop(key, execution, false)));\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\n\t\tconst start = (key: Key, force: boolean) => {\n\t\t\tconst execution: Execution<E, Reason> = {\n\t\t\t\tdone: Deferred.makeUnsafe<Exit.Exit<void, E>>(),\n\t\t\t\tpendingWake: false,\n\t\t\t\tstopping: false,\n\t\t\t};\n\t\t\texecutions.set(key, execution);\n\t\t\t// The leading yield lets `owner` be assigned before the drain can settle and\n\t\t\t// trampolines successor executions after synchronous failures.\n\t\t\texecution.owner = fork(\n\t\t\t\tEffect.yieldNow.pipe(\n\t\t\t\t\tEffect.andThen(Effect.uninterruptible(options.started?.(key) ?? Effect.void)),\n\t\t\t\t\tEffect.andThen(loop(key, execution, force)),\n\t\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\tdelete execution.owner;\n\t\t\t\t\t\t}).pipe(Effect.andThen(options.settled?.(key, exit, execution.interruptionReason) ?? Effect.void)),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.onExit((exit) => Effect.sync(() => settle(key, execution, exit))),\n\t\t\t\t\tEffect.exit,\n\t\t\t\t\tEffect.asVoid,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn execution;\n\t\t};\n\n\t\t// A wake that survives the loop or arrives during cleanup starts a fresh busy period.\n\t\tconst settle = (key: Key, execution: Execution<E, Reason>, exit: Exit.Exit<void, E>) => {\n\t\t\tif (execution.pendingWake) start(key, false);\n\t\t\telse executions.delete(key);\n\t\t\tDeferred.doneUnsafe(execution.done, Exit.succeed(exit));\n\t\t};\n\n\t\tconst run = (key: Key): Effect.Effect<void, E> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\tif (execution !== undefined) {\n\t\t\t\t\tif (execution.stopping) {\n\t\t\t\t\t\treturn Deferred.await(execution.done).pipe(Effect.andThen(run(key)));\n\t\t\t\t\t}\n\t\t\t\t\treturn Deferred.await(execution.done).pipe(Effect.flatMap((exit) => exit));\n\t\t\t\t}\n\t\t\t\treturn Deferred.await(start(key, true).done).pipe(Effect.flatMap((exit) => exit));\n\t\t\t});\n\n\t\tconst wake = (key: Key) =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\tif (execution !== undefined) {\n\t\t\t\t\texecution.pendingWake = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstart(key, false);\n\t\t\t});\n\n\t\tconst requestInterrupt = (key: Key, reason?: Reason): Effect.Effect<boolean> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\tif (execution === undefined || execution.stopping) return Effect.succeed(false);\n\t\t\t\tif (execution.owner === undefined) {\n\t\t\t\t\t// The terminal exit is already decided. Claim earlier wakes so settlement\n\t\t\t\t\t// does not restart work for the interrupted intent.\n\t\t\t\t\texecution.pendingWake = false;\n\t\t\t\t\treturn Effect.succeed(false);\n\t\t\t\t}\n\t\t\t\texecution.stopping = true;\n\t\t\t\texecution.pendingWake = false;\n\t\t\t\tif (reason !== undefined) execution.interruptionReason = reason;\n\t\t\t\tfork(Fiber.interrupt(execution.owner));\n\t\t\t\treturn Effect.succeed(true);\n\t\t\t});\n\n\t\tconst interrupt = (\n\t\t\tkey: Key,\n\t\t\treason?: Reason,\n\t\t\toptions?: { readonly awaitSettlement?: boolean },\n\t\t): Effect.Effect<boolean> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\t// Capture before requesting the interrupt: an execution already stopping\n\t\t\t\t// or inside its settled hook still has cleanup a caller may need to join.\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\treturn requestInterrupt(key, reason).pipe(\n\t\t\t\t\tEffect.tap(() =>\n\t\t\t\t\t\toptions?.awaitSettlement === true && execution !== undefined\n\t\t\t\t\t\t\t? Deferred.await(execution.done).pipe(Effect.ignoreCause)\n\t\t\t\t\t\t\t: Effect.void,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t});\n\n\t\tconst awaitIdle = (key: Key): Effect.Effect<void> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\tif (execution === undefined) return Effect.void;\n\t\t\t\treturn Deferred.await(execution.done).pipe(Effect.andThen(awaitIdle(key)));\n\t\t\t});\n\n\t\treturn { active: Effect.sync(() => new Set(executions.keys())), run, wake, interrupt, awaitIdle };\n\t});\n\nexport * as RunCoordinator from \"./coordinator.ts\";\n","/*\n * @file Implements execution contract service.\n * Connects the process coordinator to the durable input/output loop.\n */\n\nimport { Cause, Context, DateTime, Effect, Exit, Layer, Option } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { Location } from \"../location/location.ts\";\nimport { SandboxController } from \"../sandbox/control.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { RunCoordinator } from \"./coordinator.ts\";\nimport { RunnerExecution } from \"./execution.ts\";\nimport { Runner } from \"./run.ts\";\n\n// session\nimport { SessionFailure } from \"../session/failure.ts\";\nimport type { ID as SessionId } from \"../session/schema.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { Session } from \"../session/session.ts\";\n\nexport const layer = Layer.effect(\n\tRunnerExecution.Service,\n\tEffect.gen(function* () {\n\t\tconst store = yield* Session.Service;\n\t\tconst sandbox = yield* SandboxController.Controller;\n\t\tconst sql = yield* SqlClient.SqlClient;\n\t\t// Captured here, not requested inside `drain`: `RunCoordinator.make`\n\t\t// requires the drain's `R` channel to be `never`, and a `Runner.Service.use`\n\t\t// in the callback would leave the tag in it.\n\t\tconst runner = yield* Runner.Service;\n\t\tconst events = yield* Event.Service;\n\t\t// A lifecycle publish that fails is reported, never thrown back into the\n\t\t// coordinator: losing the observation must not change how the drain ends.\n\t\tconst reportLifecycle = (sessionId: SessionId, publish: Effect.Effect<unknown>) =>\n\t\t\tpublish.pipe(\n\t\t\t\tEffect.tapCause((cause) =>\n\t\t\t\t\tCause.hasInterruptsOnly(cause)\n\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t: Effect.logError(\"Failed to publish session execution lifecycle\", cause).pipe(\n\t\t\t\t\t\t\t\tEffect.annotateLogs({ sessionId }),\n\t\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\tEffect.ignore,\n\t\t\t);\n\n\t\tconst coordinator = yield* RunCoordinator.make<SessionId, Runner.RunError, SessionSchema.InterruptReason>({\n\t\t\tstarted: (sessionId) =>\n\t\t\t\treportLifecycle(\n\t\t\t\t\tsessionId,\n\t\t\t\t\tDateTime.now.pipe(\n\t\t\t\t\t\tEffect.andThen((timestamp) => events.publish(EventList.ExecutionStarted, { sessionId, timestamp })),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t// One terminal per busy period, covering every drain it coalesced.\n\t\t\tsettled: (sessionId, exit, reason) =>\n\t\t\t\treportLifecycle(\n\t\t\t\t\tsessionId,\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst timestamp = yield* DateTime.now;\n\t\t\t\t\t\tif (Exit.isSuccess(exit))\n\t\t\t\t\t\t\treturn yield* events.publish(EventList.ExecutionSucceeded, { sessionId, timestamp });\n\t\t\t\t\t\tif (Cause.hasInterruptsOnly(exit.cause))\n\t\t\t\t\t\t\t// Nobody named a reason, so the process took the decision itself.\n\t\t\t\t\t\t\treturn yield* events.publish(EventList.ExecutionInterrupted, {\n\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\t\treason: reason ?? \"shutdown\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\treturn yield* events.publish(EventList.ExecutionFailed, {\n\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\terror: SessionFailure.fromCause(Cause.squash(exit.cause)),\n\t\t\t\t\t\t});\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\tdrain: Effect.fnUntraced(function* (sessionId: SessionId, force) {\n\t\t\t\tconst session = yield* store.get(sessionId);\n\t\t\t\tif (Option.isNone(session)) return yield* new Session.SessionNotFoundError({ sessionId });\n\t\t\t\tconst space = yield* store.space(sessionId);\n\t\t\t\t// Unreachable while the FK holds; typed so a UI can offer relink\n\t\t\t\t// as the repair instead of surfacing a defect.\n\t\t\t\tif (Option.isNone(space)) return yield* new Session.SessionLinkedSpaceNotFoundError({ sessionId });\n\t\t\t\t// The session's env is derived through its space; its cwd is its own (D-SESSION).\n\t\t\t\tconst instanceId = space.value.env;\n\t\t\t\tconst mount = sandbox.mount(instanceId, { cwd: session.value.directory });\n\n\t\t\t\tconst scopedRun = Effect.gen(function* () {\n\t\t\t\t\tconst mountContext = yield* Layer.build(mount);\n\t\t\t\t\tconst current = Context.get(mountContext, SandboxIO.Current);\n\t\t\t\t\tconst fs = Context.get(mountContext, SandboxIO.FileSystem);\n\t\t\t\t\tif (!(yield* fs.exists(current.cwd))) {\n\t\t\t\t\t\treturn yield* new Runner.SandboxDirectoryNotFoundError({\n\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\tsandboxInstanceId: instanceId,\n\t\t\t\t\t\t\tdirectory: current.cwd,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst location = Location.layerMounted().pipe(\n\t\t\t\t\t\tLayer.provide(Layer.succeedContext(mountContext)),\n\t\t\t\t\t\tLayer.provide(Layer.succeed(SqlClient.SqlClient, sql)),\n\t\t\t\t\t);\n\t\t\t\t\tconst locationContext = yield* Layer.build(location).pipe(\n\t\t\t\t\t\tEffect.catchTag(\n\t\t\t\t\t\t\t[\"Location.DirectoryNotFoundError\", \"Location.NotDirectoryError\"],\n\t\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\t\tnew Runner.SandboxDirectoryNotFoundError({\n\t\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\t\tsandboxInstanceId: error.sandboxInstanceId,\n\t\t\t\t\t\t\t\t\tdirectory: error.directory,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\n\t\t\t\t\treturn yield* runner\n\t\t\t\t\t\t.run({ sessionId, force })\n\t\t\t\t\t\t.pipe(Effect.provideContext(Context.merge(locationContext, mountContext)));\n\t\t\t\t});\n\n\t\t\t\treturn yield* scopedRun.pipe(\n\t\t\t\t\tEffect.scoped,\n\t\t\t\t\tEffect.tapCause((cause) =>\n\t\t\t\t\t\tCause.hasDies(cause)\n\t\t\t\t\t\t\t? Effect.logError(\"defect\", cause).pipe(Effect.annotateLogs({ sessionId }))\n\t\t\t\t\t\t\t: Effect.void,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}),\n\t\t});\n\n\t\treturn RunnerExecution.Service.of({\n\t\t\tactive: coordinator.active,\n\t\t\tinterrupt: coordinator.interrupt,\n\t\t\tresume: coordinator.run,\n\t\t\twake: coordinator.wake,\n\t\t\tawaitIdle: coordinator.awaitIdle,\n\t\t});\n\t}),\n);\n\nexport * as RunnerExecute from \"./execute.ts\";\n","/*\n * @file Translates one aikit provider stream into Harness events.\n *\n * Request-scoped by construction: `make` is an Effect, not a `Layer` or a\n * `Context.Service`. Those are graph-lifetime, so a service here would share one\n * request's latches with every other request on the process. Every\n * `yield* make(...)` allocates its own.\n *\n * The LLM boundary sequences the stream and hands each event over; this\n * module decides what the event means. It writes nothing itself -- durable\n * lifecycle events reach `session_entry` through the projectors in\n * `session/projector.ts`.\n *\n * There are no fragment buffers here, which is the main structural difference\n * from the reference implementation this file is named after. Its provider\n * events carry only fragments, so it has to reassemble text across deltas before\n * it can persist a block. Every aikit event already carries a complete assistant\n * message, and the terminal one carries the whole response. Successful output\n * can therefore replace the draft in one write; failed output becomes a\n * partless tombstone without needing a fragment buffer.\n */\n\nimport type { Event as AikitEvent, Message } from \"@codeworksh/aikit\";\nimport { DateTime, Effect } from \"effect\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { SessionMessageSchema } from \"../session/message/schema.ts\";\nimport type { SessionSchema } from \"../session/schema.ts\";\nimport { Runner } from \"./run.ts\";\n\n/** How the response settled. The loop branches on this, never on `result()`. */\nexport type Terminal =\n\t| {\n\t\t\treadonly outcome: \"ended\";\n\t\t\treadonly reason: \"stop\" | \"length\" | \"toolUse\";\n\t\t\treadonly message: Message.AssistantMessage;\n\t }\n\t| {\n\t\t\treadonly outcome: \"failed\";\n\t\t\treadonly reason: \"aborted\" | \"error\";\n\t\t\treadonly message: Message.AssistantMessage;\n\t };\n\nexport interface Publisher {\n\t/** Set only after LLMStarted committed its draft row. */\n\treadonly startedMessageId: SessionMessageSchema.ID | undefined;\n\t/** Interpret one provider event. Durable ones commit before this returns. */\n\treadonly publish: (event: AikitEvent.LLMMessageEvent) => Effect.Effect<void, Runner.LLMStreamError>;\n\t/** How the response settled; fails if the stream ended without terminating. */\n\treadonly terminal: Effect.Effect<Terminal, Runner.LLMStreamError>;\n}\n\nexport const make = Effect.fn(\"LLMEventPublisher.make\")(function* (input: { readonly sessionId: SessionSchema.ID }) {\n\tconst events = yield* Event.Service;\n\n\tlet messageId: SessionMessageSchema.ID | undefined;\n\tlet startedMessageId: SessionMessageSchema.ID | undefined;\n\tlet settled: Terminal | undefined;\n\tconst clone = (message: Message.AssistantMessage): Message.AssistantMessage => structuredClone(message);\n\n\tconst fault = (reason: string) => new Runner.LLMStreamError({ sessionId: input.sessionId, reason });\n\n\t/**\n\t * Every event names the message it belongs to. The first one to arrive fixes\n\t * the identity for the whole response; a later disagreement means two\n\t * responses are interleaving on one stream, which would silently file half of\n\t * one under the other.\n\t *\n\t * Reading `messageId` off `partial` is safe even though `partial` itself is\n\t * not: aikit mutates that object in place as the stream advances, but the id\n\t * is fixed when the message is created and never moves.\n\t */\n\tconst identify = (observed: string) =>\n\t\tEffect.suspend(() => {\n\t\t\tconst id = SessionMessageSchema.ID.from(observed);\n\t\t\tif (messageId === undefined) {\n\t\t\t\tmessageId = id;\n\t\t\t\treturn Effect.succeed(id);\n\t\t\t}\n\t\t\treturn messageId === id\n\t\t\t\t? Effect.succeed(messageId)\n\t\t\t\t: Effect.fail(fault(`message id changed mid-response: \"${messageId}\" then \"${id}\"`));\n\t\t});\n\n\tconst publish = (event: AikitEvent.LLMMessageEvent): Effect.Effect<void, Runner.LLMStreamError> =>\n\t\tEffect.gen(function* () {\n\t\t\t// Exactly one terminal per response. A second, or anything after one,\n\t\t\t// would append a second assistant entry for the same request.\n\t\t\tif (settled !== undefined) {\n\t\t\t\treturn yield* fault(`received \"${event.type}\" after the response had already terminated`);\n\t\t\t}\n\t\t\tconst timestamp = yield* DateTime.now;\n\t\t\tconst base = { sessionId: input.sessionId, timestamp };\n\n\t\t\tswitch (event.type) {\n\t\t\t\tcase \"start\": {\n\t\t\t\t\tif (startedMessageId !== undefined) return yield* fault(\"received a second start event\");\n\t\t\t\t\tconst message = clone(event.partial);\n\t\t\t\t\tconst identified = yield* identify(message.messageId);\n\t\t\t\t\tyield* Effect.uninterruptible(\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tyield* events.publish(EventList.LLMStarted, {\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\tmessageId: identified,\n\t\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tstartedMessageId = identified;\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Live only, all of them. The terminal message contains every finished\n\t\t\t\t * block, so persisting these would write the same text twice and, worse,\n\t\t\t\t * leave an entry that a crash could strand mid-response -- which\n\t\t\t\t * `Context.assemble` would then replay to the model as a complete turn.\n\t\t\t\t *\n\t\t\t\t * Only scalars computed at push time are carried. `partial` is excluded\n\t\t\t\t * deliberately: it is one object aikit rewrites in place and pushes by\n\t\t\t\t * reference into a queue, so by the time this consumer reads a queued\n\t\t\t\t * event the value has already moved on.\n\t\t\t\t */\n\t\t\t\tcase \"text.start\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMTextStart, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"text.delta\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMTextDelta, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"text.end\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMTextEnd, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t\tcontent: event.content,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"thinking.start\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMThinkingStart, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"thinking.delta\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMThinkingDelta, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcase \"thinking.end\": {\n\t\t\t\t\tyield* events.publish(EventList.LLMThinkingEnd, {\n\t\t\t\t\t\t...base,\n\t\t\t\t\t\tmessageId: yield* identify(event.partial.messageId),\n\t\t\t\t\t\tpartIndex: event.partIndex,\n\t\t\t\t\t\tcontent: event.content,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * Tool stream fragments stay live-only. The authoritative pending calls\n\t\t\t\t * arrive in the terminal assistant and are persisted by LLMEnded.\n\t\t\t\t */\n\t\t\t\tcase \"toolcall.start\":\n\t\t\t\tcase \"toolcall.delta\":\n\t\t\t\tcase \"toolcall.end\":\n\t\t\t\tcase \"toolcall.final\": {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcase \"done\": {\n\t\t\t\t\tif (startedMessageId === undefined) return yield* fault(\"received done before start\");\n\t\t\t\t\tconst message = clone(event.message);\n\t\t\t\t\tconst identified = yield* identify(message.messageId);\n\t\t\t\t\tyield* Effect.uninterruptible(\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tyield* events.publish(EventList.LLMEnded, {\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\tmessageId: identified,\n\t\t\t\t\t\t\t\treason: event.reason,\n\t\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t// Latched after the commit, so it records what is durable rather than\n\t\t\t\t\t\t\t// what was attempted.\n\t\t\t\t\t\t\tsettled = { outcome: \"ended\", reason: event.reason, message };\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t/*\n\t\t\t\t * aikit calls the payload `error`, but it is a complete assistant\n\t\t\t\t * message. LLMFailed uses its envelope as an aborted tombstone and the\n\t\t\t\t * projector deliberately discards every partial part.\n\t\t\t\t */\n\t\t\t\tcase \"error\": {\n\t\t\t\t\tconst message = clone(event.error);\n\t\t\t\t\tconst identified = yield* identify(message.messageId);\n\t\t\t\t\tyield* Effect.uninterruptible(\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tif (startedMessageId !== undefined) {\n\t\t\t\t\t\t\t\tyield* events.publish(EventList.LLMFailed, {\n\t\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\t\tmessageId: identified,\n\t\t\t\t\t\t\t\t\treason: event.reason,\n\t\t\t\t\t\t\t\t\tmessage,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettled = { outcome: \"failed\", reason: event.reason, message };\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tconst terminal: Effect.Effect<Terminal, Runner.LLMStreamError> = Effect.suspend(() =>\n\t\tsettled === undefined\n\t\t\t? Effect.fail(fault(\"the provider stream ended without a terminal event\"))\n\t\t\t: Effect.succeed(settled),\n\t);\n\n\treturn {\n\t\tget startedMessageId() {\n\t\t\treturn startedMessageId;\n\t\t},\n\t\tpublish,\n\t\tterminal,\n\t} satisfies Publisher;\n});\n\nexport * as LLMEventPublisher from \"./event.ts\";\n","import { Model as AikitModel, type Protocol } from \"@codeworksh/aikit\";\nimport { Schema } from \"effect\";\n\nexport const ThinkingLevel = Schema.Literals(Object.values(AikitModel.ThinkingLevelEnum));\nexport const ToolExecution = Schema.Literals([\"sequential\", \"parallel\"]);\nexport type ToolExecution = typeof ToolExecution.Type;\nconst Budgets = Schema.Record(\n\tSchema.Literals(Object.values(AikitModel.ThinkingLevelEnum).filter((level) => level !== \"off\")),\n\tSchema.optional(Schema.Finite),\n);\n\n/** Aikit does not export its request schema; keep this routing surface checked against its public types. */\nexport const requestFields = {\n\ttemperature: Schema.optional(Schema.Finite),\n\tmaxTokens: Schema.optional(Schema.Finite),\n\tcacheRetention: Schema.optional(Schema.Literals([\"none\", \"short\", \"long\"])),\n\theaders: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\ttimeoutMs: Schema.optional(Schema.Finite),\n\tmaxRetries: Schema.optional(Schema.Finite),\n\tmetadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\tthinkingBudgets: Schema.optional(Budgets),\n\tbaseURL: Schema.optional(Schema.String),\n\tmethod: Schema.optional(Schema.Literals(Object.values(AikitModel.APIMethodEnum))),\n} satisfies Record<\n\t| Exclude<keyof Protocol.CommonOptions, \"signal\" | \"sessionId\" | \"reasoning\" | \"apiKey\" | \"onPayload\">\n\t| \"baseURL\"\n\t| \"method\",\n\tSchema.Top\n>;\n\nconst reserved = new Set([\n\t\"toolChoice\",\n\t\"activeTools\",\n\t\"provider\",\n\t\"id\",\n\t\"signal\",\n\t\"sessionId\",\n\t\"reasoning\",\n\t\"modelId\",\n\t\"apiKey\",\n\t\"onPayload\",\n\t\"api\",\n\t\"npm\",\n\t\"providerOptionsKey\",\n\t\"compat\",\n\t\"thinkingLevelMap\",\n\t\"protocol\",\n]);\n\nexport const Block = Schema.StructWithRest(\n\tSchema.Struct({\n\t\t...requestFields,\n\t\tthinkingLevel: Schema.optional(ThinkingLevel),\n\t\ttoolExecution: Schema.optional(ToolExecution),\n\t\tcontextWindow: Schema.optional(Schema.Finite),\n\t\textras: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n\t}),\n\t[Schema.Record(Schema.String, Schema.Unknown)],\n).check(\n\tSchema.makeFilter(\n\t\t(value) => Object.keys(value).every((key) => !reserved.has(key)) || \"Reserved configuration key in model options\",\n\t),\n);\nexport type Block = typeof Block.Type;\n\nexport const Model = Schema.Struct({\n\tprovider: Schema.optional(Schema.String),\n\tid: Schema.optional(Schema.String),\n\tthinkingLevel: Schema.optional(ThinkingLevel),\n\ttoolExecution: Schema.optional(ToolExecution),\n\tthinkingBudgets: Schema.optional(Budgets),\n\toptions: Schema.optional(Block),\n\tproviderOptions: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Block))),\n});\n/** A module to load: a path, a `file:` URL, or a package spec. */\nconst PluginReference = Schema.String.check(Schema.isNonEmpty());\n/**\n * Configuration for a plugin something else already selected, named by its ID (`plugin`) or by\n * the package it was installed from (`package`). It never loads anything: an entry naming a\n * plugin that is not in the selection is ignored.\n */\nconst config = {\n\tenabled: Schema.optional(Schema.Boolean),\n\toptions: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n};\nexport const PluginPatch = Schema.Union(\n\t[Schema.Struct({ plugin: PluginReference, ...config }), Schema.Struct({ package: PluginReference, ...config })],\n\t// `oneOf`, so an entry carrying both keys is a decode failure rather than one of them being\n\t// quietly dropped -- naming a plugin two ways at once says two different things.\n\t{ mode: \"oneOf\" },\n);\nexport const PluginEntry = Schema.Union([PluginReference, PluginPatch]);\nexport type PluginEntry = typeof PluginEntry.Type;\n\nexport const Patch = Schema.Struct({\n\t$schema: Schema.optional(Schema.String),\n\tplugins: Schema.optional(Schema.Array(PluginEntry)),\n\tmodel: Schema.optional(Model),\n});\nexport type Patch = typeof Patch.Type;\n\nexport interface Info {\n\t/**\n\t * Plugin references added to the harness selection, in order. Like every array in a\n\t * patch this replaces rather than concatenates, so one layer owns the whole list.\n\t */\n\treadonly plugins: ReadonlyArray<PluginEntry>;\n\treadonly model: typeof Model.Type & {\n\t\treadonly provider: string;\n\t\treadonly id: string;\n\t\treadonly thinkingLevel: AikitModel.ThinkingLevel;\n\t\treadonly toolExecution: ToolExecution;\n\t};\n}\n\n/** Let aikit supply model-aware generation defaults. */\nexport const defaults: Info = {\n\tplugins: [],\n\tmodel: {\n\t\tprovider: \"openai\",\n\t\tid: \"gpt-5.6-luna\",\n\t\tthinkingLevel: \"high\",\n\t\ttoolExecution: \"sequential\",\n\t\toptions: { timeoutMs: 3_600_000, maxRetries: 3 },\n\t},\n};\n","/*\n * @file The settings transform layer: a sparse, authored file becomes resolved values.\n *\n * `Settings.Info` is written for editing -- nested, partial, patterned, every field\n * optional. A snapshot is read at runtime -- flat and resolved. This module is the only\n * place that knows how one becomes the other, and it is deliberately pure: no services,\n * no file reads, no catalog lookup. Keep it that way and the file format stays free to\n * change without touching the loop.\n *\n * A key routes by its *name*, never by where it was written, which is what lets the same\n * key appear at global, provider, pattern, or exact-id scope. Names split four ways:\n * `contextWindow` corrects the catalog entry, request fields reach `stream()`, `extras`\n * reaches the provider constructor, and anything unrecognised falls through to the\n * per-request provider bag. That last rule is why a provider option aikit has never heard\n * of needs no registration here.\n *\n * Resolution is two-phase because the bag's key is `Model.optionsKey(model)`, which is only\n * knowable after the catalog lookup. Phase one produces the overrides that lookup needs;\n * phase two runs at the LLM boundary with the resolved model in hand.\n */\n\nimport { Model } from \"@codeworksh/aikit\";\nimport type { State } from \"../state/state.ts\";\nimport { merge } from \"./merge.ts\";\nimport { requestFields, type Block, type Info } from \"./schema.ts\";\n\nconst patternMatches = (pattern: string, id: string) =>\n\tnew RegExp(\n\t\t`^${pattern\n\t\t\t.split(\"*\")\n\t\t\t.map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n\t\t\t.join(\".*\")}$`,\n\t).test(id);\n\nexport function collect(settings: Info, provider: string, id: string): Block {\n\tconst config = settings.model;\n\tconst blocks = config.providerOptions?.[provider] ?? {};\n\tconst patterns = Object.keys(blocks)\n\t\t.filter((key) => key !== \"*\" && key !== id && key.includes(\"*\") && patternMatches(key, id))\n\t\t.sort((a, b) => a.indexOf(\"*\") - b.indexOf(\"*\"));\n\treturn merge<Block>(\n\t\t{\n\t\t\tthinkingLevel: config.thinkingLevel,\n\t\t\ttoolExecution: config.toolExecution,\n\t\t\t...(config.thinkingBudgets === undefined ? {} : { thinkingBudgets: config.thinkingBudgets }),\n\t\t},\n\t\tconfig.options,\n\t\tblocks[\"*\"],\n\t\t...patterns.map((key) => blocks[key]),\n\t\tblocks[id],\n\t);\n}\n\nexport const resolveOverrides = (block: Block): Partial<Model.Info> =>\n\tblock.contextWindow === undefined ? {} : { contextWindow: block.contextWindow };\n\n/** Protocol-independent request attributes can already be captured by State. */\nexport function resolveOptions(block: Block): State.RequestOptions {\n\tconst request = Object.fromEntries(Object.entries(block).filter(([key]) => Object.hasOwn(requestFields, key)));\n\treturn { ...request, ...(block.extras === undefined ? {} : { factoryOptions: merge({}, block.extras) }) };\n}\n\n/** The bag key becomes knowable only after lookup at the LLM boundary. */\nexport function resolveRequest(block: Block, model: Model.Info): State.RequestOptions {\n\tconst bag = Object.fromEntries(\n\t\tObject.entries(block).filter(\n\t\t\t([key]) =>\n\t\t\t\t!Object.hasOwn(requestFields, key) &&\n\t\t\t\t![\"thinkingLevel\", \"toolExecution\", \"contextWindow\", \"extras\"].includes(key),\n\t\t),\n\t);\n\treturn {\n\t\t...resolveOptions(block),\n\t\t...(Object.keys(bag).length === 0 ? {} : { providerOptions: { [Model.optionsKey(model)]: bag } }),\n\t};\n}\n\n/**\n * Harness-owned controls, which never reach a provider.\n *\n * Separate from {@link resolveRequest} because these steer the loop itself -- how hard to\n * think, how to schedule tool calls -- rather than the request body. Runtime bindings\n * outrank a matched block, which outranks the file's top level.\n */\nexport const resolveControls = (settings: Info, block: Block, runtime: State.Options) => ({\n\tthinkingLevel: runtime.thinkingLevel ?? block.thinkingLevel ?? settings.model.thinkingLevel,\n\ttoolExecution: runtime.toolExecution ?? block.toolExecution ?? settings.model.toolExecution,\n});\n\n/** Pure configuration composition. Domain selections need not exist in the catalog. */\nexport function compose(settings: Info, options: State.Options = {}, session: State.Options = {}) {\n\tconst runtime = merge(options, session);\n\tconst provider = runtime.provider ?? settings.model.provider;\n\tconst model = runtime.model ?? settings.model.id;\n\tconst block = collect(settings, provider, model);\n\treturn { provider, model, ...resolveControls(settings, block, runtime), block, runtime };\n}\n","/*\n * @file Effect boundary for one aikit LLM request.\n *\n * aikit owns provider normalization and emits an AsyncIterable of canonical LLM\n * events. This module owns the lifecycle that aikit cannot see: Effect fiber\n * interruption aborts the transport, while a scoped consumer stays alive long\n * enough to publish aikit's terminal error event durably.\n */\n\nimport { stream as aikitStream, llm, type Event as AikitEvent, type Message, type Model } from \"@codeworksh/aikit\";\nimport * as AikitFailure from \"@codeworksh/aikit/failure\";\nimport { Duration, Effect, Exit, Fiber, Scope, Stream } from \"effect\";\nimport type { SessionSchema } from \"../session/schema.ts\";\nimport type { State } from \"../state/state.ts\";\nimport { LLMEventPublisher } from \"./event.ts\";\nimport { resolveOverrides, resolveRequest } from \"../settings/resolve.ts\";\nimport { merge } from \"../settings/merge.ts\";\nimport type { Block } from \"../settings/schema.ts\";\nimport { Runner } from \"./run.ts\";\n\nexport interface Input {\n\treadonly sessionId: SessionSchema.ID;\n\treadonly context: Message.Context;\n\treadonly provider: string;\n\treadonly model: string;\n\treadonly resolvedModel: Model.Info;\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n\treadonly options?: State.RequestOptions;\n\treadonly settings?: Block;\n}\n\nexport interface RequestInput extends Input {\n\treadonly publisher: LLMEventPublisher.Publisher;\n}\n\nexport type Open = (\n\tinput: Input,\n\tsignal: AbortSignal,\n) => Effect.Effect<\n\tAsyncIterable<AikitEvent.LLMMessageEvent>,\n\tRunner.ModelCatalogError | Runner.ModelNotFoundError | Runner.ProviderError\n>;\n\nexport type Request = (\n\tinput: RequestInput,\n) => Effect.Effect<\n\tLLMEventPublisher.Terminal,\n\tRunner.ModelCatalogError | Runner.ModelNotFoundError | Runner.ProviderError | Runner.LLMStreamError\n>;\n\nexport const runtimeOptions = (input: Input, model: Model.Info, signal: AbortSignal) => {\n\tconst { activeTools, ...options } = merge(resolveRequest(input.settings ?? {}, model), input.options);\n\treturn {\n\t\t...options,\n\t\t...(activeTools === undefined ? {} : { activeTools: [...activeTools] }),\n\t\t...(input.thinkingLevel === undefined || input.thinkingLevel === \"off\" ? {} : { reasoning: input.thinkingLevel }),\n\t\tsessionId: input.sessionId,\n\t\tsignal,\n\t};\n};\n\nconst reasonFields = (failure: AikitFailure.Failure) => ({\n\tmessage: failure.message,\n\tisRetryable: failure.retryable,\n\t...(failure.status === undefined ? {} : { status: failure.status }),\n\t...(failure.code === undefined ? {} : { code: failure.code }),\n\t...(failure.requestId === undefined ? {} : { requestId: failure.requestId }),\n\t...(failure.retryAfterMs === undefined ? {} : { retryAfter: Duration.millis(failure.retryAfterMs) }),\n});\n\n/** Lift Aikit's JSON-safe failure data into the Effect-native Runner error channel. */\nexport const providerError = (\n\tinput: Pick<Input, \"provider\" | \"model\">,\n\tfailure: AikitFailure.Failure,\n): Runner.ProviderError => {\n\tconst fields = reasonFields(failure);\n\tconst reason: Runner.ProviderFailureReason = (() => {\n\t\tswitch (failure._tag) {\n\t\t\tcase \"Authentication\":\n\t\t\t\treturn new Runner.ProviderAuthenticationError({ authentication: failure.reason, ...fields });\n\t\t\tcase \"Configuration\":\n\t\t\t\treturn new Runner.ProviderConfigurationError(fields);\n\t\t\tcase \"Authorization\":\n\t\t\t\treturn new Runner.ProviderAuthorizationError(fields);\n\t\t\tcase \"ModelUnavailable\":\n\t\t\t\treturn new Runner.ProviderModelUnavailableError(fields);\n\t\t\tcase \"RateLimit\":\n\t\t\t\treturn new Runner.ProviderRateLimitError(fields);\n\t\t\tcase \"Quota\":\n\t\t\t\treturn new Runner.ProviderQuotaError(fields);\n\t\t\tcase \"InvalidRequest\":\n\t\t\t\treturn new Runner.ProviderInvalidRequestError(fields);\n\t\t\tcase \"ContentPolicy\":\n\t\t\t\treturn new Runner.ProviderContentPolicyError(fields);\n\t\t\tcase \"Timeout\":\n\t\t\t\treturn new Runner.ProviderTimeoutError(fields);\n\t\t\tcase \"Transport\":\n\t\t\t\treturn new Runner.ProviderTransportError(fields);\n\t\t\tcase \"Unavailable\":\n\t\t\t\treturn new Runner.ProviderUnavailableError(fields);\n\t\t\tcase \"InvalidResponse\":\n\t\t\t\treturn new Runner.ProviderInvalidResponseError(fields);\n\t\t\tcase \"Unknown\":\n\t\t\t\treturn new Runner.ProviderUnknownError(fields);\n\t\t}\n\t})();\n\treturn new Runner.ProviderError({ provider: input.provider, model: input.model, reason });\n};\n\nconst providerErrorFromUnknown = (input: Pick<Input, \"provider\" | \"model\">, cause: unknown) =>\n\tproviderError(input, AikitFailure.normalize(cause));\n\nconst modelCatalogFailure = (\n\tcause: unknown,\n):\n\t| {\n\t\t\treadonly path: string;\n\t\t\treadonly reason: \"missing\" | \"unreadable\" | \"empty\" | \"invalid\";\n\t\t\treadonly message: string;\n\t }\n\t| undefined => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"name\" in cause) || cause.name !== \"ModelCatalogLoadError\") {\n\t\treturn undefined;\n\t}\n\tif (!(\"data\" in cause) || typeof cause.data !== \"object\" || cause.data === null) return undefined;\n\tconst data = cause.data;\n\tif (\n\t\t!(\"path\" in data) ||\n\t\ttypeof data.path !== \"string\" ||\n\t\t!(\"message\" in data) ||\n\t\ttypeof data.message !== \"string\" ||\n\t\t!(\"reason\" in data) ||\n\t\t(data.reason !== \"missing\" &&\n\t\t\tdata.reason !== \"unreadable\" &&\n\t\t\tdata.reason !== \"empty\" &&\n\t\t\tdata.reason !== \"invalid\")\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { path: data.path, reason: data.reason, message: data.message };\n};\n\n/** Read structured terminal data while remaining compatible with older Aikit messages. */\nexport const messageFailure = (message: Message.AssistantMessage): AikitFailure.Failure => {\n\tconst candidate = (message as Message.AssistantMessage & { readonly failure?: unknown }).failure;\n\treturn AikitFailure.isFailure(candidate)\n\t\t? candidate\n\t\t: AikitFailure.fromMessage(message.errorMessage ?? \"The provider turn failed.\");\n};\n\nexport type ResolutionInput = Pick<Input, \"provider\" | \"model\" | \"settings\">;\nexport type Resolve = (\n\tinput: ResolutionInput,\n) => Effect.Effect<Model.Info, Runner.ModelCatalogError | Runner.ModelNotFoundError | Runner.ProviderError>;\n\n/** Resolve once before exchange setup; execution reuses this exact instance. */\nexport const resolve: Resolve = Effect.fn(\"LLM.resolve\")(function* (input) {\n\tconst model = yield* Effect.tryPromise({\n\t\ttry: () => llm(input.provider, input.model, resolveOverrides(input.settings ?? {})),\n\t\tcatch: (cause) => {\n\t\t\tconst catalog = modelCatalogFailure(cause);\n\t\t\treturn catalog === undefined\n\t\t\t\t? providerErrorFromUnknown(input, cause)\n\t\t\t\t: new Runner.ModelCatalogError({\n\t\t\t\t\t\tpath: catalog.path,\n\t\t\t\t\t\treason: catalog.reason,\n\t\t\t\t\t\tdetail: catalog.message,\n\t\t\t\t\t});\n\t\t},\n\t});\n\tif (model === undefined) {\n\t\treturn yield* new Runner.ModelNotFoundError({ provider: input.provider, model: input.model });\n\t}\n\n\treturn model;\n});\n\n/** Start a provider stream using the model pinned by State. */\nexport const open: Open = Effect.fn(\"LLM.open\")(function* (input, signal) {\n\tconst model = input.resolvedModel;\n\treturn yield* Effect.try({\n\t\ttry: () => aikitStream(model, input.context, runtimeOptions(input, model, signal)),\n\t\tcatch: (cause) => providerErrorFromUnknown(input, cause),\n\t});\n});\n\n/**\n * Build a provider request from an opener. Tests use this with deterministic\n * aikit event streams; production uses `open` above.\n */\nexport const make = (openStream: Open): Request => {\n\tconst request = Effect.fn(\"LLM.run\")(function* (input: RequestInput) {\n\t\t/*\n\t\t * Give the transport signal its own closeable scope. Closing it aborts the\n\t\t * signal immediately without closing this request's outer scope, which must\n\t\t * remain alive while the consumer drains and commits aikit's terminal event.\n\t\t */\n\t\tconst signalScope = yield* Scope.make();\n\t\tyield* Effect.addFinalizer((exit) => Scope.close(signalScope, exit));\n\t\tconst signal = yield* Effect.abortSignal.pipe(Scope.provide(signalScope));\n\t\tconst abort = Scope.close(signalScope, Exit.void);\n\n\t\treturn yield* Effect.uninterruptibleMask((restore) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst iterable = yield* restore(openStream(input, signal)).pipe(Effect.onInterrupt(() => abort));\n\t\t\t\tconst consume = Stream.fromAsyncIterable(iterable, (cause) => providerErrorFromUnknown(input, cause)).pipe(\n\t\t\t\t\tStream.runForEach(input.publisher.publish),\n\t\t\t\t\tEffect.andThen(input.publisher.terminal),\n\t\t\t\t\tEffect.interruptible,\n\t\t\t\t);\n\n\t\t\t\t/*\n\t\t\t\t * The consumer is deliberately a separate scoped fiber. Interrupting the\n\t\t\t\t * owning turn only interrupts its wait, not this consumer. The interrupt\n\t\t\t\t * handler aborts aikit's transport; aikit then emits its terminal `error`,\n\t\t\t\t * which the same consumer publishes before the parent rethrows the original\n\t\t\t\t * interruption. No second iterator can steal or lose that terminal event.\n\t\t\t\t */\n\t\t\t\tconst consumer = yield* consume.pipe(Effect.forkScoped({ startImmediately: true }));\n\t\t\t\tconst awaited = yield* restore(Fiber.await(consumer)).pipe(\n\t\t\t\t\tEffect.onInterrupt(() => abort),\n\t\t\t\t\tEffect.exit,\n\t\t\t\t);\n\n\t\t\t\tif (Exit.isFailure(awaited)) {\n\t\t\t\t\tconst drained = yield* Fiber.await(consumer);\n\t\t\t\t\tif (Exit.isFailure(drained)) return yield* Effect.failCause(drained.cause);\n\t\t\t\t\treturn yield* Effect.failCause(awaited.cause);\n\t\t\t\t}\n\n\t\t\t\tconst completed = awaited.value;\n\t\t\t\tif (Exit.isFailure(completed)) return yield* Effect.failCause(completed.cause);\n\t\t\t\treturn completed.value;\n\t\t\t}),\n\t\t);\n\t});\n\n\treturn (input) => request(input).pipe(Effect.scoped);\n};\n\nexport const run = make(open);\n\nexport * as LLM from \"./llm.ts\";\n","import type { Model } from \"@codeworksh/aikit\";\nimport { Effect } from \"effect\";\nimport type { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport type { Location } from \"../location/location.ts\";\nimport type { SandboxIO } from \"../sandbox/io.ts\";\nimport type { SessionSchema } from \"../session/schema.ts\";\nimport type { Info } from \"../settings/schema.ts\";\nimport type { PluginRegistry } from \"./registry.ts\";\n\nexport type PromptResolver = (ctx: SharedPluginContext) => string | Promise<string>;\nexport interface Config {\n\treadonly promptCustom?: PromptResolver;\n\treadonly promptSystemAppend?: PromptResolver;\n}\nexport interface Events {\n\treadonly publish: Event.Interface[\"publish\"];\n}\nexport interface SharedPluginContext {\n\treadonly sessionId: SessionSchema.ID;\n\treadonly sandbox: SandboxIO.Identity;\n\treadonly location: Location.Info;\n\treadonly settings: Info;\n\treadonly model: Model.Info;\n\treadonly config: Config;\n\treadonly events: Events;\n\treadonly plugin: PluginRegistry;\n}\n\n// Every kernel type, not just the durable ones: `EventRegistry.flatten` rejects\n// these at boot, and this stays as the backstop for anything that reaches\n// publish without going through registration.\nconst reserved = new Set<string>(EventList.Definitions.map((definition) => definition.type));\nexport const makeEvents = (events: Events): Events =>\n\tObject.freeze<Events>({\n\t\tpublish: (definition, data, options) =>\n\t\t\treserved.has(definition.type)\n\t\t\t\t? Effect.die(new Error(`plugins cannot publish kernel journal event: ${definition.type}`))\n\t\t\t\t: events.publish(definition, data, options),\n\t});\n","import { type Effect, Schema } from \"effect\";\nimport * as EventSchema from \"../../event/schema.ts\";\nimport { SessionMessageSchema } from \"../../session/message/schema.ts\";\nimport { SessionSchema } from \"../../session/schema.ts\";\nimport { type AnyToolDef, type ModelContent, type RegisteredTool, ToolCallContext } from \"../../tool/tool.ts\";\n\nexport const ToolBefore = Schema.Struct({\n\t...ToolCallContext.fields,\n\tsessionId: SessionSchema.ID,\n\tmessageId: SessionMessageSchema.ID,\n\tparams: Schema.Unknown,\n});\nexport type ToolBefore = typeof ToolBefore.Type;\nexport const ToolAfter = Schema.Struct({ ...ToolBefore.fields, terminal: EventSchema.AikitToolCallTerminalPart });\nexport type ToolAfter = typeof ToolAfter.Type;\nexport const ToolBeforeResult = Schema.Struct({ block: Schema.Boolean, reason: Schema.optional(Schema.String) });\nexport type ToolBeforeResult = typeof ToolBeforeResult.Type;\nexport type ToolResultContent = ModelContent;\nexport interface ToolAfterResult {\n\treadonly content?: ToolResultContent;\n\treadonly details?: unknown;\n\treadonly isError?: boolean;\n}\nexport type HookReturn<A> = A | void | Promise<A | void> | Effect.Effect<A | void, unknown>;\nexport type ToolBeforeFn = (call: ToolBefore) => HookReturn<ToolBeforeResult>;\nexport type ToolAfterFn = (call: ToolAfter) => HookReturn<ToolAfterResult>;\nexport interface ToolAddOptions {\n\treadonly beforeToolCall?: ToolBeforeFn;\n\treadonly afterToolCall?: ToolAfterFn;\n}\nexport interface ToolDefPatch {\n\treadonly description?: string;\n\treadonly label?: string;\n\treadonly promptSnippet?: string;\n\treadonly promptGuidelines?: ReadonlyArray<string>;\n}\n/**\n * One frozen bucket entry: the winning tool for a name together with the hooks that\n * `add` declared alongside it. Kept here rather than in the bucket implementation so\n * the executor shares the contract without importing plugin assembly.\n */\nexport interface ToolRegistration {\n\treadonly tool: RegisteredTool;\n\treadonly hooks: ToolAddOptions;\n}\nexport interface ToolRegistry {\n\treadonly add: (tool: RegisteredTool, options?: ToolAddOptions) => void;\n\treadonly update: (name: string, patch: ToolDefPatch) => void;\n\treadonly list: () => ReadonlyArray<AnyToolDef>;\n\treadonly get: (name: string) => AnyToolDef | undefined;\n\treadonly has: (name: string) => boolean;\n}\n","import { Cause } from \"effect\";\n\n/**\n * One line of model-facing text for a cause.\n *\n * Shared by the executor's outcome stage and the loop's outer catch so the same defect\n * reads the same either way. Never `Cause.pretty`: that joins stack traces, which would\n * put host paths and hundreds of tokens into the next request.\n */\nexport const errorMessage = <E>(cause: Cause.Cause<E>): string => {\n\tconst squashed = Cause.squash(cause);\n\tif (squashed instanceof Error && squashed.message.trim().length > 0) return squashed.message;\n\tif (typeof squashed === \"string\" && squashed.trim().length > 0) return squashed;\n\tif (typeof squashed === \"object\" && squashed !== null && \"_tag\" in squashed) return String(squashed._tag);\n\treturn \"an unknown error\";\n};\n","import {\n\tToolBeforeResult,\n\ttype HookReturn,\n\ttype ToolAfterResult,\n\ttype ToolBefore,\n\ttype ToolRegistration,\n} from \"../plugin/tool/schema.ts\";\nimport { Message } from \"@codeworksh/aikit\";\nimport {\n\tCause,\n\tDuration,\n\tEffect,\n\tExit,\n\tFiber,\n\tOption,\n\tPredicate,\n\tQueue,\n\tRef,\n\tResult,\n\tSchedule,\n\tSchema,\n\tScope,\n} from \"effect\";\nimport { isAikitToolCallTerminalPart } from \"../schema.ts\";\nimport { errorMessage } from \"../util/error.ts\";\nimport { ToolExecutionError } from \"./error.ts\";\nimport { ToolProgress, type ToolProgressPartial } from \"./progress.ts\";\nimport { type AnyToolDef, type ModelContent, type RegisteredTool, toAikitTool, type ToolCallContext } from \"./tool.ts\";\n\n/**\n * `ToolExecutor` — the uniform pipeline run for every tool call:\n *\n * resolve def → decode args → before → handler (scoped, exit) →\n * encode / normalize terminal → after → apply result patch.\n *\n * Tool handlers never touch event plumbing or aikit message shapes. The executor owns\n * the whole pending → terminal value transition. Result mapping:\n * - success → completed (content + encoded details)\n * - declared failure → error (content + encoded details), fed to the model\n * - interruption → aborted\n * - undeclared / defect → error terminal\n */\n\n/** A complete terminal tool-call part, ready for persistence and event publication. */\nexport type ToolOutcome = Message.ToolCallTerminalPart;\n\n/** One progress emission handed to an observer, including the complete running part. */\nexport interface ProgressEvent {\n\treadonly partial: ToolProgressPartial;\n\treadonly toolCall: Message.ToolCallRunningPart;\n\treadonly ctx: ToolCallContext;\n}\n\n/**\n * Per-call execution options (owned here; the registry only forwards them). Progress is\n * best-effort UI telemetry — see the `handle` progress path in {@link make}.\n */\nexport interface HandleOptions<RProgress = never, EProgress = never> {\n\treadonly sessionId?: ToolBefore[\"sessionId\"];\n\treadonly messageId?: ToolBefore[\"messageId\"];\n\t/** Sliding-queue capacity for best-effort progress. Bounded default (64); tunable. */\n\treadonly progressBuffer?: number;\n\t/**\n\t * On NORMAL completion, how long to let the sink flush the queue backlog before the scope\n\t * closes and the drain fiber stops (default 3s). Ignored on interruption — abort stays snappy.\n\t */\n\treadonly progressDrainGrace?: Duration.Input;\n\t/**\n\t * Best-effort progress observer, drained on a scoped background fiber — never in the tool\n\t * hot path. It MAY fail and MAY require services (`RProgress`): failures are logged/dropped,\n\t * and intermediate updates may be dropped under load. Not part of tool correctness.\n\t */\n\treadonly onProgress?: (event: ProgressEvent) => Effect.Effect<void, EProgress, RProgress>;\n}\n\nexport interface Executor {\n\t/** aikit wire view of the tool set, for the loop context (`convertTools`). */\n\treadonly wire: Message.Tool[];\n\t/**\n\t * Atomically transform one complete pending tool-call part into a complete terminal\n\t * part. Most failures become a terminal\n\t * `ToolOutcome`; declared failures retain their encoded details, while undeclared\n\t * failures/defects become error terminals.\n\t *\n\t * Tools enter as {@link RegisteredTool}s (capability `R` already discharged at\n\t * registration), so the only requirement left in the result is a progress sink's own\n\t * `RProgress`. `options.onProgress` observes live progress off the hot path.\n\t */\n\treadonly handle: <RProgress = never, EProgress = never>(\n\t\tcall: Message.ToolCallPendingPart,\n\t\toptions?: HandleOptions<RProgress, EProgress>,\n\t) => Effect.Effect<ToolOutcome, never, RProgress>;\n}\n\n/** Default sliding-queue capacity for best-effort progress. */\nconst DEFAULT_PROGRESS_BUFFER = 64;\n/** How long, on normal completion, to let a progress sink flush the backlog before teardown. */\nconst DEFAULT_DRAIN_GRACE: Duration.Input = Duration.seconds(3);\n/** Poll interval while waiting for the progress queue to drain. */\nconst DRAIN_POLL: Duration.Input = Duration.millis(20);\n\n// Erase a schema's services to `never` for decode/encode. Sound for tool schemas\n// (none require services) and keeps the executor's `R` clean of schema services.\nconst asCodec = (schema: AnyToolDef[\"parameters\"]): Schema.Codec<unknown, unknown> =>\n\tschema as unknown as Schema.Codec<unknown, unknown>;\n\nconst text = (value: string): Message.TextContent => ({ type: \"text\", text: value });\nconst encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));\nconst jsonText = (value: unknown): Effect.Effect<Message.TextContent> =>\n\tencodeUnknownJson(value).pipe(Effect.orDie, Effect.map(text));\n\nconst endTime = (call: Message.ToolCallPendingPart, now: number) => Math.max(call.time.end, now);\nconst result = <IsError extends boolean>(content: ModelContent, isError: IsError, details?: unknown) => ({\n\tcontent: [...content],\n\t...(details === undefined ? {} : { details }),\n\tisError,\n});\n\nconst completed = (\n\tcall: Message.ToolCallPendingPart,\n\tcontent: ModelContent,\n\tnow: number,\n\tdetails?: unknown,\n): ToolOutcome => ({\n\t...call,\n\tstatus: \"completed\",\n\tresult: result(content, false, details),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\nconst errored = (\n\tcall: Message.ToolCallPendingPart,\n\tcontent: ModelContent,\n\tnow: number,\n\tdetails?: unknown,\n): ToolOutcome => ({\n\t...call,\n\tstatus: \"error\",\n\tresult: result(content, true, details),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\nconst aborted = (\n\tcall: Message.ToolCallPendingPart,\n\tcontent: ModelContent,\n\tnow: number,\n\tdetails?: unknown,\n): ToolOutcome => ({\n\t...call,\n\tstatus: \"aborted\",\n\tresult: result(content, true, details),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\n\nconst running = (\n\tcall: Message.ToolCallPendingPart,\n\tpartial: ToolProgressPartial,\n\tnow: number,\n): Message.ToolCallRunningPart => ({\n\t...call,\n\tstatus: \"running\",\n\tpartial: {\n\t\t...(partial.content === undefined ? {} : { content: [...partial.content] }),\n\t\t...(partial.details === undefined ? {} : { details: partial.details }),\n\t},\n\ttime: { ...call.time, end: endTime(call, now) },\n});\n\nconst encodeOutcome = (\n\tdef: AnyToolDef,\n\tcall: Message.ToolCallPendingPart,\n\texit: Exit.Exit<unknown, ToolExecutionError>,\n\tlatest: Ref.Ref<Option.Option<ToolProgressPartial>>,\n): Effect.Effect<ToolOutcome> =>\n\tEffect.gen(function* () {\n\t\tif (Exit.isSuccess(exit)) {\n\t\t\tconst encoded = yield* Schema.encodeUnknownEffect(asCodec(def.success))(exit.value).pipe(Effect.orDie);\n\t\t\tconst content = def.encodeContent ? def.encodeContent(exit.value) : [yield* jsonText(encoded)];\n\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\treturn completed(call, content, now, encoded);\n\t\t}\n\n\t\tconst cause = exit.cause;\n\t\tif (Cause.hasInterrupts(cause)) {\n\t\t\t// Surface whatever the tool last reported via ToolProgress, so an aborted\n\t\t\t// streaming command still shows the output it produced before the interrupt.\n\t\t\tconst last = yield* Ref.get(latest);\n\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\tif (Option.isSome(last) && last.value.content !== undefined && last.value.content.length > 0) {\n\t\t\t\treturn aborted(call, [...last.value.content], now, last.value.details);\n\t\t\t}\n\t\t\treturn aborted(call, [text(\"Tool Call Aborted.\")], now);\n\t\t}\n\n\t\tconst executionError = Cause.findErrorOption(cause);\n\t\tif (Option.isSome(executionError)) {\n\t\t\tconst failure = executionError.value.cause;\n\t\t\tif (def.failure === undefined || !Schema.is(asCodec(def.failure))(failure)) {\n\t\t\t\treturn yield* Effect.die(failure);\n\t\t\t}\n\t\t\t// A failing finalizer alongside the declared failure is not model-facing, but losing\n\t\t\t// it entirely makes the tool look like it failed cleanly.\n\t\t\tif (Cause.hasDies(cause))\n\t\t\t\tyield* Effect.logError(\"tool finalizer defect alongside a declared failure\", Cause.pretty(cause));\n\t\t\t// Encode declared failures as model-facing tool error results.\n\t\t\tconst encoded = yield* Schema.encodeUnknownEffect(asCodec(def.failure))(failure).pipe(Effect.orDie);\n\t\t\tconst content = def.encodeFailureContent ? def.encodeFailureContent(failure) : [yield* jsonText(encoded)];\n\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\treturn errored(call, content, now, encoded);\n\t\t}\n\n\t\t// The execution boundary below normalizes undeclared failures and defects for after.\n\t\treturn yield* Effect.die(Cause.squash(cause));\n\t});\n\nclass HookExecutionError extends Schema.TaggedError<HookExecutionError>()(\"HookExecutionError\", {\n\tcause: Schema.Unknown,\n}) {}\n\n/** Invoke author callbacks only when the returned Effect runs. */\nconst invoke = <A>(callback: () => HookReturn<A>): Effect.Effect<A | void, HookExecutionError> =>\n\tEffect.suspend(() => {\n\t\tconst value = callback();\n\t\tif (Effect.isEffect(value)) {\n\t\t\tconst result: Effect.Effect<A | void, unknown> = value;\n\t\t\t// Normalize arbitrary plugin errors at the executor boundary.\n\t\t\t// @effect-diagnostics-next-line anyUnknownInErrorContext:off\n\t\t\treturn result.pipe(Effect.mapError((cause) => new HookExecutionError({ cause })));\n\t\t}\n\t\t// Any thenable: a foreign-realm or userland promise would otherwise fall through and be\n\t\t// read as the hook's own return value.\n\t\tif (Predicate.isPromiseLike(value))\n\t\t\treturn Effect.tryPromise({\n\t\t\t\ttry: () => Promise.resolve(value),\n\t\t\t\tcatch: (cause) => new HookExecutionError({ cause }),\n\t\t\t});\n\t\treturn Effect.succeed(value);\n\t});\n\nconst failureOutcome = (call: Message.ToolCallPendingPart, cause: Cause.Cause<unknown>, phase: string) =>\n\tEffect.map(\n\t\tEffect.clockWith((clock) => clock.currentTimeMillis),\n\t\t// Never `Cause.pretty` here: this text goes to the model, and it joins stack traces.\n\t\t(now) => errored(call, [text(`${phase}: ${errorMessage(cause)}`)], now),\n\t);\n\nconst patchOutcome = (terminal: ToolOutcome, patch: ToolAfterResult | void): ToolOutcome => {\n\tif (!patch || (terminal.status !== \"completed\" && terminal.status !== \"error\")) return terminal;\n\tconst isError = patch.isError ?? terminal.result.isError;\n\treturn {\n\t\t...terminal,\n\t\tstatus: isError ? \"error\" : \"completed\",\n\t\tresult: {\n\t\t\t...terminal.result,\n\t\t\t...(patch.content === undefined ? {} : { content: [...patch.content] }),\n\t\t\t...(patch.details === undefined ? {} : { details: patch.details }),\n\t\t\tisError,\n\t\t},\n\t} as ToolOutcome;\n};\n\nconst ABORT_HOOK_GRACE = Duration.seconds(1);\n\n/**\n * Build an executor over a set of {@link RegisteredTool}s — tools whose capability `R` was\n * already discharged at registration (`Tool.provide`). The executor therefore needs no tool\n * `R`; only a progress sink's `RProgress` (if any) surfaces from `handle`.\n */\nexport const make = (tools: ReadonlyArray<RegisteredTool | ToolRegistration>): Executor => {\n\tconst impls = new Map<string, ToolRegistration>();\n\tfor (const item of tools) {\n\t\tconst entry = \"tool\" in item ? item : { tool: item, hooks: {} };\n\t\tconst name = entry.tool.definition.name;\n\t\t// Fail fast: a duplicate name would expose two tools on the wire but only\n\t\t// run the last-registered handler.\n\t\tif (impls.has(name)) {\n\t\t\tthrow new Error(`Executor.make: duplicate tool name \"${name}\" — tool names must be unique.`);\n\t\t}\n\t\timpls.set(name, entry);\n\t}\n\n\tconst wire = [...impls.values()].map(({ tool }) => toAikitTool(tool.definition));\n\n\tconst handle = <RProgress = never, EProgress = never>(\n\t\tcall: Message.ToolCallPendingPart,\n\t\toptions?: HandleOptions<RProgress, EProgress>,\n\t): Effect.Effect<ToolOutcome, never, RProgress> =>\n\t\tEffect.gen(function* () {\n\t\t\tconst entry = impls.get(call.name);\n\t\t\tif (entry === undefined) {\n\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\treturn errored(call, [text(`Unknown tool: ${call.name}`)], now, {\n\t\t\t\t\terror: \"unknown_tool\",\n\t\t\t\t\tname: call.name,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst { tool: impl, hooks } = entry;\n\t\t\tconst def = impl.definition;\n\n\t\t\tconst decoded = yield* Effect.result(Schema.decodeEffect(asCodec(def.parameters))(call.arguments));\n\t\t\tif (Result.isFailure(decoded)) {\n\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\treturn errored(call, [text(`Invalid arguments for ${call.name}: ${decoded.failure.message}`)], now, {\n\t\t\t\t\terror: \"invalid_arguments\",\n\t\t\t\t\tname: call.name,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst ctx: ToolCallContext = { callID: call.callID, toolName: call.name, rawArgs: call.arguments };\n\n\t\t\tconst hasHooks = hooks.beforeToolCall !== undefined || hooks.afterToolCall !== undefined;\n\t\t\tif (hasHooks && (options?.sessionId === undefined || options.messageId === undefined)) {\n\t\t\t\treturn yield* Effect.die(new Error(\"Hooked tools require sessionId and messageId\"));\n\t\t\t}\n\t\t\tconst hookCall: ToolBefore | undefined =\n\t\t\t\toptions?.sessionId !== undefined && options.messageId !== undefined\n\t\t\t\t\t? { ...ctx, sessionId: options.sessionId, messageId: options.messageId, params: decoded.success }\n\t\t\t\t\t: undefined;\n\t\t\tif (hooks.beforeToolCall && hookCall) {\n\t\t\t\tconst before = yield* invoke(() => hooks.beforeToolCall!(hookCall)).pipe(Effect.exit);\n\t\t\t\tif (Exit.isFailure(before)) {\n\t\t\t\t\tif (Cause.hasInterrupts(before.cause))\n\t\t\t\t\t\treturn yield* Effect.failCause(before.cause as Cause.Cause<never>);\n\t\t\t\t\treturn yield* failureOutcome(call, before.cause, \"beforeToolCall failed\");\n\t\t\t\t}\n\t\t\t\t// A malformed verdict is as much a hook failure as a thrown one: silently\n\t\t\t\t// reading `.block` off arbitrary data would let `{block: \"yes\"}` block and\n\t\t\t\t// `\"denied\"` run the handler.\n\t\t\t\tif (before.value !== undefined && !Schema.is(ToolBeforeResult)(before.value)) {\n\t\t\t\t\treturn yield* failureOutcome(\n\t\t\t\t\t\tcall,\n\t\t\t\t\t\tCause.die(new Error(\"beforeToolCall returned an invalid result\")),\n\t\t\t\t\t\t\"beforeToolCall failed\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (before.value?.block) {\n\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\treturn errored(call, [text(before.value.reason || \"Tool execution was blocked\")], now);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Latest partial: captured for aborted-call output regardless of any sink.\n\t\t\tconst latest = yield* Ref.make(Option.none<ToolProgressPartial>());\n\t\t\tlet handlerStarted = false;\n\t\t\tlet afterStarted = false;\n\t\t\tconst notifyAbort = Effect.fn(\"ToolExecutor.notifyAbort\")(function* (terminal: ToolOutcome) {\n\t\t\t\tif (!handlerStarted || afterStarted || !hooks.afterToolCall || !hookCall) return;\n\t\t\t\tconst callback = hooks.afterToolCall;\n\t\t\t\t// `invoke` suspends, so the marker and the call land in one step: a scheduler\n\t\t\t\t// yield between them would let cancellation skip the hook entirely.\n\t\t\t\tconst fiber = yield* invoke(() => {\n\t\t\t\t\tafterStarted = true;\n\t\t\t\t\treturn callback({ ...hookCall, terminal });\n\t\t\t\t}).pipe(\n\t\t\t\t\tEffect.interruptible,\n\t\t\t\t\tEffect.timeout(ABORT_HOOK_GRACE),\n\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\tEffect.logWarning(\"afterToolCall abort notification failed\", Cause.pretty(cause)),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.forkChild({ startImmediately: true }),\n\t\t\t\t);\n\t\t\t\tyield* Fiber.join(fiber);\n\t\t\t});\n\t\t\tconst execute = Effect.gen(function* () {\n\t\t\t\t// True while an onProgress write is in flight, so \"drained\" means the queue is empty\n\t\t\t\t// AND the last sink write finished — not merely dequeued.\n\t\t\t\tconst activeProgress = yield* Ref.make(false);\n\n\t\t\t\tconst onProgress = options?.onProgress;\n\t\t\t\tconst progressQueue = onProgress\n\t\t\t\t\t? yield* Queue.sliding<ProgressEvent>(options?.progressBuffer ?? DEFAULT_PROGRESS_BUFFER)\n\t\t\t\t\t: undefined;\n\n\t\t\t\t// Best-effort delivery off the hot path: swallow (log-drop) sink failures, never fail the\n\t\t\t\t// tool. This is the only place onProgress runs, so its RProgress/error live here. Typed\n\t\t\t\t// explicitly so `RProgress` is pinned through `Effect.gen`'s requirement inference.\n\t\t\t\tconst forkDrain: Effect.Effect<void, never, RProgress | Scope.Scope> =\n\t\t\t\t\tprogressQueue && onProgress\n\t\t\t\t\t\t? Queue.take(progressQueue).pipe(\n\t\t\t\t\t\t\t\tEffect.flatMap((event) =>\n\t\t\t\t\t\t\t\t\tRef.set(activeProgress, true).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.andThen(onProgress(event).pipe(Effect.ignore)),\n\t\t\t\t\t\t\t\t\t\tEffect.ensuring(Ref.set(activeProgress, false)),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tEffect.forever,\n\t\t\t\t\t\t\t\tEffect.forkScoped,\n\t\t\t\t\t\t\t\tEffect.asVoid,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: Effect.void;\n\t\t\t\tyield* forkDrain;\n\n\t\t\t\t// report is fast + infallible: set latest, then a non-blocking offer (sliding drops the\n\t\t\t\t// oldest when full). No sink latency reaches the tool.\n\t\t\t\tconst report = Effect.fn(\"ToolExecutor.reportProgress\")(function* (partial: ToolProgressPartial) {\n\t\t\t\t\tyield* Ref.set(latest, Option.some(partial));\n\t\t\t\t\tif (progressQueue === undefined) return;\n\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\tyield* Queue.offer(progressQueue, { partial, toolCall: running(call, partial, now), ctx });\n\t\t\t\t});\n\t\t\t\tconst progress = ToolProgress.of({ report });\n\n\t\t\t\t// The handler keeps its OWN inner scope, so its resources release the moment it finishes\n\t\t\t\t// — not after the drain grace (which is bounded by the outer `Effect.scoped` below).\n\t\t\t\thandlerStarted = true;\n\t\t\t\tconst exit = yield* Effect.suspend(() => impl.handler(decoded.success, ctx)).pipe(\n\t\t\t\t\tEffect.scoped,\n\t\t\t\t\tEffect.provideService(ToolProgress, progress),\n\t\t\t\t\tEffect.exit,\n\t\t\t\t);\n\n\t\t\t\t// Graceful bounded drain on NORMAL completion: wait until the queue is empty AND no sink\n\t\t\t\t// write is in flight, bounded by progressDrainGrace. Skipped on interruption (snappy abort).\n\t\t\t\tconst interrupted = Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause);\n\t\t\t\tif (progressQueue && !interrupted) {\n\t\t\t\t\tconst drained = Effect.gen(function* () {\n\t\t\t\t\t\tconst size = yield* Queue.size(progressQueue);\n\t\t\t\t\t\tconst active = yield* Ref.get(activeProgress);\n\t\t\t\t\t\treturn size === 0 && !active;\n\t\t\t\t\t});\n\t\t\t\t\tyield* drained.pipe(\n\t\t\t\t\t\tEffect.repeat({ schedule: Schedule.spaced(DRAIN_POLL), until: (done) => done }),\n\t\t\t\t\t\tEffect.timeout(options?.progressDrainGrace ?? DEFAULT_DRAIN_GRACE),\n\t\t\t\t\t\tEffect.ignore,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn yield* encodeOutcome(def, call, exit, latest).pipe(\n\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\tCause.hasInterrupts(cause)\n\t\t\t\t\t\t\t? Effect.failCause(cause as Cause.Cause<never>)\n\t\t\t\t\t\t\t: failureOutcome(call, cause, \"Tool execution failed\"),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}).pipe(Effect.scoped);\n\t\t\treturn yield* execute.pipe(\n\t\t\t\tEffect.flatMap((terminal) => {\n\t\t\t\t\tif (terminal.status === \"aborted\")\n\t\t\t\t\t\treturn notifyAbort(terminal).pipe(Effect.uninterruptible, Effect.as(terminal));\n\t\t\t\t\tif (!hooks.afterToolCall || !hookCall) return Effect.succeed(terminal);\n\t\t\t\t\tconst callback = hooks.afterToolCall;\n\t\t\t\t\treturn invoke(() => {\n\t\t\t\t\t\tafterStarted = true;\n\t\t\t\t\t\treturn callback({ ...hookCall, terminal });\n\t\t\t\t\t}).pipe(\n\t\t\t\t\t\tEffect.flatMap((patch) => {\n\t\t\t\t\t\t\tconst patched = patchOutcome(terminal, patch);\n\t\t\t\t\t\t\t// A patch is arbitrary plugin data and the journal validates the part on\n\t\t\t\t\t\t\t// write. Reject it here, or one bad hook aborts the whole turn and takes\n\t\t\t\t\t\t\t// its sibling calls with it.\n\t\t\t\t\t\t\tif (isAikitToolCallTerminalPart(patched)) return Effect.succeed(patched);\n\t\t\t\t\t\t\treturn failureOutcome(\n\t\t\t\t\t\t\t\tcall,\n\t\t\t\t\t\t\t\tCause.die(new Error(\"afterToolCall returned an invalid result patch\")),\n\t\t\t\t\t\t\t\t\"afterToolCall failed\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\t\tCause.hasInterrupts(cause)\n\t\t\t\t\t\t\t\t? Effect.failCause(cause as Cause.Cause<never>)\n\t\t\t\t\t\t\t\t: failureOutcome(call, cause, \"afterToolCall failed\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tif (Exit.isSuccess(exit)) return;\n\t\t\t\t\t\t// A failing author finalizer can replace its interruption in Effect. Probe the\n\t\t\t\t\t\t// pending cancellation while cleanup coordination is protected, retaining both.\n\t\t\t\t\t\tconst pending = yield* Effect.void.pipe(Effect.interruptible, Effect.exit);\n\t\t\t\t\t\tconst cause = Exit.isFailure(pending) ? Cause.combine(exit.cause, pending.cause) : exit.cause;\n\t\t\t\t\t\tif (!Cause.hasInterrupts(cause)) return;\n\t\t\t\t\t\tyield* encodeOutcome(\n\t\t\t\t\t\t\tdef,\n\t\t\t\t\t\t\tcall,\n\t\t\t\t\t\t\tExit.failCause(cause as Cause.Cause<ToolExecutionError>),\n\t\t\t\t\t\t\tlatest,\n\t\t\t\t\t\t).pipe(Effect.flatMap(notifyAbort));\n\t\t\t\t\t\tif (!Cause.hasInterrupts(exit.cause)) return yield* Effect.failCause(cause);\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t);\n\t\t}).pipe(Effect.scoped);\n\n\treturn { wire, handle };\n};\n","import type { ToolRegistration } from \"../plugin/tool/schema.ts\";\nimport type { Message } from \"@codeworksh/aikit\";\nimport { Context, Layer } from \"effect\";\nimport * as Executor from \"./executor.ts\";\nimport type { AnyToolDef, RegisteredTool } from \"./tool.ts\";\n\n/**\n * `ToolRegistry` — the loop-facing entry point to the tool catalog\n *\n * A `Registry` is a plain immutable value (like {@link Executor}, not a service): a catalog\n * of {@link RegisteredTool}s plus a `resolve` that produces a frozen {@link Resolved}\n * snapshot. The registry **catalogs** tools and produces snapshots; it does **not** execute\n * them — execution lives on the resolved snapshot (`resolved.handle`), backed by the\n * `Executor`.\n *\n * Because a tool's capability `R` is discharged at registration (`Tool.provide` → a\n * `RegisteredTool` whose only residual requirement is the executor-provided `ToolProgress`),\n * `Registry` / `Resolved` are **non-generic** — so any number of tools (built-in or\n * third-party/plugin) compose without a shared capability union.\n */\n\n/** A frozen effective tool set: model-facing defs + the single execution entry point. */\nexport interface Resolved {\n\t/** Pure definition data (prompt index, debugging, future codemode). */\n\treadonly defs: ReadonlyArray<AnyToolDef>;\n\t/** The aikit wire view handed to the LLM request as `tools`. */\n\treadonly wire: ReadonlyArray<Message.Tool>;\n\t/**\n\t * Transform one complete pending tool-call part into a complete terminal part. The **only**\n\t * execution entry point — the\n\t * loop never runs a tool any other way. This is the executor's `handle` re-exposed; because\n\t * the catalog holds `RegisteredTool`s (capability `R` discharged), only a progress sink's own\n\t * `RProgress` surfaces in the result.\n\t */\n\treadonly handle: Executor.Executor[\"handle\"];\n}\n\n/** The catalog: an immutable set of registered tools + a resolver. A plain list of tools. */\nexport interface Registry {\n\t/** Metadata listing (name / description / …). */\n\treadonly defs: ReadonlyArray<AnyToolDef>;\n\treadonly names: ReadonlyArray<string>;\n\t/** Metadata lookup only — never exposes the executable impl. */\n\treadonly getDef: (name: string) => AnyToolDef | undefined;\n\t/** Resolve a frozen snapshot of the effective tool set. */\n\treadonly resolve: () => Resolved;\n}\n\n/**\n * Build a registry from a list of registered tools.\n *\n * Duplicate names are resolved by **last-registered-wins override**: a later registration\n * replaces the implementation bound to a name (e.g. a plugin's bash over the built-in).\n * `Map.set` updates the value in place, so `defs` / `wire` / `names` keep **first-seen**\n * order — only the bound implementation changes. Override resolution happens here, before\n * `Executor.make`, which requires unique effective names.\n */\nexport const make = (tools: ReadonlyArray<RegisteredTool | ToolRegistration>): Registry => {\n\tconst byName = new Map<string, ToolRegistration>();\n\tfor (const item of tools) {\n\t\tconst entry = \"tool\" in item ? item : { tool: item, hooks: {} };\n\t\tbyName.set(entry.tool.definition.name, entry);\n\t}\n\n\t// Capture the effective set ONCE; the snapshot closes over these frozen arrays, so it\n\t// keeps its winning implementations and membership regardless of any later change.\n\tconst effective = Object.freeze([...byName.values()]);\n\tconst defs = Object.freeze(effective.map((entry) => entry.tool.definition));\n\tconst names = Object.freeze(effective.map((entry) => entry.tool.definition.name));\n\n\t// The effective set is unique, so the executor's own duplicate guard never trips.\n\tconst executor = Executor.make(effective);\n\n\tconst resolved: Resolved = Object.freeze({\n\t\tdefs,\n\t\twire: Object.freeze([...executor.wire]),\n\t\thandle: executor.handle,\n\t});\n\n\treturn Object.freeze({\n\t\tdefs,\n\t\tnames,\n\t\tgetDef: (name: string) => byName.get(name)?.tool.definition,\n\t\tresolve: () => resolved,\n\t});\n};\n\n/**\n * `ToolRegistry` — the registry as an Effect service, for a loop assembled as a `Layer.effect`\n * that does `yield* ToolRegistry`. The service value is the non-generic {@link Registry} (tool\n * `R` is discharged at registration), so there is no capability union to fix here.\n */\nexport class ToolRegistry extends Context.Service<ToolRegistry, Registry>()(\n\t\"@codeworksh/harness/tool/registry/ToolRegistry\",\n) {}\n\n/** Provide a catalog of registered tools as the {@link ToolRegistry} service. */\nexport const layer = (tools: ReadonlyArray<RegisteredTool | ToolRegistration>): Layer.Layer<ToolRegistry> =>\n\tLayer.succeed(ToolRegistry, ToolRegistry.of(make(tools)));\n","import type { PromptRegistry } from \"./schema.ts\";\n\n/**\n * The system prompt used when no plugin set one.\n *\n * A selection with no prompt plugin is a legitimate configuration -- an embedder\n * passing `plugins: []`, or a user disabling `codework.prompt.default` before\n * their own plugin is ready -- and failing the exchange over it buys nothing the\n * assembled prompt would not already tell them. The real prompt lives in\n * `codework.prompt.default`; this is only the floor.\n */\nexport const fallback = \"You are an AI agent for CodeWork. CodeWork is the best agent harness for code & work.\";\n\nexport const make = () => {\n\tlet open = true;\n\tlet value: string | undefined;\n\tconst registry: PromptRegistry = Object.freeze({\n\t\tset: (prompt: string) => {\n\t\t\tif (!open) throw new Error(\"prompt registry is closed\");\n\t\t\tvalue = prompt;\n\t\t},\n\t\tget: () => value,\n\t});\n\treturn {\n\t\tregistry,\n\t\tclose: () => {\n\t\t\topen = false;\n\t\t},\n\t\tvalue: () => value,\n\t};\n};\n","import { Predicate, Schema } from \"effect\";\nimport type { RegisteredTool } from \"../../tool/tool.ts\";\nimport type { ToolAddOptions, ToolDefPatch, ToolRegistration, ToolRegistry } from \"./schema.ts\";\n\nconst definition = (tool: RegisteredTool): RegisteredTool => ({\n\t...tool,\n\tdefinition: Object.freeze({\n\t\t...tool.definition,\n\t\t...(tool.definition.promptGuidelines === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tpromptGuidelines: Object.freeze([...tool.definition.promptGuidelines]),\n\t\t\t\t}),\n\t}),\n});\n\n/**\n * The registration boundary for code the compiler cannot see. A plugin written in\n * plain JS can hand in anything; catching a malformed registration here keeps the\n * failure inside its `setup`, attributed to the plugin, rather than surfacing it\n * later as an unexplained freeze or mid-turn executor defect.\n */\nconst assertTool = (tool: RegisteredTool) => {\n\tconst def = Predicate.isObject(tool) ? tool.definition : undefined;\n\tif (!Predicate.isObject(def) || !Predicate.isString(def.name) || def.name.length === 0)\n\t\tthrow new Error(\"Registered tool needs a definition with a non-empty string name\");\n\tconst name = def.name;\n\tif (!Schema.isSchema(def.parameters)) throw new Error(`Tool ${name}: parameters must be an Effect Schema`);\n\tif (!Schema.isSchema(def.success)) throw new Error(`Tool ${name}: success must be an Effect Schema`);\n\tif (def.failure !== undefined && !Schema.isSchema(def.failure))\n\t\tthrow new Error(`Tool ${name}: failure must be an Effect Schema`);\n\tif (def.encodeContent !== undefined && !Predicate.isFunction(def.encodeContent))\n\t\tthrow new Error(`Tool ${name}: encodeContent must be a function`);\n\tif (def.encodeFailureContent !== undefined && !Predicate.isFunction(def.encodeFailureContent))\n\t\tthrow new Error(`Tool ${name}: encodeFailureContent must be a function`);\n\tif (!Predicate.isFunction(tool.handler)) throw new Error(`Tool ${name}: handler must be a function`);\n};\n\nconst assertHooks = (name: string, hooks: ToolAddOptions) => {\n\tif (hooks.beforeToolCall !== undefined && !Predicate.isFunction(hooks.beforeToolCall))\n\t\tthrow new Error(`Tool ${name}: beforeToolCall must be a function`);\n\tif (hooks.afterToolCall !== undefined && !Predicate.isFunction(hooks.afterToolCall))\n\t\tthrow new Error(`Tool ${name}: afterToolCall must be a function`);\n};\n\nexport const make = () => {\n\tlet open = true;\n\tconst entries = new Map<string, ToolRegistration>();\n\tconst assertOpen = () => {\n\t\tif (!open) throw new Error(\"tool registry is closed\");\n\t};\n\tconst registry: ToolRegistry = Object.freeze({\n\t\tadd: (tool: RegisteredTool, hooks: ToolAddOptions = {}) => {\n\t\t\tassertOpen();\n\t\t\tassertTool(tool);\n\t\t\tassertHooks(tool.definition.name, hooks);\n\t\t\tentries.set(\n\t\t\t\ttool.definition.name,\n\t\t\t\tObject.freeze({ tool: definition(tool), hooks: Object.freeze({ ...hooks }) }),\n\t\t\t);\n\t\t},\n\t\tupdate: (name: string, patch: ToolDefPatch) => {\n\t\t\tassertOpen();\n\t\t\tconst current = entries.get(name);\n\t\t\tif (!current) throw new Error(`Unknown tool: ${name}`);\n\t\t\tentries.set(\n\t\t\t\tname,\n\t\t\t\tObject.freeze({\n\t\t\t\t\t...current,\n\t\t\t\t\ttool: definition({\n\t\t\t\t\t\t...current.tool,\n\t\t\t\t\t\tdefinition: {\n\t\t\t\t\t\t\t...current.tool.definition,\n\t\t\t\t\t\t\t...(patch.description === undefined ? {} : { description: patch.description }),\n\t\t\t\t\t\t\t...(patch.label === undefined ? {} : { label: patch.label }),\n\t\t\t\t\t\t\t...(patch.promptSnippet === undefined ? {} : { promptSnippet: patch.promptSnippet }),\n\t\t\t\t\t\t\t...(patch.promptGuidelines === undefined ? {} : { promptGuidelines: patch.promptGuidelines }),\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tlist: () => Object.freeze([...entries.values()].map(({ tool }) => tool.definition)),\n\t\tget: (name: string) => entries.get(name)?.tool.definition,\n\t\thas: (name: string) => entries.has(name),\n\t});\n\treturn {\n\t\tregistry,\n\t\tclose: () => {\n\t\t\topen = false;\n\t\t},\n\t\tentries: () => Object.freeze([...entries.values()]),\n\t};\n};\n","import { make as makeCatalog } from \"../tool/registry.ts\";\nimport { fallback, make as makePrompt } from \"./prompt/registry.ts\";\nimport type { PromptRegistry } from \"./prompt/schema.ts\";\nimport { make as makeTools } from \"./tool/registry.ts\";\nimport type { ToolRegistry } from \"./tool/schema.ts\";\n\nexport interface PluginRegistry {\n\treadonly tools: ToolRegistry;\n\treadonly prompt: PromptRegistry;\n}\nexport const make = () => {\n\tconst tools = makeTools();\n\tconst prompt = makePrompt();\n\tconst close = () => {\n\t\ttools.close();\n\t\tprompt.close();\n\t};\n\treturn {\n\t\tregistry: Object.freeze({ tools: tools.registry, prompt: prompt.registry }),\n\t\tclose,\n\t\tfreeze: () => {\n\t\t\tclose();\n\t\t\treturn { tools: makeCatalog(tools.entries()).resolve(), systemPrompt: prompt.value() ?? fallback };\n\t\t},\n\t};\n};\n","import { Cause, Effect, Schema } from \"effect\";\nimport type { Prepared } from \"./catalog.ts\";\nimport type { SharedPluginContext } from \"./context.ts\";\nimport { make } from \"./registry.ts\";\n\nexport class SetupError extends Schema.TaggedError<SetupError>()(\"Plugin.SetupError\", {\n\tpluginId: Schema.optional(Schema.String),\n\tmessage: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\nexport const run = Effect.fn(\"PluginHost.run\")(function* (\n\tselection: ReadonlyArray<Prepared>,\n\tinput: Omit<SharedPluginContext, \"plugin\">,\n) {\n\tconst buckets = make();\n\tconst ctx = Object.freeze({ ...input, plugin: buckets.registry });\n\tconst setup = Effect.gen(function* () {\n\t\tfor (const { plugin, options } of selection) {\n\t\t\tyield* Effect.suspend(() => {\n\t\t\t\tconst result = plugin.setup(ctx, options);\n\t\t\t\tif (Effect.isEffect(result))\n\t\t\t\t\t// Plugin authors may fail with domain-specific errors; normalize them at this boundary.\n\t\t\t\t\t// @effect-diagnostics-next-line anyUnknownInErrorContext:off\n\t\t\t\t\treturn result.pipe(\n\t\t\t\t\t\tEffect.mapError(\n\t\t\t\t\t\t\t(cause) =>\n\t\t\t\t\t\t\t\tnew SetupError({ pluginId: plugin.id, message: `plugin setup failed: ${plugin.id}`, cause }),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\tif (result === undefined) return Effect.void;\n\t\t\t\treturn Effect.tryPromise({\n\t\t\t\t\ttry: () => result,\n\t\t\t\t\tcatch: (cause) =>\n\t\t\t\t\t\tnew SetupError({ pluginId: plugin.id, message: `plugin setup failed: ${plugin.id}`, cause }),\n\t\t\t\t});\n\t\t\t}).pipe(\n\t\t\t\tEffect.catchCause((cause) => {\n\t\t\t\t\tif (Cause.hasInterrupts(cause)) return Effect.failCause(cause);\n\t\t\t\t\t// Typed failures are already SetupErrors; wrap only defects (sync throws, dies)\n\t\t\t\t\t// so the original plugin error is never nested twice. `Schema.is` on a tagged\n\t\t\t\t\t// error class matches any Error carrying the same `_tag` and fields -- another\n\t\t\t\t\t// class with this tag passes, while a plain object does not, lacking the Error\n\t\t\t\t\t// prototype -- so a plugin throwing a bare `{ _tag: \"Plugin.SetupError\" }` is\n\t\t\t\t\t// wrapped and attributed here like any other defect.\n\t\t\t\t\tconst squashed = Cause.squash(cause);\n\t\t\t\t\treturn Effect.fail(\n\t\t\t\t\t\tSchema.is(SetupError)(squashed)\n\t\t\t\t\t\t\t? squashed\n\t\t\t\t\t\t\t: new SetupError({\n\t\t\t\t\t\t\t\t\tpluginId: plugin.id,\n\t\t\t\t\t\t\t\t\tmessage: `plugin setup failed: ${plugin.id}`,\n\t\t\t\t\t\t\t\t\tcause: squashed,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn yield* Effect.try({\n\t\t\ttry: buckets.freeze,\n\t\t\tcatch: (cause) =>\n\t\t\t\tnew SetupError({\n\t\t\t\t\tmessage: `plugin snapshot freeze failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t\t\tcause,\n\t\t\t\t}),\n\t\t});\n\t});\n\treturn yield* setup.pipe(Effect.ensuring(Effect.sync(buckets.close)));\n});\n","import { Context, Effect, Layer, Option, Ref } from \"effect\";\nimport type { SessionSchema } from \"./schema.ts\";\nimport type { State } from \"../state/state.ts\";\n\n/**\n * Per-session configuration, held in process.\n *\n * These bindings override file settings and the caller's `State.layer(options)` -- nothing here is written to the session log, so nothing\n * survives a restart. `Session.attach` merges into it rather than replacing it.\n */\nexport type Bindings = State.Options;\n\nexport interface Interface {\n\treadonly get: (sessionId: SessionSchema.ID) => Effect.Effect<Option.Option<Bindings>>;\n\treadonly set: (sessionId: SessionSchema.ID, bindings: Bindings) => Effect.Effect<void>;\n\treadonly update: (sessionId: SessionSchema.ID, patch: Bindings) => Effect.Effect<void>;\n\treadonly remove: (sessionId: SessionSchema.ID) => Effect.Effect<void>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/session/runtime/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst bindings = yield* Ref.make(new Map<SessionSchema.ID, Bindings>());\n\n\t\tconst get = (sessionId: SessionSchema.ID) =>\n\t\t\tRef.get(bindings).pipe(Effect.map((entries) => Option.fromUndefinedOr(entries.get(sessionId))));\n\n\t\tconst set = (sessionId: SessionSchema.ID, value: Bindings) =>\n\t\t\tRef.update(bindings, (entries) => {\n\t\t\t\tconst next = new Map(entries);\n\t\t\t\tnext.set(sessionId, value);\n\t\t\t\treturn next;\n\t\t\t});\n\n\t\tconst update = (sessionId: SessionSchema.ID, patch: Bindings) =>\n\t\t\tRef.update(bindings, (entries) => {\n\t\t\t\tconst next = new Map(entries);\n\t\t\t\tnext.set(sessionId, { ...entries.get(sessionId), ...patch });\n\t\t\t\treturn next;\n\t\t\t});\n\n\t\tconst remove = (sessionId: SessionSchema.ID) =>\n\t\t\tRef.update(bindings, (entries) => {\n\t\t\t\tconst next = new Map(entries);\n\t\t\t\tnext.delete(sessionId);\n\t\t\t\treturn next;\n\t\t\t});\n\n\t\treturn Service.of({ get, set, update, remove });\n\t}),\n);\n\nexport * as SessionRuntime from \"./runtime.ts\";\n","(function (factory) {\n if (typeof module === \"object\" && typeof module.exports === \"object\") {\n var v = factory(require, exports);\n if (v !== undefined) module.exports = v;\n }\n else if (typeof define === \"function\" && define.amd) {\n define([\"require\", \"exports\", \"./impl/format\", \"./impl/edit\", \"./impl/scanner\", \"./impl/parser\"], factory);\n }\n})(function (require, exports) {\n /*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n 'use strict';\n Object.defineProperty(exports, \"__esModule\", { value: true });\n exports.applyEdits = exports.modify = exports.format = exports.printParseErrorCode = exports.ParseErrorCode = exports.stripComments = exports.visit = exports.getNodeValue = exports.getNodePath = exports.findNodeAtOffset = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = exports.SyntaxKind = exports.ScanError = exports.createScanner = void 0;\n const formatter = require(\"./impl/format\");\n const edit = require(\"./impl/edit\");\n const scanner = require(\"./impl/scanner\");\n const parser = require(\"./impl/parser\");\n /**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\n exports.createScanner = scanner.createScanner;\n var ScanError;\n (function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n })(ScanError || (exports.ScanError = ScanError = {}));\n var SyntaxKind;\n (function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n })(SyntaxKind || (exports.SyntaxKind = SyntaxKind = {}));\n /**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\n exports.getLocation = parser.getLocation;\n /**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\n exports.parse = parser.parse;\n /**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\n exports.parseTree = parser.parseTree;\n /**\n * Finds the node at the given path in a JSON DOM.\n */\n exports.findNodeAtLocation = parser.findNodeAtLocation;\n /**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\n exports.findNodeAtOffset = parser.findNodeAtOffset;\n /**\n * Gets the JSON path of the given JSON DOM node\n */\n exports.getNodePath = parser.getNodePath;\n /**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\n exports.getNodeValue = parser.getNodeValue;\n /**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\n exports.visit = parser.visit;\n /**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\n exports.stripComments = parser.stripComments;\n var ParseErrorCode;\n (function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n })(ParseErrorCode || (exports.ParseErrorCode = ParseErrorCode = {}));\n function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n }\n exports.printParseErrorCode = printParseErrorCode;\n /**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\n function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n }\n exports.format = format;\n /**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\n function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n }\n exports.modify = modify;\n /**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\n function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n }\n exports.applyEdits = applyEdits;\n});\n","/*\n * @file Host discovery and loading for settings files.\n *\n * Three layers are read, lowest priority first, each merged onto the built-in defaults so\n * that \"no file anywhere\" needs no special case -- zero patches over the defaults is a\n * valid result:\n *\n * 1. `<Global.home>/settings.json` -- the user's own, `~/.codework` by default\n * 2. `<options.cwd>/codework.json` or, when absent, `<options.cwd>/.codework/settings.json`\n * -- committed with the project; the single file\n * wins, it is never merged with the directory\n * 3. `<--user-config-dir>/settings.json` -- explicit override, `~` expanded, relative to cwd\n *\n * **All three are host paths.** They are resolved from the process's startup directory and\n * `Global.home`, never from a session's `--cwd`, its working directory, or its sandbox\n * mount. A session running in a remote or in-memory sandbox reads the same host files as\n * every other session in the process; there is no per-session settings discovery\n * and no parent-directory search. The startup directory arrives as `options.cwd` and is\n * resolved once, so later `cd` or a session pointed elsewhere changes nothing.\n *\n * `load` re-reads all layers on every call. There is no cache to invalidate and no reload\n * API: an edit lands at the next exchange capture because the next capture goes to disk.\n *\n * A missing file is ordinary; a file that exists and cannot be used is not. An unreadable,\n * unparseable or invalid file fails the read with the path, the reason and the offending key.\n * The alternative -- warn and skip the layer -- discards everything else that file configured,\n * so one typo in `plugins` silently moves a session onto a different model, and the only signal\n * is a log line. Failing is what gets it fixed.\n */\n\nimport { Context, Effect, Layer, Predicate, Result, Schema, SchemaIssue } from \"effect\";\nimport { type ParseError, parse as parseJsonc, printParseErrorCode } from \"jsonc-parser\";\nimport { Global } from \"../global.ts\";\nimport { fileSystem, hostPath } from \"../host.ts\";\nimport { expandTilde } from \"../util/home.ts\";\nimport { merge, normalize } from \"./merge.ts\";\nimport { defaults, Patch, type Info } from \"./schema.ts\";\n\nexport interface Options {\n\treadonly userConfigDir?: string;\n\t/**\n\t * Host startup directory, supplied by the caller -- never `process.cwd()` read\n\t * here. The distinction it protects is between the OS process's directory and a\n\t * session's sandbox mount, which are unrelated and easy to confuse; requiring it\n\t * means a caller cannot get the host layer by forgetting to say which it meant.\n\t */\n\treadonly cwd: string;\n}\n\n/**\n * Ordered layers, each a group of candidates where the first file that exists is\n * selected -- a group never contributes more than one file. The project layer's\n * candidates are `codework.json` then `.codework/settings.json`, so a project can\n * pick either layout and the single file takes precedence.\n */\nexport function paths(home: string, cwd: string, custom?: string): ReadonlyArray<ReadonlyArray<string>> {\n\tconst expanded = custom === undefined ? undefined : expandTilde(custom, hostPath);\n\treturn [\n\t\t[hostPath.join(home, \"settings.json\")],\n\t\t[hostPath.join(cwd, \"codework.json\"), hostPath.join(cwd, Global.appConfigDir, \"settings.json\")],\n\t\t...(expanded === undefined ? [] : [[hostPath.resolve(cwd, expanded, \"settings.json\")]]),\n\t];\n}\n\nexport class SettingsError extends Schema.TaggedError<SettingsError>()(\"SettingsError\", {\n\tpath: Schema.String,\n\treason: Schema.Literals([\"read\", \"parse\", \"decode\"]),\n\tdetail: Schema.String,\n}) {\n\toverride get message(): string {\n\t\treturn `${this.path}: ${this.reason}: ${this.detail}`;\n\t}\n}\n\n/** `line:column`, 1-based, for a parser offset into the source. */\nconst at = (source: string, offset: number): string => {\n\tconst before = source.slice(0, offset).split(\"\\n\");\n\treturn `${before.length}:${(before.at(-1)?.length ?? 0) + 1}`;\n};\n\nexport const parse = Effect.fn(\"Settings.parse\")(function* (path: string, source: string) {\n\t// JSONC: a settings file is written by hand, so comments and a trailing comma are part of\n\t// the format rather than mistakes. The parser reports offsets, which become `line:column`\n\t// below; Schema validates the normalized value after that.\n\tconst errors: ParseError[] = [];\n\tconst json: unknown = parseJsonc(source, errors, { allowTrailingComma: true, disallowComments: false });\n\tconst first = errors[0];\n\tif (first !== undefined) {\n\t\treturn yield* new SettingsError({\n\t\t\tpath,\n\t\t\treason: \"parse\",\n\t\t\tdetail: `${printParseErrorCode(first.error)} at ${at(source, first.offset)}`,\n\t\t});\n\t}\n\t// Normalization reads a `null` as \"absent\", which is right for a settings patch and wrong\n\t// inside a plugin's `options`: that block is opaque, and `{ \"endpoint\": null }` is a value\n\t// its plugin may need. The `plugins` array is therefore decoded exactly as written.\n\tconst document = normalize(json);\n\tif (Predicate.isObject(document) && Predicate.isObject(json) && \"plugins\" in json) {\n\t\tObject.assign(document, { plugins: json.plugins });\n\t}\n\treturn yield* Schema.decodeUnknownEffect(Patch)(document).pipe(\n\t\tEffect.mapError(\n\t\t\t(error) =>\n\t\t\t\tnew SettingsError({\n\t\t\t\t\tpath,\n\t\t\t\t\treason: \"decode\",\n\t\t\t\t\tdetail: SchemaIssue.makeFormatterStandardSchemaV1()(error.issue)\n\t\t\t\t\t\t.issues.map(\n\t\t\t\t\t\t\t(issue) =>\n\t\t\t\t\t\t\t\t`${issue.path?.map((part) => (typeof part === \"object\" ? String(part.key) : part)).join(\".\") ?? \"settings\"}: invalid value`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join(\"; \"),\n\t\t\t\t}),\n\t\t),\n\t);\n});\n\nexport interface Interface {\n\t/**\n\t * Await fresh host files at each exchange. No cache, mutation, or reload API. Fails when a\n\t * file exists and cannot be used, including on an edit made mid-session.\n\t */\n\treadonly load: Effect.Effect<Info, SettingsError>;\n}\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/settings/settings/Service\") {}\n\n/**\n * Anchor relative plugin entries to the file that declared them.\n *\n * A reference is otherwise resolved against the host startup directory, which is right for\n * a project file sitting in it and meaningless for `~/.codework/settings.json`, where\n * `./plugins/x.ts` would name a different file in every project the process is started in.\n * `file:` URLs, package specs and package names are left exactly as written, and a `plugin`\n * key is an ID rather than a location. A configuration entry's `package` is anchored like a\n * module entry, so a relative path names the same module in both spellings.\n */\nconst anchor = (patch: Patch, file: string): Patch => {\n\tif (patch.plugins === undefined) return patch;\n\tconst directory = hostPath.dirname(file);\n\tconst resolve = (reference: string) =>\n\t\treference.startsWith(\"./\") || reference.startsWith(\"../\") ? hostPath.resolve(directory, reference) : reference;\n\treturn {\n\t\t...patch,\n\t\tplugins: patch.plugins.map((entry) => {\n\t\t\tif (typeof entry === \"string\") return resolve(entry);\n\t\t\treturn \"package\" in entry ? { ...entry, package: resolve(entry.package) } : entry;\n\t\t}),\n\t};\n};\n\nconst attempt = (path: string) =>\n\tfileSystem.readFileString(path).pipe(\n\t\tEffect.mapError((error) => new SettingsError({ path, reason: \"read\", detail: error.reason._tag })),\n\t\tEffect.flatMap((source) => parse(path, source)),\n\t);\n\n/**\n * One read of every layer. Exported for the harness constructor, which needs the plugin\n * selection before any layer is built; everything else goes through `Service`.\n */\nexport const load = Effect.fn(\"Settings.load\")(function* (options: Options & { readonly home: string }) {\n\tconst files = paths(options.home, hostPath.resolve(options.cwd), options.userConfigDir);\n\tlet settings = merge(defaults);\n\t// `merge` copies through the same null-dropping walk as normalization, so the winning\n\t// layer's entries are carried outside it. Arrays replace rather than merge, so the last\n\t// layer that names `plugins` owns the list whole -- there is nothing to combine.\n\tlet plugins = defaults.plugins;\n\tfor (const group of files) {\n\t\tfor (const path of group) {\n\t\t\tconst result = yield* Effect.result(attempt(path));\n\t\t\tif (Result.isSuccess(result)) {\n\t\t\t\tconst patch = anchor(result.success, path);\n\t\t\t\tsettings = merge(settings, patch);\n\t\t\t\tif (patch.plugins !== undefined) plugins = patch.plugins;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// A missing candidate falls through to the next; anything else selects the file, and a\n\t\t\t// file this layer selected has to be usable.\n\t\t\tconst error = result.failure;\n\t\t\tif (error.reason === \"read\" && error.detail === \"NotFound\") continue;\n\t\t\treturn yield* error;\n\t\t}\n\t}\n\treturn { ...settings, plugins };\n});\n\nexport const layer = (options: Options) =>\n\tLayer.effect(\n\t\tService,\n\t\tEffect.gen(function* () {\n\t\t\tconst global = yield* Global.Service;\n\t\t\treturn Service.of({ load: load({ ...options, home: global.home }) });\n\t\t}),\n\t);\n\nexport { defaults } from \"./schema.ts\";\nexport * as Settings from \"./settings.ts\";\n","/*\n * @file Runtime state snapshot for one exchange.\n *\n * State.Snapshot answers \"what is this agent, right now\": its system prompt, its tool\n * set, and the provider options a request is built from. It is captured once per\n * exchange and pinned for every turn inside it, so a turn's continuations all\n * see the same prompt and the same tools.\n *\n * State.Snapshot should read the mount; it never acquires one. `snapshot` therefore declares\n * `SandboxIO.Provides | Location.Service` in its requirements, which makes\n * \"mount first\" a type-level fact: the method cannot be called outside a session\n * drain.\n */\n\nimport type { Model, Protocol } from \"@codeworksh/aikit\";\nimport { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport { Event } from \"../event/event.ts\";\nimport { makeEvents, type PromptResolver } from \"../plugin/context.ts\";\nimport { run as setup } from \"../plugin/host.ts\";\nimport type { Prepared } from \"../plugin/catalog.ts\";\nimport { LLM } from \"../runner/llm.ts\";\nimport type { Runner } from \"../runner/run.ts\";\nimport { Location } from \"../location/location.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { SessionRuntime } from \"../session/runtime.ts\";\nimport type { ID as SessionId } from \"../session/schema.ts\";\nimport { merge } from \"../settings/merge.ts\";\nimport { compose, resolveOptions } from \"../settings/resolve.ts\";\nimport type { Block } from \"../settings/schema.ts\";\nimport { Settings } from \"../settings/settings.ts\";\nimport type { Resolved } from \"../tool/registry.ts\";\n\n/**\n * How a turn's tool calls are scheduled once the array has been re-read.\n *\n * Pinned in the snapshot so a configuration change cannot switch scheduling\n * halfway through an exchange. State supplies the value; Loop implements it.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/**\n * Everything a caller may legally inject into aikit's\n * `stream(model, context, options)`.\n *\n * aikit's bag is generic per protocol (`Protocol.OptionsFor<TProtocol>`); this is\n * the erased form, the same move the tool registry makes when it discharges a\n * tool's capability `R`. Four fields are excluded:\n *\n * - `signal` -- `LLM.run` binds it to the scope that aborts the transport on\n * interruption. A caller value would silently break cancellation.\n * - `sessionId` -- Loop owns it.\n * - `reasoning` -- this *is* the thinking level. Exposing it alongside\n * `thinkingLevel` would be two spellings of one value, free to drift.\n * - `modelId` -- duplicates {@link Options.model}.\n *\n * Note: keep options in sync with aikit see @codeworksh/aikit\n */\nexport type RequestOptions = Omit<Protocol.CommonOptions, \"signal\" | \"sessionId\" | \"reasoning\"> & {\n\treadonly baseURL?: string;\n\treadonly method?: Model.APIMethodEnum;\n\treadonly toolChoice?: unknown;\n\treadonly activeTools?: ReadonlyArray<string>;\n\treadonly factoryOptions?: Record<string, unknown>;\n\treadonly providerOptions?: Record<string, Record<string, unknown>>;\n};\n\nexport interface Options extends RequestOptions {\n\t/** Optional caller inputs interpreted by prompt plugins. */\n\treadonly promptCustom?: string | PromptResolver;\n\treadonly promptSystemAppend?: string | PromptResolver;\n\treadonly provider?: string;\n\treadonly model?: string;\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n\treadonly toolExecution?: ToolExecutionMode;\n}\n\n/**\n * Exchange plugin setup failed.\n *\n * Typed rather than a defect: a caller's callback failing is a caller bug, but it\n * is one the session should report and survive rather than crash on. The turn\n * fails before any provider request goes out.\n */\nexport class SnapshotError extends Schema.TaggedError<SnapshotError>()(\"State.SnapshotError\", {\n\tsessionId: Schema.String,\n\treason: Schema.String,\n\tcause: Schema.Defect(),\n}) {\n\toverride get message(): string {\n\t\treturn this.reason;\n\t}\n}\n\n/**\n * Immutable runtime state for one exchange.\n *\n * `tools.handle` is executable, and that is deliberate: the definitions the model\n * is shown, the wire schemas it is given, and the handlers that run all come from\n * one resolved registry. Splitting them would let the advertised set drift from\n * the executed one.\n *\n * Not durable and not serializable. It holds no mutable refs and owns no\n * lifecycle -- the mount it reads outlives it.\n */\nexport interface Snapshot {\n\treadonly sessionId: SessionId;\n\treadonly sandbox: SandboxIO.Identity;\n\treadonly location: Location.Info;\n\treadonly systemPrompt: string;\n\treadonly tools: Resolved;\n\treadonly provider: string;\n\treadonly model: string;\n\treadonly resolvedModel: Model.Info;\n\treadonly thinkingLevel: Model.ThinkingLevel;\n\treadonly request: RequestOptions;\n\t/** Matched file attributes used to construct provider requests. */\n\treadonly settings: Block;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\nexport interface Interface {\n\t/**\n\t * Capture runtime state for one exchange. Called inside a session drain,\n\t * where the mount it reads is already open.\n\t */\n\treadonly snapshot: (\n\t\tsessionId: SessionId,\n\t) => Effect.Effect<\n\t\tSnapshot,\n\t\t| SnapshotError\n\t\t| Settings.SettingsError\n\t\t| Runner.ModelCatalogError\n\t\t| Runner.ModelNotFoundError\n\t\t| Runner.ProviderError,\n\t\tSandboxIO.Provides | Location.Service\n\t>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/state/state/Service\") {}\n\nconst resolver = (input: string | PromptResolver): PromptResolver => (typeof input === \"string\" ? () => input : input);\n\n/**\n * `selection` is the prepared, ordered list — resolved once during harness construction\n * (`plugin/catalog.ts`). State runs it as given: no insertion, reordering, or rerun, and no\n * default of its own.\n */\nexport const layer = (options: Options, selection: ReadonlyArray<Prepared>) => {\n\treturn Layer.effect(\n\t\tService,\n\t\tEffect.gen(function* () {\n\t\t\tconst runtime = yield* SessionRuntime.Service;\n\t\t\tconst settings = yield* Settings.Service;\n\t\t\tconst events = makeEvents(yield* Event.Service);\n\t\t\treturn Service.of({\n\t\t\t\tsnapshot: Effect.fn(\"State.snapshot\")(function* (sessionId: SessionId) {\n\t\t\t\t\tconst sessionOptions = Option.getOrElse(yield* runtime.get(sessionId), () => ({}));\n\t\t\t\t\t// Not wrapped: a file the user can fix is more useful to a client as a settings\n\t\t\t\t\t// failure carrying its path and key than as an anonymous snapshot failure.\n\t\t\t\t\tconst loadedSettings = yield* settings.load;\n\t\t\t\t\tconst configured = compose(loadedSettings, options, sessionOptions);\n\t\t\t\t\tconst {\n\t\t\t\t\t\tpromptCustom,\n\t\t\t\t\t\tpromptSystemAppend,\n\t\t\t\t\t\tprovider: _provider,\n\t\t\t\t\t\tmodel: _model,\n\t\t\t\t\t\tthinkingLevel: _thinkingLevel,\n\t\t\t\t\t\ttoolExecution: _toolExecution,\n\t\t\t\t\t\t...rest\n\t\t\t\t\t} = configured.runtime;\n\t\t\t\t\tconst { provider, model, thinkingLevel, toolExecution } = configured;\n\t\t\t\t\tconst request = merge(resolveOptions(configured.block), rest);\n\t\t\t\t\tconst sandbox = yield* SandboxIO.Current;\n\t\t\t\t\tconst location = yield* Location.Service;\n\n\t\t\t\t\tconst resolvedModel = yield* LLM.resolve({ provider, model, settings: configured.block });\n\t\t\t\t\tconst contributions = yield* setup(selection, {\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tlocation,\n\t\t\t\t\t\tsettings: loadedSettings,\n\t\t\t\t\t\tmodel: resolvedModel,\n\t\t\t\t\t\tevents,\n\t\t\t\t\t\tconfig: {\n\t\t\t\t\t\t\t...(promptCustom === undefined ? {} : { promptCustom: resolver(promptCustom) }),\n\t\t\t\t\t\t\t...(promptSystemAppend === undefined ? {} : { promptSystemAppend: resolver(promptSystemAppend) }),\n\t\t\t\t\t\t},\n\t\t\t\t\t}).pipe(Effect.mapError((cause) => new SnapshotError({ sessionId, reason: cause.message, cause })));\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tlocation,\n\t\t\t\t\t\t...contributions,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tresolvedModel,\n\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tsettings: configured.block,\n\t\t\t\t\t\ttoolExecution,\n\t\t\t\t\t} satisfies Snapshot;\n\t\t\t\t}),\n\t\t\t});\n\t\t}),\n\t);\n};\n\nexport * as State from \"./state.ts\";\n","/*\n * @file Durable session drain.\n *\n * The loop reads queues and projections, but every durable mutation is an\n * event. LLMStarted owns the speculative draft; TurnEnded is the only commit.\n */\n\nimport { type Message } from \"@codeworksh/aikit\";\nimport { Cause, DateTime, Effect, Exit, Layer, Option } from \"effect\";\nimport { ContextCodec } from \"../context/codec.ts\";\nimport { Context } from \"../context/context.ts\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { SessionInput } from \"../session/input/input.ts\";\nimport { SessionMessageSchema } from \"../session/message/schema.ts\";\nimport type { SessionSchema } from \"../session/schema.ts\";\nimport { Session } from \"../session/session.ts\";\nimport { State } from \"../state/state.ts\";\nimport { errorMessage } from \"../util/error.ts\";\nimport { LLMEventPublisher } from \"./event.ts\";\nimport { LLM } from \"./llm.ts\";\nimport { Runner } from \"./run.ts\";\n\nexport type Promotion = \"steer\" | \"followUp\" | undefined;\n\nexport interface TurnResult {\n\treadonly needsContinuation: boolean;\n\treadonly messageId?: string;\n}\n\nexport interface Options {\n\t/** Deterministic provider seam for tests. */\n\treadonly request?: LLM.Request;\n}\n\nconst terminalResult = (text: string) => ({\n\tcontent: [{ type: \"text\" as const, text }],\n\tisError: true as const,\n});\n\nconst endTime = (call: Message.ToolCallPendingPart, now: number) => Math.max(call.time.end, now);\n\nconst skippedPart = (call: Message.ToolCallPendingPart, message: string, now: number): Message.ToolCallSkippedPart => ({\n\t...call,\n\tstatus: \"skipped\",\n\tresult: terminalResult(message),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\n\nconst abortedPart = (call: Message.ToolCallPendingPart, now: number): Message.ToolCallAbortedPart => ({\n\t...call,\n\tstatus: \"aborted\",\n\tresult: terminalResult(\"Tool Execution Interrupted\"),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\n\nconst errorPart = (\n\tcall: Message.ToolCallPendingPart,\n\tcause: Cause.Cause<unknown>,\n\tnow: number,\n): Message.ToolCallErrorPart => ({\n\t...call,\n\tstatus: \"error\",\n\tresult: terminalResult(`tool execution failed: ${errorMessage(cause)}`),\n\ttime: { ...call.time, end: endTime(call, now) },\n});\n\nexport const layer = (options: Options = {}) =>\n\tLayer.effect(\n\t\tRunner.Service,\n\t\tEffect.gen(function* () {\n\t\t\tconst context = yield* Context.Service;\n\t\t\tconst events = yield* Event.Service;\n\t\t\tconst inputs = yield* SessionInput.make;\n\t\t\tconst sessions = yield* Session.Service;\n\t\t\tconst state = yield* State.Service;\n\t\t\tconst requestLLM = options.request ?? LLM.run;\n\n\t\t\tconst failureStub = Effect.fn(\"Loop.failureStub\")(function* (\n\t\t\t\tdraft: Session.HydratedEntry,\n\t\t\t\treason: \"aborted\" | \"error\",\n\t\t\t\tmessage: string,\n\t\t\t) {\n\t\t\t\tconst decoded = yield* ContextCodec.decodeMessage(draft).pipe(Effect.orDie);\n\t\t\t\tif (decoded.role !== \"assistant\") return yield* Effect.die(`draft ${draft.entry.id} is not an assistant`);\n\t\t\t\tconst completed = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\treturn {\n\t\t\t\t\t...decoded,\n\t\t\t\t\tstopReason: reason,\n\t\t\t\t\terrorMessage: message,\n\t\t\t\t\ttime: { ...decoded.time, completed },\n\t\t\t\t\tparts: [],\n\t\t\t\t} satisfies Message.AssistantMessage;\n\t\t\t});\n\n\t\t\tconst publishFailure = Effect.fn(\"Loop.publishFailure\")(function* (\n\t\t\t\tdraft: Session.HydratedEntry,\n\t\t\t\tcause: EventList.TurnAbortCause,\n\t\t\t) {\n\t\t\t\tconst reason = cause._tag === \"interrupted\" ? \"aborted\" : \"error\";\n\t\t\t\tconst message = cause._tag === \"interrupted\" ? \"turn interrupted before commit\" : cause.message;\n\t\t\t\tyield* events.publish(EventList.LLMFailed, {\n\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\tsessionId: draft.entry.sessionId,\n\t\t\t\t\tmessageId: SessionMessageSchema.ID.from(draft.entry.id),\n\t\t\t\t\treason,\n\t\t\t\t\tmessage: yield* failureStub(draft, reason, message),\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tconst healDanglingDraft = Effect.fn(\"Loop.healDanglingDraft\")(function* (sessionId: SessionSchema.ID) {\n\t\t\t\tconst path = yield* sessions.path(sessionId);\n\t\t\t\tconst draft = path.find((entry) => entry.entry.type === \"assistant\" && entry.entry.state === \"draft\");\n\t\t\t\tif (draft === undefined) return;\n\t\t\t\tyield* publishFailure(draft, { _tag: \"interrupted\" });\n\t\t\t});\n\n\t\t\tconst settleTools = Effect.fn(\"Loop.settleTools\")(function* (\n\t\t\t\tsnapshot: State.Snapshot,\n\t\t\t\tmessage: Message.AssistantMessage,\n\t\t\t\treason: \"stop\" | \"length\" | \"toolUse\",\n\t\t\t\tmarkCommitted: () => void,\n\t\t\t) {\n\t\t\t\tconst pending = message.parts.filter(\n\t\t\t\t\t(part): part is Message.ToolCallPendingPart => part.type === \"toolCall\" && part.status === \"pending\",\n\t\t\t\t);\n\t\t\t\tlet interruptedCause: Cause.Cause<never> | undefined;\n\t\t\t\tconst messageId = SessionMessageSchema.ID.from(message.messageId);\n\n\t\t\t\tconst settle = Effect.fn(\"Loop.settleTool\")(function* (\n\t\t\t\t\tcall: Message.ToolCallPendingPart,\n\t\t\t\t\tpart: Message.ToolCallTerminalPart,\n\t\t\t\t) {\n\t\t\t\t\tyield* events.publish(EventList.ToolSettled, {\n\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\tsessionId: snapshot.sessionId,\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tcallID: call.callID,\n\t\t\t\t\t\tpart,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst commit = Effect.fn(\"Loop.commitTurn\")(function* () {\n\t\t\t\t\tyield* events.publish(EventList.TurnEnded, {\n\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\tsessionId: snapshot.sessionId,\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t});\n\t\t\t\t\tmarkCommitted();\n\t\t\t\t});\n\n\t\t\t\tyield* Effect.uninterruptibleMask((restore) =>\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tif (reason === \"length\") {\n\t\t\t\t\t\t\tfor (const call of pending) {\n\t\t\t\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\t\t\t\tyield* settle(call, skippedPart(call, \"tool call arguments were truncated\", now));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield* commit();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (reason !== \"toolUse\") {\n\t\t\t\t\t\t\tfor (const call of pending) {\n\t\t\t\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\t\t\t\tyield* settle(call, skippedPart(call, \"unexpected tool call for terminal response\", now));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield* commit();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst settled = new Set<string>();\n\t\t\t\t\t\tconst handle = Effect.fn(\"Loop.handleTool\")(function* (call: Message.ToolCallPendingPart) {\n\t\t\t\t\t\t\tyield* events.publish(EventList.ToolStarted, {\n\t\t\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\t\t\tsessionId: snapshot.sessionId,\n\t\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\t\tcallID: call.callID,\n\t\t\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst handled = yield* snapshot.tools\n\t\t\t\t\t\t\t\t.handle(call, {\n\t\t\t\t\t\t\t\t\tsessionId: snapshot.sessionId,\n\t\t\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\t\t\tonProgress: (progress) =>\n\t\t\t\t\t\t\t\t\t\tevents\n\t\t\t\t\t\t\t\t\t\t\t.publish(EventList.ToolProgress, {\n\t\t\t\t\t\t\t\t\t\t\t\ttimestamp: DateTime.makeUnsafe(progress.toolCall.time.end),\n\t\t\t\t\t\t\t\t\t\t\t\tsessionId: snapshot.sessionId,\n\t\t\t\t\t\t\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\t\t\t\t\t\t\tcallID: call.callID,\n\t\t\t\t\t\t\t\t\t\t\t\tpartial: progress.partial,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t.pipe(Effect.asVoid),\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.pipe(\n\t\t\t\t\t\t\t\t\tEffect.catchCauseIf(\n\t\t\t\t\t\t\t\t\t\t(cause) => !Cause.hasInterrupts(cause),\n\t\t\t\t\t\t\t\t\t\t(cause) =>\n\t\t\t\t\t\t\t\t\t\t\tEffect.map(\n\t\t\t\t\t\t\t\t\t\t\t\tEffect.clockWith((clock) => clock.currentTimeMillis),\n\t\t\t\t\t\t\t\t\t\t\t\t(now) => errorPart(call, cause, now),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t// The durable settlement and the in-memory completion marker form one\n\t\t\t\t\t\t\t// protected step. Otherwise an interrupt between them could make the\n\t\t\t\t\t\t\t// cleanup publish a second terminal transition for the same call.\n\t\t\t\t\t\t\tyield* Effect.uninterruptible(\n\t\t\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\t\t\tyield* settle(call, handled);\n\t\t\t\t\t\t\t\t\tyield* Effect.sync(() => settled.add(call.callID));\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconst execution = Effect.forEach(pending, handle, {\n\t\t\t\t\t\t\tdiscard: true,\n\t\t\t\t\t\t\tconcurrency: snapshot.toolExecution === \"parallel\" ? \"unbounded\" : 1,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst exit = yield* restore(execution).pipe(Effect.exit);\n\t\t\t\t\t\tif (Exit.isFailure(exit)) {\n\t\t\t\t\t\t\tif (!Cause.hasInterrupts(exit.cause)) return yield* Effect.failCause(exit.cause);\n\t\t\t\t\t\t\tinterruptedCause = exit.cause;\n\t\t\t\t\t\t\tfor (const call of pending) {\n\t\t\t\t\t\t\t\tif (settled.has(call.callID)) continue;\n\t\t\t\t\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\t\t\t\t\tyield* settle(call, abortedPart(call, now));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield* commit();\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\treturn interruptedCause;\n\t\t\t});\n\n\t\t\tconst runTurnAttempt = Effect.fn(\"Loop.runTurnAttempt\")(function* (\n\t\t\t\tpromotion: Promotion,\n\t\t\t\tsnapshot: State.Snapshot,\n\t\t\t) {\n\t\t\t\tconst sessionId = snapshot.sessionId;\n\t\t\t\tif (promotion !== undefined) {\n\t\t\t\t\tconst cutoff = yield* events.latestSequence(sessionId);\n\t\t\t\t\tif (promotion === \"followUp\") yield* inputs.promoteFollowUp(sessionId);\n\t\t\t\t\tyield* inputs.promoteSteers(sessionId, cutoff);\n\t\t\t\t}\n\n\t\t\t\tconst assembled = yield* context.assemble(sessionId);\n\t\t\t\tconst leaf =\n\t\t\t\t\tassembled.lastAssistant?.entryId === assembled.leafEntryId ? assembled.lastAssistant.message : undefined;\n\t\t\t\tif (leaf !== undefined && (leaf.stopReason === \"stop\" || leaf.stopReason === \"length\")) {\n\t\t\t\t\treturn { needsContinuation: false } satisfies TurnResult;\n\t\t\t\t}\n\n\t\t\t\tlet publisher: LLMEventPublisher.Publisher | undefined;\n\t\t\t\tlet committed = false;\n\t\t\t\tconst turnWindow = Effect.gen(function* () {\n\t\t\t\t\tyield* events.publish(EventList.TurnStarted, { timestamp: yield* DateTime.now, sessionId });\n\t\t\t\t\tpublisher = yield* LLMEventPublisher.make({ sessionId }).pipe(\n\t\t\t\t\t\tEffect.provideService(Event.Service, events),\n\t\t\t\t\t);\n\t\t\t\t\tconst terminal = yield* requestLLM({\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tsystemPrompt: snapshot.systemPrompt,\n\t\t\t\t\t\t\tmessages: [...assembled.messages],\n\t\t\t\t\t\t\ttools: [...snapshot.tools.wire],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tprovider: snapshot.provider,\n\t\t\t\t\t\tmodel: snapshot.model,\n\t\t\t\t\t\tresolvedModel: snapshot.resolvedModel,\n\t\t\t\t\t\tthinkingLevel: snapshot.thinkingLevel,\n\t\t\t\t\t\toptions: snapshot.request,\n\t\t\t\t\t\tsettings: snapshot.settings,\n\t\t\t\t\t\tpublisher,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (terminal.outcome === \"failed\") {\n\t\t\t\t\t\tif (terminal.reason === \"aborted\") return yield* Effect.interrupt;\n\t\t\t\t\t\treturn yield* LLM.providerError(\n\t\t\t\t\t\t\t{ provider: snapshot.provider, model: snapshot.model },\n\t\t\t\t\t\t\tLLM.messageFailure(terminal.message),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst interrupted = yield* settleTools(snapshot, terminal.message, terminal.reason, () => {\n\t\t\t\t\t\tcommitted = true;\n\t\t\t\t\t});\n\t\t\t\t\tif (interrupted !== undefined) return yield* Effect.failCause(interrupted);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tneedsContinuation: terminal.reason === \"toolUse\",\n\t\t\t\t\t\tmessageId: terminal.message.messageId,\n\t\t\t\t\t} satisfies TurnResult;\n\t\t\t\t});\n\n\t\t\t\treturn yield* turnWindow.pipe(\n\t\t\t\t\tEffect.catchCause((cause) => {\n\t\t\t\t\t\tif (committed) return Effect.failCause(cause);\n\t\t\t\t\t\tconst turnCause: EventList.TurnAbortCause = Cause.hasInterrupts(cause)\n\t\t\t\t\t\t\t? { _tag: \"interrupted\" }\n\t\t\t\t\t\t\t: { _tag: \"error\", message: errorMessage(cause) };\n\t\t\t\t\t\tconst record = Effect.gen(function* () {\n\t\t\t\t\t\t\tif (publisher?.startedMessageId !== undefined) {\n\t\t\t\t\t\t\t\tconst stored = yield* sessions.entry(publisher.startedMessageId);\n\t\t\t\t\t\t\t\tif (Option.isSome(stored) && stored.value.entry.state === \"draft\") {\n\t\t\t\t\t\t\t\t\tyield* publishFailure(stored.value, turnCause);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tyield* events.publish(EventList.TurnAborted, {\n\t\t\t\t\t\t\t\ttimestamp: yield* DateTime.now,\n\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\tcause: turnCause,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn Effect.uninterruptible(record).pipe(Effect.andThen(Effect.failCause(cause)));\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tconst runTurn = Effect.fn(\"Loop.runTurn\")(function* (promotion: Promotion, snapshot: State.Snapshot) {\n\t\t\t\treturn yield* runTurnAttempt(promotion, snapshot);\n\t\t\t});\n\n\t\t\tconst run = Effect.fn(\"Loop.run\")(function* (input: {\n\t\t\t\treadonly sessionId: SessionSchema.ID;\n\t\t\t\treadonly force: boolean;\n\t\t\t}) {\n\t\t\t\tyield* healDanglingDraft(input.sessionId);\n\n\t\t\t\tconst hasSteer = yield* inputs.hasPending(input.sessionId, \"steer\");\n\t\t\t\tconst hasFollowUp = hasSteer ? false : yield* inputs.hasPending(input.sessionId, \"followUp\");\n\t\t\t\tif (!input.force && !hasSteer && !hasFollowUp) return;\n\n\t\t\t\tlet promotion: Promotion = hasSteer ? \"steer\" : hasFollowUp ? \"followUp\" : undefined;\n\t\t\t\tlet shouldRun = true;\n\t\t\t\twhile (shouldRun) {\n\t\t\t\t\tconst snapshot = yield* state.snapshot(input.sessionId);\n\t\t\t\t\tlet needsContinuation = true;\n\t\t\t\t\twhile (needsContinuation) {\n\t\t\t\t\t\tconst result = yield* runTurn(promotion, snapshot);\n\t\t\t\t\t\tpromotion = \"steer\";\n\t\t\t\t\t\tneedsContinuation = result.needsContinuation || (yield* inputs.hasPending(input.sessionId, \"steer\"));\n\t\t\t\t\t}\n\t\t\t\t\tshouldRun = yield* inputs.hasPending(input.sessionId, \"followUp\");\n\t\t\t\t\tpromotion = shouldRun ? \"followUp\" : undefined;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn Runner.Service.of({ run });\n\t\t}),\n\t);\n\nexport * as Loop from \"./loop.ts\";\n","import { Effect, Schema } from \"effect\";\nimport { importModule, resolveModule } from \"../util/module.ts\";\nimport { SandboxDriver } from \"./driver.ts\";\nimport { SandboxDriverLoadError } from \"./errors.ts\";\n\nexport interface PackageEntry {\n\treadonly package: string;\n\treadonly options?: unknown;\n}\n\nexport type Entry = string | PackageEntry | SandboxDriver.Registration;\n\nexport interface Resolved {\n\treadonly specifier: string;\n\treadonly url: string;\n\treadonly source: Extract<SandboxDriver.Source, \"builtin\" | \"package\" | \"file\">;\n}\n\nexport type Resolver = (specifier: string) => Effect.Effect<Resolved, SandboxDriverLoadError>;\nexport type Importer = (url: string) => Promise<unknown>;\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n\ttypeof value === \"object\" && value !== null;\n\nconst splitPackage = (specifier: string): { readonly name: string; readonly key: string } | undefined => {\n\tconst parts = specifier.split(\"/\");\n\tif (specifier.startsWith(\"@\")) {\n\t\tif (parts.length < 2 || parts[0]?.length === 1 || parts[1]?.length === 0) return undefined;\n\t\treturn { name: `${parts[0]}/${parts[1]}`, key: parts.length === 2 ? \".\" : `./${parts.slice(2).join(\"/\")}` };\n\t}\n\tif (parts[0]?.length === 0) return undefined;\n\treturn { name: parts[0]!, key: parts.length === 1 ? \".\" : `./${parts.slice(1).join(\"/\")}` };\n};\n\nexport const isPackageSpecifier = (specifier: string): boolean =>\n\t!specifier.startsWith(\".\") &&\n\t!specifier.startsWith(\"/\") &&\n\t!specifier.startsWith(\"file:\") &&\n\t!specifier.includes(\"\\\\\") &&\n\t!specifier.includes(\":\") &&\n\tsplitPackage(specifier) !== undefined;\n\nconst official = new Set([\"@codeworksh/harness/sandboxes/vercel\", \"@codeworksh/harness/sandboxes/daytona\"]);\n\n/**\n * Resolves driver package specifiers against `hostCwd` -- the OS process's\n * directory, supplied by the caller. This is host module resolution, not sandbox\n * addressing: a driver package lives on the host filesystem no matter which\n * namespace the sandbox it builds will serve. Required rather than defaulted so\n * it can never silently disagree with the directory the harness was started in.\n */\nexport const packageResolver = (\n\thostCwd: string,\n\tconditions: ReadonlyArray<string> = [\"node\", \"import\", \"default\"],\n): Resolver =>\n\tEffect.fn(\"SandboxDriverLoader.resolve\")(function* (specifier: string) {\n\t\tif (!isPackageSpecifier(specifier)) {\n\t\t\treturn yield* new SandboxDriverLoadError({\n\t\t\t\tspecifier,\n\t\t\t\tphase: \"resolve\",\n\t\t\t\treason: \"expected an installed npm package specifier; filesystem paths are not supported yet\",\n\t\t\t});\n\t\t}\n\t\tconst url = yield* Effect.try({\n\t\t\ttry: () => resolveModule(specifier, hostCwd, conditions),\n\t\t\tcatch: (reason) => new SandboxDriverLoadError({ specifier, phase: \"resolve\", reason: String(reason) }),\n\t\t});\n\t\treturn {\n\t\t\tspecifier,\n\t\t\turl,\n\t\t\tsource: official.has(specifier) ? \"builtin\" : \"package\",\n\t\t};\n\t});\n\ninterface LoadableModule {\n\treadonly apiVersion: number;\n\treadonly name: string;\n\treadonly options: Schema.Codec<unknown, unknown>;\n\treadonly make: (options: unknown) => unknown;\n}\n\nconst isModule = (value: unknown): value is LoadableModule =>\n\tisRecord(value) &&\n\ttypeof value.apiVersion === \"number\" &&\n\ttypeof value.name === \"string\" &&\n\tSchema.isSchema(value.options) &&\n\ttypeof value.make === \"function\";\n\nconst isRegistration = (value: unknown): value is SandboxDriver.Registration => {\n\tif (\n\t\t!isRecord(value) ||\n\t\tvalue.apiVersion !== SandboxDriver.apiVersion ||\n\t\ttypeof value.source !== \"string\" ||\n\t\t!isRecord(value.registered)\n\t)\n\t\treturn false;\n\tconst registered = value.registered;\n\tconst capabilities = registered.capabilities;\n\treturn (\n\t\ttypeof registered.name === \"string\" &&\n\t\t(registered.kind === \"virtual\" || registered.kind === \"remote\") &&\n\t\tisRecord(capabilities) &&\n\t\t[\"inspect\", \"reattach\", \"wake\", \"stop\", \"destroy\", \"cancels\"].every(\n\t\t\t(capability) => typeof capabilities[capability] === \"boolean\",\n\t\t) &&\n\t\tSchema.isSchema(registered.createConfigCodec) &&\n\t\tSchema.isSchema(registered.runtimeConfigCodec) &&\n\t\ttypeof registered.create === \"function\" &&\n\t\ttypeof registered.attach === \"function\"\n\t);\n};\n\nconst failure = (specifier: string, phase: SandboxDriverLoadError[\"phase\"], reason: unknown, driver?: string) =>\n\tnew SandboxDriverLoadError({\n\t\tspecifier,\n\t\tphase,\n\t\t...(driver === undefined ? {} : { driver }),\n\t\treason: String(reason),\n\t});\n\nexport interface Options {\n\t/** The OS process's directory. See {@link packageResolver}. */\n\treadonly hostCwd: string;\n\treadonly resolve?: Resolver;\n\treadonly import?: Importer;\n}\n\nexport const load = Effect.fn(\"SandboxDriverLoader.load\")(function* (entry: Entry, options: Options) {\n\tif (isRegistration(entry)) return entry;\n\tconst specifier = typeof entry === \"string\" ? entry : entry.package;\n\tconst rawOptions = typeof entry === \"string\" ? {} : (entry.options ?? {});\n\tconst resolved = yield* (options.resolve ?? packageResolver(options.hostCwd))(specifier);\n\tconst imported = yield* Effect.tryPromise({\n\t\ttry: () => (options.import ?? importModule)(resolved.url),\n\t\tcatch: (reason) => failure(specifier, \"import\", reason),\n\t});\n\tconst loaded = isRecord(imported) ? imported.default : undefined;\n\tif (!isModule(loaded)) return yield* failure(specifier, \"module\", \"default export is not a sandbox driver module\");\n\tif (loaded.apiVersion !== SandboxDriver.apiVersion) {\n\t\treturn yield* failure(\n\t\t\tspecifier,\n\t\t\t\"api-version\",\n\t\t\t`unsupported sandbox driver API version: ${loaded.apiVersion}`,\n\t\t\tloaded.name,\n\t\t);\n\t}\n\tconst decoded = yield* Schema.decodeEffect(loaded.options)(rawOptions).pipe(\n\t\tEffect.mapError(() => failure(specifier, \"options\", \"options did not match the module schema\", loaded.name)),\n\t);\n\tconst registration = yield* Effect.try({\n\t\ttry: () => loaded.make(decoded),\n\t\tcatch: (reason) => failure(specifier, \"factory\", reason, loaded.name),\n\t});\n\tif (!isRegistration(registration)) {\n\t\treturn yield* failure(specifier, \"registration\", \"module factory returned an invalid registration\", loaded.name);\n\t}\n\tif (registration.registered.name !== loaded.name) {\n\t\treturn yield* failure(\n\t\t\tspecifier,\n\t\t\t\"registration\",\n\t\t\t`module name does not match driver name: ${registration.registered.name}`,\n\t\t\tloaded.name,\n\t\t);\n\t}\n\treturn SandboxDriver.withSource(registration, resolved.source);\n});\n\nexport const loadAll = (\n\tentries: ReadonlyArray<Entry>,\n\toptions: Options,\n): Effect.Effect<ReadonlyArray<SandboxDriver.Registration>, SandboxDriverLoadError> =>\n\tEffect.forEach(entries, (entry) => load(entry, options));\n\nexport * as SandboxDriverLoader from \"./loader.ts\";\n","/*\n * @file Registers the durable-input projectors with the event service.\n *\n * Provides no service. Its only purpose is the registration side effect, which\n * must happen exactly once and before anything publishes -- `Layer` gives both,\n * because a layer is built once per graph, at startup.\n *\n * Registering from `SessionInput.make` instead would run once per consumer, and\n * a projector registered twice runs twice on one event: the second insert hits\n * ON CONFLICT, raises LifecycleConflict inside the commit, and rolls the event\n * back. Every admission would fail, blaming a conflict that does not exist.\n *\n * Nothing type-errors if this layer is left out of the graph. `admit` publishes\n * happily and writes no row, so the wiring is worth asserting in a test.\n *\n * Only durable definitions are registered here, and that is not a stylistic\n * choice: `Event.project` hands its callback to `commitDurableEvent`, which only\n * runs for events that have a transaction. Registering a projector for a live\n * definition -- TurnStarted/TurnAborted, LLM fragments, or tool progress --\n * compiles, looks wired, and never fires.\n *\n * Live events are not lost, they take the other path. `notify` publishes every\n * event to the typed and firehose pubsubs, so deltas and block boundaries are\n * already streaming; what does not exist yet is a `subscribe` on\n * `Event.Interface` for a consumer to read them from. That is the hook a future\n * streamer wants -- a stream it subscribes to, not a callback per event type --\n * so nothing needs registering here for it.\n */\n\nimport { Message } from \"@codeworksh/aikit\";\nimport { DateTime, Effect, Layer } from \"effect\";\nimport { ContextCodec } from \"../context/codec.ts\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { SessionInput } from \"./input/input.ts\";\nimport type { SessionMessageSchema } from \"./message/schema.ts\";\nimport type { SessionSchema } from \"./schema.ts\";\nimport { Session } from \"./session.ts\";\n\nexport const layer = Layer.effectDiscard(\n\tEffect.gen(function* () {\n\t\tconst events = yield* Event.Service;\n\t\tconst input = yield* SessionInput.make;\n\t\tconst sessions = yield* Session.Service;\n\n\t\tconst encodeAssistant = Effect.fn(\"SessionProjector.encodeAssistant\")(function* (input: {\n\t\t\treadonly sessionId: SessionSchema.ID;\n\t\t\treadonly messageId: SessionMessageSchema.ID;\n\t\t\treadonly message: Message.AssistantMessage;\n\t\t}) {\n\t\t\tif (input.message.messageId !== input.messageId) {\n\t\t\t\treturn yield* Effect.die(\n\t\t\t\t\t`assistant message id \"${input.message.messageId}\" does not match event message id \"${input.messageId}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn yield* ContextCodec.encodeMessage(input.message).pipe(Effect.orDie);\n\t\t});\n\n\t\tyield* events.project(EventList.PromptAdmitted, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\t// The sequence is assigned by the commit itself, so a durable event\n\t\t\t\t// arriving without one means it never went through the transaction.\n\t\t\t\tif (event.durable === undefined)\n\t\t\t\t\treturn yield* Effect.die(\"PromptAdmitted is missing its aggregate sequence\");\n\t\t\t\tyield* input.projectAdmitted({\n\t\t\t\t\tadmittedSeq: event.durable.seq,\n\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tprompt: event.data.prompt,\n\t\t\t\t\tdelivery: event.data.delivery,\n\t\t\t\t\ttimeCreated: event.data.timestamp,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\n\t\t// Publishing `Prompted` is what promotes an input, so this registration is\n\t\t// what makes `promoteSteers` / `promoteFollowUp` take effect at all.\n\t\tyield* events.project(EventList.Prompted, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (event.durable === undefined) return yield* Effect.die(\"Prompted is missing its aggregate sequence\");\n\t\t\t\tyield* input.projectPrompted({\n\t\t\t\t\tpromotedSeq: event.durable.seq,\n\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tprompt: event.data.prompt,\n\t\t\t\t\tdelivery: event.data.delivery,\n\t\t\t\t\ttimeCreated: event.data.timestamp,\n\t\t\t\t});\n\t\t\t\t// Promotion is what puts a prompt into the conversation, so the append\n\t\t\t\t// belongs in this commit: \"promoted but absent from history\" is then\n\t\t\t\t// unrepresentable rather than a window someone has to reconcile.\n\t\t\t\t// Materialize the canonical conversation message now. Context later\n\t\t\t\t// rehydrates this envelope + parts; aikit performs only the target-model\n\t\t\t\t// conversion when Loop calls the provider.\n\t\t\t\tconst encoded = yield* ContextCodec.encodeMessage(\n\t\t\t\t\tMessage.createUserMessage({\n\t\t\t\t\t\tmessageId: event.data.messageId,\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\ttime: { created: DateTime.toEpochMillis(event.data.timestamp) },\n\t\t\t\t\t\tparts: [{ type: \"text\", text: event.data.prompt.text }],\n\t\t\t\t\t}),\n\t\t\t\t).pipe(Effect.orDie);\n\t\t\t\tyield* sessions\n\t\t\t\t\t.append({\n\t\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\t\tseq: event.durable.seq,\n\t\t\t\t\t\tstate: \"committed\",\n\t\t\t\t\t\t...encoded,\n\t\t\t\t\t\t// Rides the in-memory payload; the event row never carried it, so\n\t\t\t\t\t\t// the entry is the only place it can outlive the publish.\n\t\t\t\t\t\t...(event.metadata === undefined ? {} : { metadata: event.metadata }),\n\t\t\t\t\t})\n\t\t\t\t\t.pipe(Effect.orDie);\n\t\t\t}),\n\t\t);\n\n\t\tyield* events.project(EventList.LLMStarted, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (event.durable === undefined) return yield* Effect.die(\"LLMStarted is missing its aggregate sequence\");\n\t\t\t\tconst encoded = yield* encodeAssistant({\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tmessageId: event.data.messageId,\n\t\t\t\t\tmessage: event.data.message,\n\t\t\t\t});\n\t\t\t\tyield* sessions\n\t\t\t\t\t.append({\n\t\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\t\tseq: event.durable.seq,\n\t\t\t\t\t\tstate: \"draft\",\n\t\t\t\t\t\t...encoded,\n\t\t\t\t\t\t...(event.metadata === undefined ? {} : { metadata: event.metadata }),\n\t\t\t\t\t})\n\t\t\t\t\t.pipe(Effect.orDie);\n\t\t\t}),\n\t\t);\n\n\t\tyield* events.project(EventList.LLMEnded, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst encoded = yield* encodeAssistant({\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tmessageId: event.data.messageId,\n\t\t\t\t\tmessage: event.data.message,\n\t\t\t\t});\n\t\t\t\tyield* sessions.replaceAssistant({\n\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tdata: encoded.data,\n\t\t\t\t\tparts: encoded.parts,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\n\t\tyield* events.project(EventList.LLMFailed, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst encoded = yield* encodeAssistant({\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tmessageId: event.data.messageId,\n\t\t\t\t\tmessage: event.data.message,\n\t\t\t\t});\n\t\t\t\tyield* sessions.abortAssistant({\n\t\t\t\t\tid: event.data.messageId,\n\t\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\t\tdata: encoded.data,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\n\t\tyield* events.project(EventList.ToolSettled, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst encoded = yield* ContextCodec.encodePart(event.data.part).pipe(Effect.orDie);\n\t\t\t\tyield* sessions.settleToolCall({\n\t\t\t\t\tentryId: event.data.messageId,\n\t\t\t\t\tcallId: event.data.callID,\n\t\t\t\t\tstatus: event.data.part.status,\n\t\t\t\t\tdata: encoded.data,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\n\t\tyield* events.project(EventList.TurnEnded, (event) =>\n\t\t\tsessions.setEntryState({\n\t\t\t\tid: event.data.messageId,\n\t\t\t\tsessionId: event.data.sessionId,\n\t\t\t\tstate: \"committed\",\n\t\t\t}),\n\t\t);\n\t}),\n);\n\nexport * as SessionProjector from \"./projector.ts\";\n","/*\n * @file The session service with its projections registered.\n *\n * Provide this, not `Session.layer` alone. `Control.prompt` records a prompt by\n * publishing an event, and the row only appears because a projector reacted to\n * it — without `SessionProjector.layer` in the graph the publish succeeds, the\n * inbox stays empty, and nothing errors.\n */\n\nimport { Layer } from \"effect\";\nimport { SessionProjector } from \"./projector.ts\";\nimport { Session } from \"./session.ts\";\n\nexport const layer = Layer.provideMerge(SessionProjector.layer, Session.layer);\n\nexport * as SessionLive from \"./live.ts\";\n","import { Effect, Layer } from \"effect\";\nimport { Context } from \"../context/context.ts\";\nimport { Control } from \"../control.ts\";\nimport { Database } from \"../db/db.ts\";\nimport { Event } from \"../event/event.ts\";\nimport { Global } from \"../global.ts\";\nimport { EventRegistry } from \"../event/registry.ts\";\nimport { prepare, type PluginRef } from \"../plugin/catalog.ts\";\nimport { builtins } from \"../plugin/builtin.ts\";\nimport { RunnerExecute } from \"../runner/execute.ts\";\nimport { LLM } from \"../runner/llm.ts\";\nimport { Loop } from \"../runner/loop.ts\";\nimport { SandboxController } from \"../sandbox/control.ts\";\nimport { SandboxDriver } from \"../sandbox/driver.ts\";\nimport { MemorySandboxDriver } from \"../sandbox/drivers/memory.ts\";\nimport { SqldbSandboxDriver } from \"../sandbox/drivers/sqldb.ts\";\nimport { SandboxDriverLoader } from \"../sandbox/loader.ts\";\nimport { SandboxDriverRegistry } from \"../sandbox/registry.ts\";\nimport { SessionLive } from \"../session/live.ts\";\nimport { SessionRuntime } from \"../session/runtime.ts\";\nimport { Settings } from \"../settings/settings.ts\";\nimport { State } from \"../state/state.ts\";\n\nexport interface Options {\n\t/**\n\t * The complete selection, replacing both the built-ins and whatever `settings.plugins`\n\t * asks for -- an embedder that passes this owns the plugin set, and an empty array runs\n\t * none. Omit it to get the built-ins plus the settings block.\n\t */\n\treadonly plugins?: ReadonlyArray<PluginRef>;\n\treadonly database?: string;\n\treadonly home?: string;\n\t/** user provided directory containing the highest-priority config. */\n\treadonly userConfigDir?: string;\n\treadonly sandboxes?: ReadonlyArray<SandboxDriverLoader.Entry>;\n\treadonly llm?: LLM.Open;\n}\n\nexport const layer = (options: Options = {}) =>\n\tLayer.unwrap(\n\t\tEffect.gen(function* () {\n\t\t\tconst paths = yield* Global.resolve(options.home === undefined ? {} : { home: options.home });\n\t\t\t// The single sanctioned `process.cwd()` in the harness. Everything downstream\n\t\t\t// takes the host directory as a required parameter, so no module can quietly\n\t\t\t// fall back to the OS process's directory when it meant a session's mount.\n\t\t\tconst hostCwd = process.cwd();\n\t\t\tconst global = Global.layerWith(paths);\n\t\t\tconst settingsOptions = {\n\t\t\t\tcwd: hostCwd,\n\t\t\t\t...(options.userConfigDir === undefined ? {} : { userConfigDir: options.userConfigDir }),\n\t\t\t};\n\t\t\t// Settings are read once here because the plugin selection has to be prepared before\n\t\t\t// any layer that depends on it; every later read goes through `Settings.Service`.\n\t\t\tconst config = yield* Settings.load({ ...settingsOptions, home: paths.home });\n\t\t\t// Settings entries extend the built-in selection rather than standing in for it, so\n\t\t\t// naming a plugin cannot silently drop Bash or the default prompt. A built-in is turned\n\t\t\t// off by name, with a `{ \"plugin\": \"codework.tool.bash\", \"enabled\": false }` entry.\n\t\t\tconst selection = yield* prepare(options.plugins ?? [...builtins, ...config.plugins], {\n\t\t\t\tbuiltins,\n\t\t\t\tcache: paths.cache,\n\t\t\t\thostCwd,\n\t\t\t});\n\t\t\t// Flattened before anything can publish: a plugin event type that collides\n\t\t\t// or is not namespaced is a boot failure, not a surprise at first publish.\n\t\t\tconst definitions = yield* EventRegistry.flatten(selection.map((entry) => entry.plugin));\n\t\t\tconst configuredDatabase = options.database ?? (yield* Database.locationConfig);\n\t\t\tconst database = Database.layer(Database.resolveDatabaseLocation(configuredDatabase, paths.data));\n\t\t\tconst configured = yield* SandboxDriverLoader.loadAll(options.sandboxes ?? [], { hostCwd });\n\t\t\tconst drivers = SandboxDriverRegistry.layer(\n\t\t\t\tSandboxDriver.withSource(MemorySandboxDriver.make().driver, \"core\"),\n\t\t\t\tSandboxDriver.withSource(SqldbSandboxDriver.make().driver, \"core\"),\n\t\t\t\t...configured,\n\t\t\t);\n\t\t\tconst sandboxes = SandboxController.layer().pipe(Layer.provideMerge(drivers), Layer.provideMerge(database));\n\t\t\tconst loop = options.llm === undefined ? Loop.layer() : Loop.layer({ request: LLM.make(options.llm) });\n\n\t\t\treturn Control.layer.pipe(\n\t\t\t\tLayer.provideMerge(RunnerExecute.layer.pipe(Layer.provide(loop))),\n\t\t\t\tLayer.provideMerge(State.layer({}, selection)),\n\t\t\t\tLayer.provideMerge(Settings.layer(settingsOptions)),\n\t\t\t\tLayer.provideMerge(SessionRuntime.layer),\n\t\t\t\tLayer.provideMerge(sandboxes),\n\t\t\t\tLayer.provideMerge(Context.layer),\n\t\t\t\tLayer.provideMerge(SessionLive.layer),\n\t\t\t\tLayer.provideMerge(Event.layer),\n\t\t\t\tLayer.provideMerge(EventRegistry.layer(definitions)),\n\t\t\t\tLayer.provideMerge(database),\n\t\t\t\tLayer.provideMerge(global),\n\t\t\t);\n\t\t}),\n\t);\n\nexport * as Harness from \"./harness.ts\";\n","import { Effect, Option, Schema } from \"effect\";\nimport { SandboxController } from \"../sandbox/control.ts\";\nimport { SandboxDriver } from \"../sandbox/driver.ts\";\nimport {\n\tSandboxDriverNotRegisteredError,\n\tSandboxDriverRegistrationError,\n\tSandboxNotFoundError,\n} from \"../sandbox/errors.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { SandboxDriverLoader } from \"../sandbox/loader.ts\";\nimport { SandboxDriverRegistry, type DriverInfo } from \"../sandbox/registry.ts\";\n\nimport { optional } from \"../schema.ts\";\n\nexport type Info = SandboxInstance.Info;\nexport type Driver = SandboxDriverLoader.Entry;\nexport type { DriverInfo };\n\nexport interface CreateInput {\n\treadonly driver: string;\n\treadonly config?: unknown;\n}\n\nexport interface RegisterInput {\n\treadonly driver: string;\n\treadonly providerResourceId: string;\n\treadonly runtimeConfig?: unknown;\n}\n\nconst name = (value: string) => SandboxDriver.Name.make(value);\n\nconst registered = Effect.fn(\"Sandbox.registered\")(function* (value: string) {\n\tconst registry = yield* SandboxDriverRegistry.Registry;\n\treturn yield* registry.get(name(value));\n});\n\nconst runtimeOverrides = (driver: SandboxDriver.Name, value: unknown) => {\n\tif (value === undefined) return Effect.void;\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn Effect.fail(\n\t\t\tnew SandboxDriverRegistrationError({\n\t\t\t\tdriver,\n\t\t\t\treason: \"runtimeConfig must be an object\",\n\t\t\t}),\n\t\t);\n\t}\n\treturn Effect.succeed(value as Readonly<Record<string, unknown>>);\n};\n\nexport const create = Effect.fn(\"Sandbox.create\")(function* (input: CreateInput) {\n\tconst controller = yield* SandboxController.Controller;\n\tconst registry = yield* SandboxDriverRegistry.Registry;\n\tconst driverName = name(input.driver);\n\tconst driver = yield* registry.get(driverName);\n\tconst config = yield* registry.decodeCreateConfig(driverName, input.config ?? {});\n\treturn yield* controller.create({ driver, config });\n});\n\nexport const register = Effect.fn(\"Sandbox.register\")(function* (input: RegisterInput) {\n\tconst controller = yield* SandboxController.Controller;\n\tconst driver = yield* registered(input.driver);\n\tconst runtimeConfig = yield* runtimeOverrides(driver.name, input.runtimeConfig);\n\treturn yield* controller.register({\n\t\tdriver,\n\t\tproviderResourceId: input.providerResourceId,\n\t\t...(runtimeConfig === undefined ? {} : { runtimeConfig }),\n\t});\n});\n\n/** Coordinates for either reusing an instance or provisioning/registering one. */\nexport const Selection = Schema.Union([\n\tSchema.Struct({ id: SandboxInstance.ID }),\n\tSchema.Struct({ driver: Schema.String, providerResourceId: optional(Schema.String) }),\n]);\nexport type Selection = typeof Selection.Type;\n\nexport const resolve = Effect.fn(\"Sandbox.resolve\")(function* (input: Selection) {\n\tif (\"id\" in input) {\n\t\tconst found = yield* get(input.id);\n\t\tif (Option.isNone(found)) return yield* new SandboxNotFoundError({ id: input.id });\n\t\treturn { info: found.value, created: false };\n\t}\n\tif (input.driver === \"local\") {\n\t\tif (input.providerResourceId !== undefined)\n\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\tdriver: input.driver,\n\t\t\t\treason: \"providerResourceId requires a remote sandbox driver\",\n\t\t\t});\n\t\treturn { info: undefined, created: false };\n\t}\n\tconst available = yield* drivers();\n\tconst driver = available.find((candidate) => candidate.name === input.driver);\n\tif (driver === undefined)\n\t\treturn yield* new SandboxDriverNotRegisteredError({\n\t\t\tdriver: input.driver,\n\t\t\tregistered: [\"local\", ...available.map(({ name }) => name)],\n\t\t});\n\tif (input.providerResourceId !== undefined && driver.kind !== \"remote\")\n\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\tdriver: input.driver,\n\t\t\treason: \"providerResourceId requires a remote sandbox driver\",\n\t\t});\n\tconst info =\n\t\tinput.providerResourceId === undefined\n\t\t\t? yield* create({ driver: input.driver })\n\t\t\t: yield* register({ driver: input.driver, providerResourceId: input.providerResourceId });\n\treturn { info, created: input.providerResourceId === undefined && info.ownership === \"managed\" };\n});\n\nexport const drivers = Effect.fn(\"Sandbox.drivers\")(function* () {\n\tconst registry = yield* SandboxDriverRegistry.Registry;\n\treturn registry.drivers;\n});\n\nexport const get = Effect.fn(\"Sandbox.get\")(function* (id: SandboxInstance.ID) {\n\tconst controller = yield* SandboxController.Controller;\n\treturn yield* controller.get(id);\n});\n\nexport const list = Effect.fn(\"Sandbox.list\")(function* (input?: {\n\treadonly driver?: string;\n\treadonly status?: SandboxInstance.Status;\n}) {\n\tconst controller = yield* SandboxController.Controller;\n\treturn yield* controller.list({\n\t\t...(input?.driver === undefined ? {} : { driver: name(input.driver) }),\n\t\t...(input?.status === undefined ? {} : { status: input.status }),\n\t});\n});\n\nexport const refresh = Effect.fn(\"Sandbox.refresh\")(function* (id: SandboxInstance.ID) {\n\tconst controller = yield* SandboxController.Controller;\n\treturn yield* controller.refresh(id);\n});\n\nexport const wake = Effect.fn(\"Sandbox.wake\")(function* (id: SandboxInstance.ID) {\n\tconst controller = yield* SandboxController.Controller;\n\treturn yield* controller.wake(id);\n});\n\nexport const stop = Effect.fn(\"Sandbox.stop\")(function* (id: SandboxInstance.ID) {\n\tconst controller = yield* SandboxController.Controller;\n\treturn yield* controller.stop(id);\n});\n\nexport const destroy = Effect.fn(\"Sandbox.destroy\")(function* (id: SandboxInstance.ID) {\n\tconst controller = yield* SandboxController.Controller;\n\tyield* controller.destroy(id);\n});\n\nexport { SandboxInstance };\n\nexport * as Sandbox from \"./sandbox.ts\";\n","import type { Model } from \"@codeworksh/aikit\";\nimport { Effect, Option, Stream } from \"effect\";\nimport * as Control from \"../control.ts\";\nimport * as Event from \"../event/event.ts\";\nimport type { EventSchema } from \"../event/schema.ts\";\nimport { Location } from \"../location/location.ts\";\nimport * as SandboxController from \"../sandbox/control.ts\";\nimport { SandboxInstance as SandboxInstanceSchema } from \"../sandbox/instance.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\nimport { SessionMessageSchema } from \"../session/message/schema.ts\";\nimport type { Delivery } from \"../session/prompt/schema.ts\";\nimport { PromptSchema } from \"../session/prompt/schema.ts\";\nimport * as SessionRuntime from \"../session/runtime.ts\";\nimport { SessionSchema } from \"../session/schema.ts\";\nimport { Session as SessionStore } from \"../session/session.ts\";\nimport type { State } from \"../state/state.ts\";\nimport type { Info as SandboxInfo } from \"./sandbox.ts\";\n\nexport interface ModelConfig {\n\treadonly provider: string;\n\treadonly id: string;\n\treadonly options?: State.RequestOptions;\n}\n\nexport interface ToolsConfig {\n\treadonly execution?: State.ToolExecutionMode;\n}\n\nexport interface SystemPromptConfig {\n\treadonly custom?: State.Options[\"promptCustom\"];\n\treadonly append?: State.Options[\"promptSystemAppend\"];\n}\n\nexport interface RuntimeInput {\n\treadonly model?: ModelConfig;\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n\treadonly tools?: ToolsConfig;\n\treadonly systemPrompt?: SystemPromptConfig;\n}\n\nexport interface CreateInput extends RuntimeInput {\n\treadonly title?: string;\n\treadonly sandbox?: SandboxInfo;\n\treadonly directory?: string;\n}\n\nexport interface AttachInput extends RuntimeInput {\n\treadonly sessionId: SessionSchema.ID;\n}\n\nexport interface RelinkInput {\n\treadonly sessionId: SessionSchema.ID;\n\treadonly sandbox?: SandboxInfo;\n\treadonly directory?: string;\n}\n\nexport type PromptInput =\n\t| string\n\t| {\n\t\t\treadonly text: string;\n\t\t\treadonly delivery?: Delivery;\n\t\t\treadonly id?: SessionMessageSchema.ID;\n\t };\n\nexport interface Info {\n\treadonly id: SessionSchema.ID;\n\treadonly title: string;\n\treadonly directory: AbsolutePath;\n\treadonly sandbox?: SandboxInfo;\n}\n\nexport interface Handle {\n\treadonly id: SessionSchema.ID;\n\treadonly active: Effect.Effect<boolean>;\n\treadonly info: Effect.Effect<Info, SessionStore.SessionNotFoundError>;\n\treadonly prompt: (input: PromptInput) => ReturnType<Control.Interface[\"prompt\"]>;\n\treadonly run: (input: PromptInput) => ReturnType<Control.Interface[\"run\"]>;\n\treadonly wait: () => ReturnType<Control.Interface[\"wait\"]>;\n\treadonly resume: () => ReturnType<Control.Interface[\"resume\"]>;\n\t/** Stops active work and waits for its cleanup; idle is a no-op returning false. */\n\treadonly interrupt: () => ReturnType<Control.Interface[\"interrupt\"]>;\n\t/** Live session notifications. Use Event.log for durable replay. */\n\treadonly events: () => Stream.Stream<EventSchema.Payload, Event.SubscriptionOverflowError>;\n\treadonly path: () => Effect.Effect<ReadonlyArray<SessionStore.HydratedEntry>>;\n}\n\nconst runtimeBindings = (input: RuntimeInput): SessionRuntime.Bindings => ({\n\t...input.model?.options,\n\t...(input.model === undefined ? {} : { provider: input.model.provider, model: input.model.id }),\n\t...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),\n\t...(input.tools?.execution === undefined ? {} : { toolExecution: input.tools.execution }),\n\t...(input.systemPrompt?.custom === undefined ? {} : { promptCustom: input.systemPrompt.custom }),\n\t...(input.systemPrompt?.append === undefined ? {} : { promptSystemAppend: input.systemPrompt.append }),\n});\n\nconst promptInput = (input: PromptInput) => {\n\tconst value = typeof input === \"string\" ? { text: input } : input;\n\treturn {\n\t\tprompt: PromptSchema.Prompt.make({ text: value.text }),\n\t\t...(value.delivery === undefined ? {} : { delivery: value.delivery }),\n\t\t...(value.id === undefined ? {} : { id: value.id }),\n\t};\n};\n\nconst makeHandle = Effect.fn(\"Session.makeHandle\")(function* (id: SessionSchema.ID) {\n\tconst sessions = yield* SessionStore.Service;\n\tconst control = yield* Control.Service;\n\tconst events = yield* Event.Service;\n\tconst sandboxes = yield* SandboxController.Controller;\n\n\tconst info = Effect.gen(function* () {\n\t\tconst found = yield* sessions.get(id);\n\t\tif (Option.isNone(found)) return yield* new SessionStore.SessionNotFoundError({ sessionId: id });\n\t\tconst row = found.value;\n\t\t// The env is the space's. A missing space or a destroyed env both read as\n\t\t// \"no sandbox\": the handle stays readable (title, directory); running it\n\t\t// is the mount's call, which refuses a removed instance.\n\t\tconst space = Option.getOrUndefined(yield* sessions.space(id));\n\t\tconst sandbox =\n\t\t\tspace === undefined || space.env === SandboxInstanceSchema.ID.local\n\t\t\t\t? undefined\n\t\t\t\t: Option.getOrUndefined(yield* sandboxes.get(space.env));\n\t\treturn {\n\t\t\tid,\n\t\t\ttitle: row.title,\n\t\t\tdirectory: row.directory,\n\t\t\t...(sandbox === undefined ? {} : { sandbox }),\n\t\t};\n\t}).pipe(Effect.withSpan(\"Session.info\"));\n\n\treturn {\n\t\tid,\n\t\tactive: control.active.pipe(Effect.map((active) => active.has(id))),\n\t\tinfo,\n\t\tprompt: (input) => control.prompt({ sessionId: id, ...promptInput(input) }),\n\t\trun: (input) => control.run({ sessionId: id, ...promptInput(input) }),\n\t\twait: () => control.wait(id),\n\t\tresume: () => control.resume(id),\n\t\t// The embedder API keeps its blocking contract: a caller that returns from\n\t\t// `interrupt()` can assume the drain released its mount.\n\t\tinterrupt: () => control.interrupt(id, { awaitSettlement: true }),\n\t\tevents: () =>\n\t\t\tevents\n\t\t\t\t.subscribe()\n\t\t\t\t.pipe(Stream.filter((event) => (event.data as { readonly sessionId?: unknown }).sessionId === id)),\n\t\tpath: () => sessions.path(id),\n\t} satisfies Handle;\n});\n\nexport const create = Effect.fn(\"Session.create\")(function* (input: CreateInput = {}) {\n\tconst sessions = yield* SessionStore.Service;\n\tconst runtime = yield* SessionRuntime.Service;\n\tconst sandboxes = yield* SandboxController.Controller;\n\tconst id = SessionSchema.ID.create();\n\tconst sandboxId = input.sandbox?.id ?? SandboxInstanceSchema.ID.local;\n\t// Mount, then resolve the cwd into its space. The mount is\n\t// what makes the directory mean anything, so resolution happens inside it.\n\tconst location = yield* sandboxes.withMount(\n\t\tsandboxId,\n\t\tEffect.provide(Location.Service.use(Effect.succeed), Location.layerMounted()),\n\t\tinput.directory === undefined ? undefined : { cwd: input.directory },\n\t);\n\tyield* sessions.create({\n\t\tid,\n\t\tspaceId: location.space.id,\n\t\tdirectory: location.directory,\n\t\tslug: id,\n\t\ttitle: input.title ?? \"Session\",\n\t});\n\tyield* runtime.set(id, runtimeBindings(input));\n\treturn yield* makeHandle(id);\n});\n\n/**\n * Move a session to wherever a checkout of the same project now lives — the\n * remote env died and the repo was cloned locally, say. `directory` is\n * resolved into its space exactly like `create`; the session keeps its\n * position under the new root when that absolute path exists there, else it\n * lands on the resolved directory. The transcript is untouched.\n */\nexport const relink = Effect.fn(\"Session.relink\")(function* (input: RelinkInput) {\n\tconst sessions = yield* SessionStore.Service;\n\tconst sandboxes = yield* SandboxController.Controller;\n\tconst sandboxId = input.sandbox?.id ?? SandboxInstanceSchema.ID.local;\n\treturn yield* sandboxes.withMount(\n\t\tsandboxId,\n\t\tEffect.gen(function* () {\n\t\t\tconst location = yield* Location.Service.use(Effect.succeed).pipe(Effect.provide(Location.layerMounted()));\n\t\t\tconst session = yield* sessions.get(input.sessionId);\n\t\t\tconst current = yield* sessions.space(input.sessionId);\n\t\t\tconst rebased =\n\t\t\t\tOption.isSome(session) && Option.isSome(current)\n\t\t\t\t\t? SessionStore.rebaseDirectory(current.value.location, location.space.location, session.value.directory)\n\t\t\t\t\t: undefined;\n\t\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\t\tconst directory =\n\t\t\t\trebased !== undefined && (yield* fs.exists(rebased).pipe(Effect.orElseSucceed(() => false)))\n\t\t\t\t\t? rebased\n\t\t\t\t\t: location.directory;\n\t\t\tyield* sessions.relink({ sessionId: input.sessionId, spaceId: location.space.id, directory });\n\t\t\treturn yield* makeHandle(input.sessionId);\n\t\t}),\n\t\tinput.directory === undefined ? undefined : { cwd: input.directory },\n\t);\n});\n\nexport const get = Effect.fn(\"Session.get\")(function* (sessionId: SessionSchema.ID) {\n\tconst sessions = yield* SessionStore.Service;\n\tconst found = yield* sessions.get(sessionId);\n\tif (Option.isNone(found)) return Option.none<Handle>();\n\treturn Option.some(yield* makeHandle(sessionId));\n});\n\nexport const attach = Effect.fn(\"Session.attach\")(function* (input: AttachInput) {\n\tconst found = yield* get(input.sessionId);\n\tif (Option.isNone(found)) {\n\t\treturn yield* new SessionStore.SessionNotFoundError({ sessionId: input.sessionId });\n\t}\n\tconst runtime = yield* SessionRuntime.Service;\n\t/*\n\t * Merge, not replace. `runtimeBindings` emits only the keys this call names, so a\n\t * bare `attach({ sessionId })` produces `{}` -- and a replace would silently drop the\n\t * tool execution mode, prompt inputs, and model a previous attach established. Bindings are now\n\t * the only config layer, so there is nothing behind them to restore what a wipe took.\n\t */\n\tyield* runtime.update(input.sessionId, runtimeBindings(input));\n\treturn found.value;\n});\n\nexport { AbsolutePath, SessionMessageSchema, SessionSchema };\n\nexport * as Session from \"./session.ts\";\n","import { EventList, EventSchema, optional } from \"@codeworksh/harness/effect\";\nimport { Effect, Schema } from \"effect\";\n\n/**\n * The wire form of an `EventSchema.Payload`. `data` is carried in its encoded\n * form — decoded payloads are not wire-safe (`Schema.Duration`, aikit class\n * transforms) — so clients decode it lazily through their own copy of the\n * registry and can skip types they do not know.\n */\nexport const EventEnvelope = Schema.Struct({\n\tid: EventSchema.ID,\n\ttype: Schema.String,\n\tdurable: optional(Schema.Struct({ aggregateId: Schema.String, seq: Schema.Int, version: Schema.Int })),\n\tmetadata: optional(Schema.Record(Schema.String, Schema.String)),\n\tdata: Schema.Unknown,\n});\nexport type EventEnvelope = typeof EventEnvelope.Type;\n\nexport class UnknownEventTypeError extends Schema.TaggedError<UnknownEventTypeError>()(\"UnknownEventTypeError\", {\n\ttype: Schema.String,\n}) {}\n\n/** The transport's own readiness frame; it has no meaning inside the harness. */\nexport const Connected = EventSchema.define({ type: \"server.connected\", schema: {} });\n\n/** Resolves a published type to the definition that encodes it. */\nexport type Registry = (type: string) => EventSchema.Definition | undefined;\n\n/**\n * What a stock client can decode: the harness's public events plus the frames\n * the transport adds itself. A server may know more than this -- plugins\n * register their own types -- which is exactly why `data` crosses the wire\n * encoded and is decoded lazily, so an unknown type is skipped, not fatal.\n */\nconst core = EventSchema.latest([...EventList.PublicDefinitions, Connected]);\nexport const Core: Registry = (type) => core.get(type);\n\nexport class EncodingError extends Schema.TaggedError<EncodingError>()(\"EventEncodingError\", {\n\ttype: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\nexport const encode = Effect.fn(\"Envelope.encode\")(function* (payload: EventSchema.Payload, registry: Registry = Core) {\n\tconst definition = registry(payload.type);\n\tif (definition === undefined) return yield* new UnknownEventTypeError({ type: payload.type });\n\tconst data = yield* Schema.encodeEffect(definition.data)(payload.data).pipe(\n\t\tEffect.mapError((cause) => new EncodingError({ type: payload.type, cause })),\n\t);\n\treturn {\n\t\tid: payload.id,\n\t\ttype: payload.type,\n\t\t...(payload.durable === undefined ? {} : { durable: payload.durable }),\n\t\t...(payload.metadata === undefined ? {} : { metadata: payload.metadata }),\n\t\tdata,\n\t};\n});\n\nexport const decode = Effect.fn(\"Envelope.decode\")(function* (envelope: EventEnvelope, registry: Registry = Core) {\n\tconst definition = registry(envelope.type);\n\tif (definition === undefined) {\n\t\treturn yield* new UnknownEventTypeError({ type: envelope.type });\n\t}\n\tconst data = yield* Schema.decodeEffect(definition.data)(envelope.data);\n\treturn {\n\t\tid: envelope.id,\n\t\ttype: envelope.type,\n\t\t...(envelope.durable === undefined ? {} : { durable: envelope.durable }),\n\t\t...(envelope.metadata === undefined ? {} : { metadata: envelope.metadata }),\n\t\tdata,\n\t} as EventSchema.Payload;\n});\n\nexport * as Envelope from \"./envelope.ts\";\n","import { Model } from \"@codeworksh/aikit\";\nimport {\n\tControl,\n\tEvent,\n\tLocation,\n\toptional,\n\tPromptSchema,\n\tSandbox,\n\tSandboxError,\n\tSession,\n\tSessionStore,\n} from \"@codeworksh/harness/effect\";\nimport { Schema } from \"effect\";\nimport { Rpc, RpcGroup } from \"effect/unstable/rpc\";\nimport { EncodingError, EventEnvelope } from \"./envelope.ts\";\n\nexport const SandboxInfo = Schema.Struct({\n\tid: Sandbox.SandboxInstance.ID,\n\tdriver: Schema.String,\n\tkind: Sandbox.SandboxInstance.Kind,\n\tproviderResourceId: Schema.OptionFromNullOr(Schema.String),\n\townership: Sandbox.SandboxInstance.Ownership,\n\tstatus: Sandbox.SandboxInstance.Status,\n\tusage: Sandbox.SandboxInstance.Usage,\n\trefCount: Schema.Int,\n\tcreatedAt: Schema.DateFromString,\n\tupdatedAt: Schema.DateFromString,\n});\nexport type SandboxInfo = typeof SandboxInfo.Type;\n\nexport const SessionInfo = Schema.Struct({\n\tid: Session.SessionSchema.ID,\n\ttitle: Schema.String,\n\tdirectory: Schema.String,\n\tsandbox: optional(SandboxInfo),\n});\nexport type SessionInfo = typeof SessionInfo.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tmodel: optional(Schema.Struct({ provider: Schema.String, id: Schema.String })),\n\tthinkingLevel: optional(Schema.Enum(Model.ThinkingLevelEnum)),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nexport const SandboxRef = Sandbox.Selection;\n\nconst SessionErrors = Schema.Union([\n\tSessionStore.SessionNotFoundError,\n\tSessionStore.SessionLinkedSpaceNotFoundError,\n\tSessionStore.RelinkError,\n]);\n\n// Every lifecycle error the sandbox control plane can raise; narrowing per\n// endpoint would misreport what `withMount` and `stop` actually fail with.\nconst SandboxErrors = Schema.Union([\n\tSandboxError.SandboxNotFoundError,\n\tSandboxError.SandboxDriverNotRegisteredError,\n\tSandboxError.SandboxDriverRegistrationError,\n\tSandboxError.SandboxUnsupportedError,\n\tSandboxError.SandboxProviderError,\n\tSandboxError.SandboxUnavailError,\n\tSandboxError.SandboxRemovedError,\n\tSandboxError.SandboxTransitionConflictError,\n\tSandboxError.SandboxBusyError,\n]);\n\nconst LocationErrors = Schema.Union([Location.DirectoryNotFoundError, Location.NotDirectoryError]);\n\nexport const Api = RpcGroup.make(\n\tRpc.make(\"session.create\", {\n\t\tpayload: {\n\t\t\ttitle: optional(Schema.String),\n\t\t\tdirectory: optional(Schema.String),\n\t\t\tsandbox: optional(SandboxRef),\n\t\t\truntime: optional(RuntimeConfig),\n\t\t},\n\t\tsuccess: SessionInfo,\n\t\terror: Schema.Union([SessionErrors, SandboxErrors, LocationErrors]),\n\t}),\n\tRpc.make(\"session.list\", {\n\t\tpayload: {},\n\t\tsuccess: Schema.Array(SessionInfo),\n\t}),\n\tRpc.make(\"session.configure\", {\n\t\tpayload: { sessionId: Session.SessionSchema.ID, runtime: RuntimeConfig },\n\t\tsuccess: SessionInfo,\n\t\terror: SessionStore.SessionNotFoundError,\n\t}),\n\tRpc.make(\"session.info\", {\n\t\tpayload: { sessionId: Session.SessionSchema.ID },\n\t\tsuccess: SessionInfo,\n\t\terror: SessionStore.SessionNotFoundError,\n\t}),\n\tRpc.make(\"session.relink\", {\n\t\tpayload: {\n\t\t\tsessionId: Session.SessionSchema.ID,\n\t\t\tsandbox: optional(SandboxRef),\n\t\t\tdirectory: optional(Schema.String),\n\t\t},\n\t\tsuccess: SessionInfo,\n\t\terror: Schema.Union([SessionErrors, SandboxErrors, LocationErrors]),\n\t}),\n\tRpc.make(\"session.prompt\", {\n\t\tpayload: {\n\t\t\tsessionId: Session.SessionSchema.ID,\n\t\t\ttext: Schema.String,\n\t\t\tdelivery: optional(PromptSchema.Delivery),\n\t\t\tid: optional(Session.SessionMessageSchema.ID),\n\t\t},\n\t\tsuccess: Schema.Void,\n\t\terror: Schema.Union([SessionStore.SessionNotFoundError, Control.PromptConflictError]),\n\t}),\n\tRpc.make(\"session.interrupt\", {\n\t\tpayload: { sessionId: Session.SessionSchema.ID },\n\t\tsuccess: Schema.Struct({ interrupted: Schema.Boolean }),\n\t}),\n\t/**\n\t * Whether a prompt materialized into the conversation. An admitted prompt\n\t * that is still queued has no entry yet, so this is the projection a client\n\t * reconciles against when the volatile stream left it unsure\n\t */\n\tRpc.make(\"session.message\", {\n\t\tpayload: { sessionId: Session.SessionSchema.ID, messageId: Session.SessionMessageSchema.ID },\n\t\tsuccess: Schema.Struct({ found: Schema.Boolean }),\n\t}),\n\tRpc.make(\"session.wait\", {\n\t\tpayload: { sessionId: Session.SessionSchema.ID },\n\t\tsuccess: Schema.Void,\n\t\terror: SessionStore.SessionNotFoundError,\n\t}),\n\tRpc.make(\"sandbox.drivers\", {\n\t\tpayload: {},\n\t\tsuccess: Schema.Array(Schema.Struct({ name: Schema.String, kind: Schema.String })),\n\t}),\n\tRpc.make(\"sandbox.list\", {\n\t\tpayload: {},\n\t\tsuccess: Schema.Array(SandboxInfo),\n\t}),\n\tRpc.make(\"sandbox.create\", {\n\t\tpayload: { driver: Schema.String },\n\t\tsuccess: SandboxInfo,\n\t\terror: SandboxErrors,\n\t}),\n\tRpc.make(\"sandbox.register\", {\n\t\tpayload: { driver: Schema.String, providerResourceId: Schema.String },\n\t\tsuccess: SandboxInfo,\n\t\terror: SandboxErrors,\n\t}),\n\tRpc.make(\"sandbox.stop\", {\n\t\tpayload: { sandboxId: Sandbox.SandboxInstance.ID },\n\t\tsuccess: Schema.Void,\n\t\terror: SandboxErrors,\n\t}),\n\tRpc.make(\"event.subscribe\", {\n\t\tpayload: {},\n\t\tsuccess: EventEnvelope,\n\t\terror: Schema.Union([Event.SubscriptionOverflowError, EncodingError]),\n\t\tstream: true,\n\t}),\n);\n\nexport * as Contract from \"./contract.ts\";\n","import { EventList, type EventSchema, optional, Session } from \"@codeworksh/harness/effect\";\nimport { NodeSocket } from \"@effect/platform-node\";\nimport { Deferred, Effect, Layer, Predicate, Schema, Stream } from \"effect\";\nimport { RpcClient, RpcSerialization } from \"effect/unstable/rpc\";\nimport { Contract } from \"./contract.ts\";\nimport { Envelope } from \"./envelope.ts\";\n\nexport const make = RpcClient.make(Contract.Api);\nexport type Client = Effect.Success<typeof make>;\n\nexport const layer = (url: string) =>\n\tRpcClient.layerProtocolSocket().pipe(\n\t\tLayer.provide(NodeSocket.layerWebSocket(url)),\n\t\tLayer.provide(RpcSerialization.layerNdjson),\n\t);\n\n/** A server-side failure as the client sees it: the category, not the cause. */\nexport class ExecutionError extends Schema.TaggedError<ExecutionError>()(\"Client.ExecutionError\", {\n\ttype: Schema.String,\n\tmessage: Schema.String,\n\tstatus: optional(Schema.Int),\n}) {}\n\n/**\n * Runs one prompt against a server and renders its output.\n *\n * Sessions are shared, so the stream carries other clients' work too and every\n * terminal event has to be attributed before it is believed. A terminal that\n * arrives before our own prompt is promoted belongs to somebody else's drain:\n * it is remembered rather than raised, and forgotten the moment our prompt is\n * promoted. It only becomes our outcome if the session reaches idle having\n * never promoted us -- at which point it is the best explanation available for\n * why our prompt never ran.\n */\nexport const run = Effect.fn(\"Client.run\")(function* <E, R>(\n\trpc: Client,\n\tinput: { sessionId: Session.SessionSchema.ID; text: string },\n\trender: (event: EventSchema.Payload) => Effect.Effect<void, E, R>,\n) {\n\tconst id = Session.SessionMessageSchema.ID.create();\n\tlet admitted = false;\n\tlet promoted = false;\n\tlet settled = false;\n\tlet unattributed: ExecutionError | undefined;\n\t// Raised once a busy period ends without our prompt in it: the session may be\n\t// about to go idle, and only idleness proves our prompt is never running.\n\tconst stalled = yield* Deferred.make<void>();\n\n\tconst terminal = (event: EventSchema.Payload): ExecutionError | undefined => {\n\t\tif (Schema.is(EventList.ExecutionInterrupted)(event))\n\t\t\treturn new ExecutionError({\n\t\t\t\ttype: \"aborted\",\n\t\t\t\tmessage: event.data.reason === \"shutdown\" ? \"Server stopped the session\" : \"Session interrupted\",\n\t\t\t});\n\t\tif (Schema.is(EventList.ExecutionFailed)(event))\n\t\t\treturn new ExecutionError({\n\t\t\t\ttype: event.data.error.type,\n\t\t\t\tmessage: event.data.error.message,\n\t\t\t\t...(event.data.error.status === undefined ? {} : { status: event.data.error.status }),\n\t\t\t});\n\t\treturn undefined;\n\t};\n\n\tconst consume = rpc[\"event.subscribe\"]({}).pipe(\n\t\tStream.mapEffect(\n\t\t\tEffect.fnUntraced(function* (envelope) {\n\t\t\t\tif (envelope.type === Envelope.Connected.type) {\n\t\t\t\t\tyield* rpc[\"session.prompt\"]({ ...input, id, delivery: \"followUp\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst event = yield* Envelope.decode(envelope).pipe(\n\t\t\t\t\tEffect.catchTag(\"UnknownEventTypeError\", () => Effect.void),\n\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tevent === undefined ||\n\t\t\t\t\t!Predicate.hasProperty(event.data, \"sessionId\") ||\n\t\t\t\t\tevent.data.sessionId !== input.sessionId\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tif (Schema.is(EventList.PromptAdmitted)(event) && event.data.messageId === id) admitted = true;\n\t\t\t\tif (Schema.is(EventList.Prompted)(event) && event.data.messageId === id) {\n\t\t\t\t\tpromoted = true;\n\t\t\t\t\t// Our prompt is running after all; whatever ended before it was not ours.\n\t\t\t\t\tunattributed = undefined;\n\t\t\t\t}\n\t\t\t\tif (!admitted) return;\n\n\t\t\t\tconst ended = terminal(event);\n\t\t\t\tconst succeeded = Schema.is(EventList.ExecutionSucceeded)(event);\n\t\t\t\tif (!promoted) {\n\t\t\t\t\tif (ended !== undefined) unattributed = ended;\n\t\t\t\t\t// A busy period that ended without us: wait for idle to find out\n\t\t\t\t\t// whether a successor still picks our prompt up.\n\t\t\t\t\tif (ended !== undefined || succeeded) yield* Deferred.succeed(stalled, undefined);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (ended !== undefined) return yield* ended;\n\t\t\t\tif (succeeded) {\n\t\t\t\t\tsettled = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tyield* render(event);\n\t\t\t}),\n\t\t),\n\t\tStream.takeUntil(() => settled),\n\t\tStream.runDrain,\n\t);\n\n\t// Idle is the cue to reconcile, not the verdict. `wait` follows successors, so\n\t// it resolves only once the session is quiet -- then the projection says\n\t// whether our prompt was ever part of it. A prompt that did run leaves its\n\t// terminal in flight on the same socket, so the consumer is left alone to\n\t// finish; only a prompt that never materialized ends the run early.\n\tlet abandoned = false;\n\tconst reconcile = Deferred.await(stalled).pipe(\n\t\tEffect.andThen(rpc[\"session.wait\"]({ sessionId: input.sessionId })),\n\t\tEffect.andThen(rpc[\"session.message\"]({ sessionId: input.sessionId, messageId: id })),\n\t\tEffect.andThen(({ found }) =>\n\t\t\tfound\n\t\t\t\t? Effect.never\n\t\t\t\t: Effect.sync(() => {\n\t\t\t\t\t\tabandoned = true;\n\t\t\t\t\t}),\n\t\t),\n\t);\n\n\tyield* Effect.raceFirst(consume, reconcile);\n\tif (settled) return;\n\tif (abandoned)\n\t\treturn yield* unattributed ?? new ExecutionError({ type: \"unknown\", message: \"Prompt was not promoted\" });\n\treturn yield* new ExecutionError({\n\t\ttype: \"transport.disconnected\",\n\t\tmessage: \"Event stream ended before the prompt finished; its output was not rendered\",\n\t});\n});\n\nexport * as Client from \"./client.ts\";\n","import type { Message } from \"@codeworksh/aikit\";\nimport { Effect } from \"effect\";\n\nexport interface UsageSummary {\n\treadonly turns: number;\n\treadonly provider?: string;\n\treadonly model?: string;\n\treadonly input: number;\n\treadonly output: number;\n\treadonly reasoning: number;\n\treadonly cacheRead: number;\n\treadonly cacheWrite: number;\n\treadonly totalTokens: number;\n\treadonly cost: number;\n}\n\nexport const emptyUsage: UsageSummary = {\n\tturns: 0,\n\tinput: 0,\n\toutput: 0,\n\treasoning: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: 0,\n};\n\nexport const addUsage = (summary: UsageSummary, message: Message.AssistantMessage): UsageSummary => ({\n\tturns: summary.turns + 1,\n\tprovider: message.provider.id,\n\tmodel: message.responseModel ?? message.model,\n\tinput: summary.input + message.usage.input,\n\toutput: summary.output + message.usage.output,\n\treasoning: summary.reasoning + (message.usage.reasoning ?? 0),\n\tcacheRead: summary.cacheRead + message.usage.cacheRead,\n\tcacheWrite: summary.cacheWrite + message.usage.cacheWrite,\n\ttotalTokens: summary.totalTokens + message.usage.totalTokens,\n\tcost: summary.cost + message.usage.cost.total,\n});\n\nconst number = new Intl.NumberFormat(\"en-US\");\nconst row = (label: string, value: string) => `${label.padEnd(9)}${value}\\n`;\n\nconst formatCost = (cost: number): string => `$${cost.toFixed(cost > 0 && cost < 0.01 ? 6 : 4)}`;\n\nexport const divider = (label: string, columns = 72): string => {\n\tconst width = Math.min(100, Math.max(32, columns));\n\tconst start = `── ${label} `;\n\treturn `${start}${\"─\".repeat(Math.max(2, width - start.length))}\\n`;\n};\n\nexport const header = (input: {\n\treadonly sessionId: string;\n\treadonly sandbox: string;\n\treadonly directory: string;\n\treadonly columns?: number;\n}): string =>\n\t`${row(\"session\", input.sessionId)}${row(\"sandbox\", `${input.sandbox} · ${input.directory}`)}\\n${divider(\n\t\t\"response\",\n\t\tinput.columns,\n\t)}`;\n\nexport const usage = (summary: UsageSummary, columns?: number): string => {\n\tconst turns = `${summary.turns} ${summary.turns === 1 ? \"turn\" : \"turns\"}`;\n\tconst model =\n\t\tsummary.provider === undefined || summary.model === undefined\n\t\t\t? \"unknown\"\n\t\t\t: `${summary.provider}/${summary.model}`;\n\tconst reasoning = summary.reasoning === 0 ? \"\" : ` · ${number.format(summary.reasoning)} reasoning`;\n\treturn `${divider(\"usage\", columns)}${row(\"model\", model)}${row(\n\t\t\"tokens\",\n\t\t`${number.format(summary.input)} input · ${number.format(summary.output)} output${reasoning} · ${number.format(\n\t\t\tsummary.totalTokens,\n\t\t)} total`,\n\t)}${row(\"cache\", `${number.format(summary.cacheRead)} read · ${number.format(summary.cacheWrite)} write`)}${row(\n\t\t\"cost\",\n\t\t`${formatCost(summary.cost)} · ${turns}`,\n\t)}`;\n};\n\nexport const writeOut = (value: string) => Effect.sync(() => void process.stdout.write(value));\nexport const writeError = (value: string) => Effect.sync(() => void process.stderr.write(value));\nexport const terminalColumns = () => (process.stderr.isTTY ? (process.stderr.columns ?? 72) : 72);\n","import { Plugin, Runner, SandboxError, Settings } from \"@codeworksh/harness/effect\";\nimport { SandboxProvider } from \"@codeworksh/harness/sandbox\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { Client } from \"../server/client.ts\";\nimport { writeError } from \"./output.ts\";\n\n/** Bad flag or argument combinations the parser cannot express on its own. */\nexport class InvalidInputError extends Schema.TaggedError<InvalidInputError>()(\"CLI.InvalidInputError\", {\n\tmessage: Schema.String,\n}) {}\n\nexport class ModelgenError extends Schema.TaggedError<ModelgenError>()(\"CLI.ModelgenError\", {\n\tcause: Schema.Defect(),\n}) {}\n\n/**\n * Every failure a command handler may surface to the runtime. Harness failures are\n * rendered inside the handler that owns them, so only the CLI's own errors reach\n * the top-level renderer.\n */\nexport type CommandError = InvalidInputError | ModelgenError;\n\nconst isInvalidInputError = Schema.is(InvalidInputError);\nconst isModelgenError = Schema.is(ModelgenError);\nconst isProviderError = Schema.is(Runner.ProviderError);\nconst isModelCatalogError = Schema.is(Runner.ModelCatalogError);\nconst isModelNotFoundError = Schema.is(Runner.ModelNotFoundError);\nconst isLLMStreamError = Schema.is(Runner.LLMStreamError);\nconst isSandboxProviderError = Schema.is(SandboxProvider.SandboxProviderError);\nconst isPluginPreparationError = Schema.is(Plugin.PreparationError);\nconst isPluginInstallError = Schema.is(Plugin.InstallError);\nconst isSettingsError = Schema.is(Settings.SettingsError);\nconst isSandboxDriverNotRegisteredError = Schema.is(SandboxError.SandboxDriverNotRegisteredError);\nconst isSandboxDriverRegistrationError = Schema.is(SandboxError.SandboxDriverRegistrationError);\nconst isExecutionError = Schema.is(Client.ExecutionError);\n\nconst providerCategory = (reason: Runner.ProviderFailureReason): string => {\n\tswitch (reason._tag) {\n\t\tcase \"Runner.ProviderAuthenticationError\":\n\t\t\treturn \"authentication\";\n\t\tcase \"Runner.ProviderConfigurationError\":\n\t\t\treturn \"configuration\";\n\t\tcase \"Runner.ProviderAuthorizationError\":\n\t\t\treturn \"authorization\";\n\t\tcase \"Runner.ProviderModelUnavailableError\":\n\t\t\treturn \"model_unavailable\";\n\t\tcase \"Runner.ProviderRateLimitError\":\n\t\t\treturn \"rate_limited\";\n\t\tcase \"Runner.ProviderQuotaError\":\n\t\t\treturn \"quota\";\n\t\tcase \"Runner.ProviderInvalidRequestError\":\n\t\t\treturn \"invalid_request\";\n\t\tcase \"Runner.ProviderContentPolicyError\":\n\t\t\treturn \"content_policy\";\n\t\tcase \"Runner.ProviderTimeoutError\":\n\t\t\treturn \"timeout\";\n\t\tcase \"Runner.ProviderTransportError\":\n\t\t\treturn \"transport\";\n\t\tcase \"Runner.ProviderUnavailableError\":\n\t\t\treturn \"provider_unavailable\";\n\t\tcase \"Runner.ProviderInvalidResponseError\":\n\t\t\treturn \"invalid_response\";\n\t\tcase \"Runner.ProviderUnknownError\":\n\t\t\treturn \"provider\";\n\t}\n};\n\nconst credentialHint = (provider: string): string => {\n\tswitch (provider) {\n\t\tcase \"openrouter\":\n\t\t\treturn \"set OPENROUTER_API_KEY and retry\";\n\t\tcase \"openai\":\n\t\t\treturn \"set OPENAI_API_KEY and retry\";\n\t\tcase \"anthropic\":\n\t\t\treturn \"set ANTHROPIC_API_KEY and retry\";\n\t\tcase \"google\":\n\t\t\treturn \"set GOOGLE_GENERATIVE_AI_API_KEY and retry\";\n\t\tcase \"xai\":\n\t\t\treturn \"set XAI_API_KEY and retry\";\n\t\tdefault:\n\t\t\treturn `configure credentials for provider \"${provider}\" and retry`;\n\t}\n};\n\nconst providerHint = (error: Runner.ProviderError): string | undefined => {\n\tswitch (error.reason._tag) {\n\t\tcase \"Runner.ProviderAuthenticationError\":\n\t\t\treturn error.reason.authentication === \"missing\"\n\t\t\t\t? credentialHint(error.provider)\n\t\t\t\t: `check the credentials configured for provider \"${error.provider}\"`;\n\t\tcase \"Runner.ProviderAuthorizationError\":\n\t\t\treturn \"check that the credential can access this model and endpoint\";\n\t\tcase \"Runner.ProviderModelUnavailableError\":\n\t\t\treturn \"check the provider model ID and whether your account can access it\";\n\t\tcase \"Runner.ProviderRateLimitError\":\n\t\t\treturn error.reason.retryAfter === undefined\n\t\t\t\t? \"retry after the provider rate-limit window resets\"\n\t\t\t\t: `retry in about ${Math.ceil(Duration.toMillis(error.reason.retryAfter) / 1_000)} seconds`;\n\t\tcase \"Runner.ProviderQuotaError\":\n\t\t\treturn \"check the provider account quota or billing balance\";\n\t\tcase \"Runner.ProviderTimeoutError\":\n\t\tcase \"Runner.ProviderTransportError\":\n\t\tcase \"Runner.ProviderUnavailableError\":\n\t\t\treturn error.isRetryable ? \"this failure is retryable\" : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n};\n\nconst unknownMessage = (error: unknown): string => {\n\tif (error instanceof Error && error.message.trim().length > 0) return error.message;\n\tif (typeof error === \"string\" && error.trim().length > 0) return error;\n\tif (typeof error === \"object\" && error !== null && \"_tag\" in error) return String(error._tag);\n\treturn \"the command failed for an unknown reason\";\n};\n\n/**\n * What the reader can do about a reference that failed to prepare. A plugin list is\n * usually hand-written in a settings file, so the phase is worth translating.\n */\nconst pluginHint = (phase: Plugin.PreparationError[\"phase\"]): string => {\n\tswitch (phase) {\n\t\tcase \"source\":\n\t\t\treturn \"check the spelling; a path entry starts with `./`, `../`, `~/`, or `/`, and anything else is a package\";\n\t\tcase \"install\":\n\t\t\treturn \"check the package name and version, and that the registry is reachable\";\n\t\tcase \"import\":\n\t\t\treturn \"the module failed to load; import it directly to see its own error\";\n\t\tcase \"definition\":\n\t\t\treturn \"a plugin module must default-export one object with a `setup` and a `vendor.domain.name` id\";\n\t}\n};\n\nconst settingsHint = (reason: Settings.SettingsError[\"reason\"]): string => {\n\tswitch (reason) {\n\t\tcase \"read\":\n\t\t\treturn \"the file exists but could not be read; check that it is a file and readable\";\n\t\tcase \"parse\":\n\t\t\treturn \"the file is not valid JSON; the location above is where parsing stopped\";\n\t\tcase \"decode\":\n\t\t\treturn \"the key above holds a value this setting does not accept\";\n\t}\n};\n\n/** Render typed SDK errors for humans without exposing Effect causes or provider payloads. */\nexport const renderError = (error: unknown): string => {\n\tif (isSandboxDriverNotRegisteredError(error)) {\n\t\treturn `error: sandbox driver \"${error.driver}\" is not registered (available: ${error.registered?.join(\", \") ?? \"none\"})\\n`;\n\t}\n\tif (isSandboxDriverRegistrationError(error)) {\n\t\treturn `error: ${error.reason}\\n`;\n\t}\n\tif (isInvalidInputError(error)) {\n\t\treturn `error: ${error.message}\\n`;\n\t}\n\tif (isModelgenError(error)) {\n\t\treturn (\n\t\t\t[\"error[model-catalog]: failed to generate the model catalog\", \"hint: check the output path and retry\"].join(\n\t\t\t\t\"\\n\",\n\t\t\t) + \"\\n\"\n\t\t);\n\t}\n\tif (isSandboxProviderError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error: SandboxProviderError - ${error.sanitized.message}`,\n\t\t\t\t`driver: ${error.driver}`,\n\t\t\t\t`operation: ${error.operation}`,\n\t\t\t\t...(error.sanitized.code === undefined ? [] : [`code: ${error.sanitized.code}`]),\n\t\t\t\t...(error.stack === undefined ? [] : [\"traceback:\", error.stack]),\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isPluginPreparationError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[plugin]: failed to prepare plugin \"${error.reference}\"`,\n\t\t\t\t`phase: ${error.phase}`,\n\t\t\t\t...(error.id === undefined ? [] : [`id: ${error.id}`]),\n\t\t\t\t`detail: ${unknownMessage(error.cause)}`,\n\t\t\t\t`hint: ${pluginHint(error.phase)}`,\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isSettingsError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[settings]: ${error.path}`,\n\t\t\t\t`reason: ${error.reason}`,\n\t\t\t\t`detail: ${error.detail}`,\n\t\t\t\t`hint: ${settingsHint(error.reason)}`,\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isPluginInstallError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[plugin-install]: ${unknownMessage(error.cause)}`,\n\t\t\t\t\"hint: check the package name and version, and that the registry is reachable\",\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isProviderError(error)) {\n\t\tconst hint = providerHint(error);\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[${providerCategory(error.reason)}]: ${error.message}`,\n\t\t\t\t`provider: ${error.provider}`,\n\t\t\t\t`model: ${error.model}`,\n\t\t\t\t...(error.reason.requestId === undefined ? [] : [`request: ${error.reason.requestId}`]),\n\t\t\t\t...(hint === undefined ? [] : [`hint: ${hint}`]),\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isModelCatalogError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[model-catalog]: ${error.message}`,\n\t\t\t\t\"hint: run `codework models generate` or set CODEWORK_MODELS_FILE to a generated catalog\",\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isModelNotFoundError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\t`error[model-not-found]: ${error.message}`,\n\t\t\t\t\"hint: check the provider/model IDs in models.gen.json or regenerate the catalog\",\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\tif (isLLMStreamError(error)) {\n\t\treturn `error[stream]: ${error.message}\\n`;\n\t}\n\t// A remote run has only the category the server published; render it the same\n\t// way a local typed error is rendered, minus the detail that stayed server-side.\n\tif (isExecutionError(error)) {\n\t\treturn (\n\t\t\t[\n\t\t\t\terror.type === \"aborted\" ? `error: ${error.message}` : `error[${error.type}]: ${error.message}`,\n\t\t\t\t...(error.status === undefined ? [] : [`status: ${error.status}`]),\n\t\t\t].join(\"\\n\") + \"\\n\"\n\t\t);\n\t}\n\treturn `error: ${unknownMessage(error)}\\n`;\n};\n\nexport const reportFailure = (error: unknown) =>\n\twriteError(renderError(error)).pipe(\n\t\tEffect.andThen(\n\t\t\tEffect.sync(() => {\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t}),\n\t\t),\n\t);\n"],"x_google_ignoreList":[68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,152],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,kCAAkB,IAAI,QAA2D;AAEvF,MAAM,qBAAwC,WAA2D;CACxG,MAAM,SAAS,gBAAgB,IAAI,MAAM;CACzC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,WAAW,cAAc,QAAQ,MAAM;CAC7C,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACR;AAEA,MAAM,kBAAkB,UAGV;CACb,IAAI,MAAM,cAAc,OAAO,MAAM,aAAa,UAAU,CAAC;CAC7D,MAAM,WAAW,MAAM,QAAQ;CAC/B,OAAO,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK,IAAI,IAAI;AACxD;AAEA,MAAM,uBAA0C,QAAW,OAAgB,UAA6B;CACvG,MAAM,YAAY,kBAAkB,MAAM;CAC1C,IAAI,UAAU,MAAM,KAAK,GAAG,OAAO;CAEnC,MAAM,GAAG,UAAU,UAAU,OAAO,KAAK;CACzC,MAAM,UAAU,OAAO,KAAK,UAAU,MAAM,eAAe,KAAK,EAAE,IAAI,MAAM,SAAS,CAAC,CAAC,KAAK,IAAI,KAAK;CACrG,MAAM,IAAI,MAAM,yBAAyB,MAAM,IAAI,SAAS;AAC7D;;AAGA,MAAa,wBAAwB,OAAgB,UACpD,oBAAoB,QAAQ,eAAe,OAAO,KAAK;AAExD,MAAa,4BAA4B,OAAgB,UACxD,oBAAoB,QAAQ,mBAAmB,OAAO,KAAK;AAE5D,MAAa,iCAAiC,OAAgB,UAC7D,oBAAoB,QAAQ,wBAAwB,OAAO,KAAK;AAEjE,MAAa,qCAAqC,OAA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