@codeworksh/harness 0.0.1-dev.20260907151726 → 0.0.1-dev.20260917115353

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/effect.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"effect.mjs","names":["ID","Service","make","build","layer","layer","Str","Global.resolve","defaultLayer","reasonOf","ID","define","Model","EventSchema.ID","SandboxInstance.ID","SandboxInstance.Kind","SandboxInstance.Ownership","SandboxInstance.Status","SandboxInstance.PersistedError","SessionSchema.IDFromDb","ID","SessionSchema.ID","SessionMessageSchema.ID","PromptSchema.Prompt","PromptSchema.Delivery","EventSchema.define","EventSchema.AikitAssistantMessage","ToolProgress","EventSchema.AikitToolCallTerminalPart","EventSchema.inventory","EventSchema.durable","EventList.DurableDefinitions","Schema","EffectSchema","Service","layer","EventSchema.versionedType","EventManifest.Manifest","Service","SessionSchema.AssistantEnvelopeUsage","SessionSchema.MessageEnvelopeIdentity","decodeCompactionData","SessionSchema.CompactionData","decodeJsonObject","SessionSchema.JsonObject","encodeJsonObject","layer","Event.Service","SandboxInstance.toField","EventList.SessionForked","Database.defaultLayer","SessionSchema.JsonObject","parseJson","SessionSchema.CompactionData","Service","layer","Session.Service","Session.SessionNotFoundError","reserved","make","SandboxDriver.erase","layer","Buffer","make","SandboxFileSystem.isNotFoundError","layer","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","layer","Local.Vfs","Process.host","layer","make","SandboxInstance.ID","Local.layer","HostExe.layer","EnvNodeJSDefault.layer","SandboxInstance.PersistedError","encodeUnknownJson","providerError","make","SandboxDriverRegistry.Registry","SandboxStore.make","SandboxIO.resolveMountCwd","SandboxInstance.isMountable","SandboxIO.FileSystem","SandboxIO.Shell","SandboxIO.Current","SandboxFileSystem.withCwd","shellWithCwd","layer","Buffer","make","Seed.initialize","Buffer","make","transport","Local.Vfs","Local.layer","EnvBash.transport","Local.Vfs","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","SandboxDriver.RuntimeConfigBase","make","providerError","SandboxDriver.driver","EnvInMemory.make","make","Seed.initialize","Local.Vfs","layer","Process.host","Process.unsupported","SandboxDriver.AbsolutePath","make","EnvSqldb.layer","providerError","SandboxDriver.driver","EnvSqldb.make","Service","layer","SandboxIO.FileSystem","SandboxIO.Shell","SandboxFs.up","path","Service","layer","SandboxIO.FileSystem","SandboxFs.up","SandboxFs.isDirectory","SandboxFs.readFileSafe","SandboxInstance.ID","Info","Hash.fast","Service","layer","SandboxIO.FileSystem","Git.Service","ProjectCopy.Service","SandboxIO.Current","SandboxInstance.toColumn","SandboxInstance.fromField","path","Model","SandboxInstance.toField","Ref","SandboxInstance.ID","ProjectSchema.ID","ProjectSchema.Vcs","Service","layer","SandboxIO.Current","Project.Service","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","make","layer","RunnerExecution.Service","Session.Service","SandboxController.Controller","Runner.Service","RunCoordinator.make","SandboxInstance.fromField","SandboxIO.Current","SandboxIO.FileSystem","Runner.SandboxDirectoryNotFoundError","Git.layer","ProjectCopy.layer","Location.layer","make","Event.Service","Runner.LLMStreamError","EventList.LLMStarted","EventList.LLMTextStart","EventList.LLMTextDelta","EventList.LLMTextEnd","EventList.LLMThinkingStart","EventList.LLMThinkingDelta","EventList.LLMThinkingEnd","EventList.LLMEnded","EventList.LLMFailed","normalize","AikitModel","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","Runner.ModelCatalogError","Runner.ModelNotFoundError","aikitStream","make","Service","layer","Global.appConfigDir","normalize","Service","layer","Global.Service","make","make","register","Tool.define","Tool.implement","endTime","make","Executor.make","layer","SessionRuntime.Service","Settings.Service","SandboxIO.Current","Location.Service","SandboxIO.Shell","Tool.provide","makeRegistry","StatePrompt.build","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","run","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","Global.resolve","Database.locationConfig","Global.layerWith","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","SandboxDriverRegistry.Registry","create","SandboxController.Controller","get","SessionStore.Service","Control.Service","Event.Service","SandboxController.Controller","SessionStore.SessionNotFoundError","SandboxInstanceSchema.fromField","create","SessionRuntime.Service"],"sources":["../../src/session/schema.ts","../../src/host.ts","../../src/global.ts","../../src/db/migrations.ts","../../src/db/db.ts","../../src/event/schema.ts","../../src/session/prompt/schema.ts","../../src/db/schema.sql.ts","../../src/session/message/schema.ts","../../src/event/list.ts","../../src/event/manifest.ts","../../src/event/event.ts","../../src/session/session.ts","../../src/context/errors.ts","../../src/context/codec.ts","../../src/context/assemble.ts","../../src/context/context.ts","../../src/sandbox/fs/util.ts","../../src/sandbox/registry.ts","../../src/sandbox/utils/process.ts","../../src/sandbox/fs/vfs.ts","../../src/sandbox/fs/nodejs.ts","../../src/sandbox/shell/host.ts","../../src/sandbox/store.ts","../../src/sandbox/control.ts","../../src/sandbox/utils/seed.ts","../../src/sandbox/fs/inmemory.ts","../../src/sandbox/shell/justbash.ts","../../src/sandbox/virtual.ts","../../src/sandbox/drivers/memory.ts","../../src/sandbox/fs/sqldb.ts","../../src/sandbox/drivers/sqldb.ts","../../src/git/git.ts","../../src/util/hash.ts","../../src/project/copy.ts","../../src/project/schema.ts","../../src/project/project.ts","../../src/location/location.ts","../../src/runner/run.ts","../../src/runner/execution.ts","../../src/session/input/schema.ts","../../src/session/input/input.ts","../../src/control.ts","../../src/runner/coordinator.ts","../../src/runner/execute.ts","../../src/runner/event.ts","../../src/settings/merge.ts","../../src/settings/schema.ts","../../src/settings/resolve.ts","../../src/runner/llm.ts","../../src/session/runtime.ts","../../src/settings/settings.ts","../../src/tools/truncate.ts","../../src/tools/accumulator.ts","../../src/tools/progress.ts","../../src/tools/shell.ts","../../src/tools/error.ts","../../src/tools/tool.ts","../../src/tools/bash.ts","../../src/tools/executor.ts","../../src/tools/registry.ts","../../src/state/prompt.ts","../../src/state/state.ts","../../src/runner/loop.ts","../../src/sandbox/loader.ts","../../src/session/projector.ts","../../src/session/live.ts","../../src/effect/harness.ts","../../src/effect/sandbox.ts","../../src/effect/session.ts","../../src/effect/tools.ts"],"sourcesContent":["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// 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 { NodeFileSystem, NodePath } from \"@effect/platform-node\";\nimport { 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","import { Config, Context, Effect, Layer } from \"effect\";\nimport * as os from \"node:os\";\nimport { fileSystem } from \"./host.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\nfunction expandHome(value: string) {\n\tif (value === \"~\") return os.homedir();\n\tif (value.startsWith(\"~/\")) return posix.join(os.homedir(), value.slice(2));\n\treturn posix.resolve(value);\n}\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 config: 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\tconfig: input.config ?? posix.join(home, \"config\"),\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.config, { 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 project_directory and\n\t\t// session because both reference 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\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\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// Nullable, NULL = the host. RESTRICT, not CASCADE: destroying\n\t\t// infrastructure tombstones the sandbox row rather than deleting it, so\n\t\t// history keeps a valid reference. The FK is skipped on NULL, so a host\n\t\t// directory can be written before any namespace is registered.\n\t\tyield* sql`\n\t\t\tCREATE TABLE project_directory (\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 CASCADE,\n\t\t\t\tdirectory TEXT NOT NULL,\n\t\t\t\ttype TEXT NOT NULL,\n\t\t\t\tsandbox_instance_id TEXT\n\t\t\t\t\tREFERENCES sandbox_instance(id) ON UPDATE CASCADE ON DELETE RESTRICT\n\t\t\t\t\tCHECK (sandbox_instance_id IS NULL OR sandbox_instance_id <> 'local'),\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// SQLite treats NULLs as distinct in a unique index, so (project, NULL, '/repo')\n\t\t// would insert twice. Coalescing to the reserved id makes the\n\t\t// index read as what it means.\n\t\tyield* sql`\n\t\t\tCREATE UNIQUE INDEX project_directory_project_directory_idx\n\t\t\tON project_directory (project_id, COALESCE(sandbox_instance_id, 'local'), directory)\n\t\t`;\n\n\t\tyield* sql`\n\t\t\tCREATE TABLE session (\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 CASCADE,\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\tsandbox_instance_id TEXT\n\t\t\t\t\tREFERENCES sandbox_instance(id) ON UPDATE CASCADE ON DELETE RESTRICT\n\t\t\t\t\tCHECK (sandbox_instance_id IS NULL OR sandbox_instance_id <> 'local'),\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 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 enabled by the client itself.)\nconst setup = Effect.gen(function* () {\n\tconst sql = yield* SqlClient.SqlClient;\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.transformOrFail(decodeAikitAssistantMessage),\n\t\tencode: SchemaGetter.transformOrFail(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.transformOrFail(decodeAikitToolCallTerminalPart),\n\t\tencode: SchemaGetter.transformOrFail(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 { 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 { Model } from \"effect/unstable/schema\";\nimport { EventSchema } from \"../event/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\";\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\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\nexport class ProjectDirectoryRow extends Model.Class<ProjectDirectoryRow>(\"ProjectDirectoryRow\")({\n\tid: Schema.String,\n\tprojectId: Schema.String,\n\tdirectory: AbsolutePath,\n\ttype: Schema.Literals([\"main\", \"root\", \"gitworktree\"]),\n\t// Nullable: NULL is the host. Service-level code sees a plain ID through\n\t// SandboxInstance.toColumn/fromColumn and never branches on the host.\n\tsandboxInstanceId: Model.FieldOption(SandboxInstance.ID),\n\t...Timestamps,\n}) {}\n\nexport class SessionRow extends Model.Class<SessionRow>(\"SessionRow\")({\n\tid: SessionSchema.IDFromDb,\n\tprojectId: Schema.String,\n\tparentId: Model.FieldOption(SessionSchema.IDFromDb),\n\tslug: Schema.String,\n\tdirectory: AbsolutePath,\n\ttitle: Schema.String,\n\ttag: Model.FieldOption(Schema.String),\n\tmetadata: Model.FieldOption(Model.JsonFromString(Metadata)),\n\t// Nullable: NULL is the host (§4), so a session can be written before any\n\t// namespace is registered — the foreign key is skipped on NULL.\n\tsandboxInstanceId: Model.FieldOption(SandboxInstance.ID),\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 { Schema } from \"effect\";\nimport { DateTimeUtcFromMillis, NonNegativeInt } from \"../schema.ts\";\nimport { SessionMessageSchema } from \"../session/message/schema.ts\";\nimport { PromptSchema } from \"../session/prompt/schema.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\n// confirmed\nexport const PromptAdmitted = EventSchema.define({\n\ttype: \"session.next.prompt.admitted\",\n\t...durableOptions,\n\tschema: PromptFields,\n});\nexport type PromptAdmitted = typeof PromptAdmitted.Type;\n\n// confirmed\nexport const Prompted = EventSchema.define({\n\ttype: \"session.next.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\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, 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\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 interface Interface {\n\treadonly latestSequence: (aggregateId: string) => Effect.Effect<number>;\n\treadonly readAggregate: <A>(input: ReadAggregateInput<A>) => Effect.Effect<ReadAggregateResult<A>>;\n\t/**\n\t * Appends one event. Durable definitions are assigned the aggregate's next\n\t * sequence, projected, and stored in a single transaction; the returned\n\t * payload carries that sequence in `durable`.\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 projector for one event type. Projectors run inside the commit\n\t * transaction, so a failing projector rolls the event back with it.\n\t */\n\treadonly project: <D extends Definition>(definition: D, projector: Subscriber<D>) => Effect.Effect<void>;\n\t/**\n\t * Live stream of one event type.\n\t *\n\t * This is the only way to read a non-durable definition -- stream deltas and\n\t * block boundaries. They never reach a projector: projectors run inside the\n\t * commit, and a live event has no commit, so registering one for a live type\n\t * compiles and silently never fires.\n\t */\n\treadonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>>;\n\t/** Every event, durable and live alike, in publish order. */\n\treadonly all: () => Stream.Stream<Payload>;\n\t/** Durable catch-up followed by the process-local event tail for one session.\n\t * TODO(sanchitrk):\n\t * revisite once's we implement durable streams, a common channel for IO output,\n\t * chances are we wont't need this anymore?\n\t */\n\treadonly stream: (input: { readonly sessionId: string; readonly after?: number }) => Stream.Stream<Payload>;\n\t/**\n\t * Callback form of {@link all}, returning its own removal. A listener runs\n\t * after the commit for a durable event, and its failures are logged rather\n\t * than surfaced -- the event already happened, so a watcher cannot undo it.\n\t */\n\treadonly listen: (listener: Subscriber) => Effect.Effect<Unsubscribe>;\n\t/**\n\t * Moves an aggregate's head to at least `seq`, so the next published event\n\t * lands above it. Two callers need this: a fork, reserving [0..seq] for\n\t * copied entries, and any write that takes a position without going through\n\t * an event -- otherwise the head still points below state that already\n\t * exists, and the next event collides with it.\n\t *\n\t * A sequence is a version position, not a row count, so declaring an\n\t * aggregate \"already at version N\" is legal. Never rewinds: a lower `seq`\n\t * than the current head is a no-op.\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\tall: yield* PubSub.unbounded<Payload>(),\n\t\t\ttyped: new Map<string, PubSub.PubSub<Payload>>(),\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* PubSub.shutdown(pubsub.all);\n\t\t\t\tyield* Effect.forEach(pubsub.typed.values(), PubSub.shutdown, { discard: true });\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\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\tconst typed = pubsub.typed.get(event.type);\n\t\t\t\tif (typed) yield* PubSub.publish(typed, event);\n\t\t\t\tyield* PubSub.publish(pubsub.all, event);\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\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, types, limit }) =>\n\t\t\t\tsql`\n SELECT * FROM event\n WHERE aggregate_id = ${aggregateId} AND seq > ${after} AND ${sql.in(\"type\", types)}\n ORDER BY seq ASC\n LIMIT ${limit}\n `,\n\t\t});\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 after = input.after ?? -1;\n\t\t\tconst rows = yield* selectAggregateEvents({\n\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\tafter,\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 decode = Schema.decodeUnknownEffect(input.manifest.schema);\n\t\t\t// The `type` column stores the versioned type; the envelope carries the\n\t\t\t// bare type, so it is mapped back through the definition. A row that no\n\t\t\t// longer decodes is a broken store, not a recoverable read.\n\t\t\tconst events = yield* Effect.forEach(page, (row) => {\n\t\t\t\tconst definition = input.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\treturn { events, hasMore: rows.length > input.limit };\n\t\t}, Effect.orDie);\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\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\t// One pubsub per type, created on first subscribe. A type nobody watches\n\t\t// costs nothing, and `notify` skips it.\n\t\tconst getOrCreate = (definition: Definition) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst existing = pubsub.typed.get(definition.type);\n\t\t\t\tif (existing) return existing;\n\t\t\t\tconst created = yield* PubSub.unbounded<Payload>();\n\t\t\t\tpubsub.typed.set(definition.type, created);\n\t\t\t\treturn created;\n\t\t\t});\n\n\t\tconst subscribe = <D extends Definition>(definition: D): Stream.Stream<Payload<D>> =>\n\t\t\tStream.unwrap(getOrCreate(definition).pipe(Effect.map((created) => Stream.fromPubSub(created)))).pipe(\n\t\t\t\tStream.map((event) => event as Payload<D>),\n\t\t\t);\n\n\t\tconst streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(pubsub.all);\n\n\t\tconst stream = (input: { readonly sessionId: string; readonly after?: number }): Stream.Stream<Payload> => {\n\t\t\tconst forSession = (event: Payload) =>\n\t\t\t\t(event.data as { readonly sessionId?: unknown }).sessionId === input.sessionId;\n\t\t\tconst after = input.after;\n\t\t\tif (after === undefined) return streamAll().pipe(Stream.filter(forSession));\n\n\t\t\treturn Stream.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t// Subscribe before the first journal read. The subscription's unbounded\n\t\t\t\t\t// queue buffers durable and live-only events across the replay boundary.\n\t\t\t\t\tconst subscription = yield* PubSub.subscribe(pubsub.all);\n\t\t\t\t\tconst watermark = yield* Ref.make(after);\n\t\t\t\t\tconst history = Stream.paginate(\n\t\t\t\t\t\tafter,\n\t\t\t\t\t\tEffect.fn(\"Event.stream.history\")(function* (after) {\n\t\t\t\t\t\t\tconst page = yield* readAggregate({\n\t\t\t\t\t\t\t\taggregateId: input.sessionId,\n\t\t\t\t\t\t\t\tafter,\n\t\t\t\t\t\t\t\tlimit: 100,\n\t\t\t\t\t\t\t\tmanifest: EventManifest.Manifest,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst last = page.events.at(-1);\n\t\t\t\t\t\t\tconst next =\n\t\t\t\t\t\t\t\tpage.hasMore && last?.durable !== undefined\n\t\t\t\t\t\t\t\t\t? Option.some(last.durable.seq)\n\t\t\t\t\t\t\t\t\t: Option.none<number>();\n\t\t\t\t\t\t\treturn [page.events, next] as const;\n\t\t\t\t\t\t}),\n\t\t\t\t\t).pipe(\n\t\t\t\t\t\tStream.map((event) => event as Payload),\n\t\t\t\t\t\tStream.tap((event) => {\n\t\t\t\t\t\t\tconst seq = event.durable?.seq;\n\t\t\t\t\t\t\treturn seq === undefined\n\t\t\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t\t\t: Ref.update(watermark, (current) => Math.max(current, seq));\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\tconst tail = Stream.fromSubscription(subscription).pipe(\n\t\t\t\t\t\tStream.filter(forSession),\n\t\t\t\t\t\tStream.filterEffect((event) => {\n\t\t\t\t\t\t\tconst seq = event.durable?.seq;\n\t\t\t\t\t\t\treturn seq === undefined\n\t\t\t\t\t\t\t\t? Effect.succeed(true)\n\t\t\t\t\t\t\t\t: Ref.get(watermark).pipe(Effect.map((replayed) => seq > replayed));\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn history.pipe(Stream.concat(tail));\n\t\t\t\t}),\n\t\t\t);\n\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\tpublish,\n\t\t\tsubscribe,\n\t\t\tall: streamAll,\n\t\t\tstream,\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, 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\ttype ToolStatus,\n\ttoolStatuses,\n} from \"../db/schema.sql.ts\";\nimport { Event } from \"../event/event.ts\";\nimport { EventList } from \"../event/list.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport type { AbsolutePath } from \"../schema.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\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\nexport interface CreateSession {\n\treadonly id?: SessionSchema.ID;\n\treadonly projectId: string;\n\treadonly parentId?: SessionSchema.ID; // session hierarchy (subagents) or fork lineage\n\treadonly slug: string;\n\treadonly directory: AbsolutePath;\n\treadonly title: string;\n\treadonly tag?: string;\n\t/**\n\t * The namespace this session's directory lives in. Defaults to the host,\n\t * which needs no row; any other namespace must already be registered.\n\t */\n\treadonly sandboxInstanceId?: SandboxInstance.ID;\n\treadonly metadata?: Readonly<Record<string, string>>;\n}\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// 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\treadonly list: (input: { projectId: string }) => 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/** 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 selectSessions = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: SessionRow,\n\t\t\texecute: (projectId) => sql`SELECT * FROM session WHERE project_id = ${projectId} 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\tprojectId: input.projectId,\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\tsandboxInstanceId: SandboxInstance.toField(input.sandboxInstanceId ?? SandboxInstance.ID.local),\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 list = Effect.fn(\"Session.list\")(function* (input: { projectId: string }) {\n\t\t\treturn yield* selectSessions(input.projectId).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\tprojectId: source.value.projectId,\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\t// Same directory as the source, so the same sandbox env.\n\t\t\t\t\t\t\tsandboxInstanceId: source.value.sandboxInstanceId,\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 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\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\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 { 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\nexport * as SandboxFs from \"./util.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 { 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};\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\";\nimport { Process } from \"../utils/process.ts\";\nimport { Local } from \"./vfs.ts\";\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 RealFSProvider(\"/\"), {\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 { 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 { SandboxDriver } from \"./driver.ts\";\nimport { SandboxDriverRegistry } from \"./registry.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 { 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(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\n\t\t\t? Effect.succeed(Option.some(hostInfo()))\n\t\t\t: 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(\n\t\t\t\t\t(error): Effect.Effect<never, SandboxProviderError | SandboxUnavailError> =>\n\t\t\t\t\t\tproviderErrorIsNotFound(error)\n\t\t\t\t\t\t\t? markUnavailable(id, error)\n\t\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(\n\t\t\t\t\t(error): Effect.Effect<never, SandboxProviderError | SandboxUnavailError> =>\n\t\t\t\t\t\tproviderErrorIsNotFound(error)\n\t\t\t\t\t\t\t? markUnavailable(id, error)\n\t\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\tyield* transports.invalidate(id);\n\t\tconst current = yield* requireRow(id);\n\t\tconst attached = yield* runtime(current, \"stop\");\n\t\tconst observed = yield* attached.driver.stop!(attached.input).pipe(\n\t\t\tEffect.catch(\n\t\t\t\t(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),\n\t\t);\n\t\tyield* updateObservation({\n\t\t\tid,\n\t\t\tstatus: \"offline\",\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 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\tyield* sql`\n\t\t\tUPDATE sandbox_instance\n\t\t\tSET\n\t\t\t\tstatus = 'removed',\n\t\t\t\tremoved_at = ${now},\n\t\t\t\tstate_observed_at = ${now},\n\t\t\t\tlast_error = NULL,\n\t\t\t\tupdated_at = ${now}\n\t\t\tWHERE id = ${id}\n\t\t`.pipe(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(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, Effect, Layer, Schema } from \"effect\";\nimport { posix as path } from \"../util/posix.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\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 Repo {\n\t/**\n\t * The root directory of the working tree that contains the input path.\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\treadonly directory: AbsolutePath;\n\t/**\n\t * The shared Git storage directory used by this repo and any linked worktrees.\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\treadonly store: AbsolutePath;\n}\n\nexport interface Result {\n\treadonly exitCode: number;\n\treadonly text: string;\n\treadonly stderr: string;\n}\n\nexport class WorktreeError extends Schema.TaggedError<WorktreeError>()(\"Git.WorktreeError\", {\n\toperation: Schema.Literals([\"create\", \"remove\", \"list\"]),\n\tmessage: Schema.String,\n\tdirectory: Schema.optional(AbsolutePath),\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface Interface {\n\treadonly find: (input: AbsolutePath) => Effect.Effect<Repo | undefined>;\n\treadonly remote: (repo: Repo, name?: string) => Effect.Effect<string | undefined>;\n\treadonly roots: (repo: Repo) => 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\treadonly worktreeCreate: (input: { repo: Repo; directory: AbsolutePath }) => Effect.Effect<void, WorktreeError>;\n\treadonly worktreeRemove: (input: { repo: Repo; directory: AbsolutePath }) => Effect.Effect<void, WorktreeError>;\n\treadonly worktreeList: (repo: Repo) => Effect.Effect<AbsolutePath[], WorktreeError>;\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 fs = yield* SandboxIO.FileSystem;\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 = (cwd: string) => (args: string[], options?: { readonly env?: Record<string, string> }) =>\n\t\t\tshell\n\t\t\t\t.execArgv([\"git\", ...args], {\n\t\t\t\t\tcwd,\n\t\t\t\t\t...(options?.env === undefined ? {} : { env: options.env }),\n\t\t\t\t})\n\t\t\t\t.pipe(\n\t\t\t\t\tEffect.map(\n\t\t\t\t\t\t(result) =>\n\t\t\t\t\t\t\t({\n\t\t\t\t\t\t\t\texitCode: result.exitCode,\n\t\t\t\t\t\t\t\ttext: result.stdout,\n\t\t\t\t\t\t\t\tstderr: result.stderr,\n\t\t\t\t\t\t\t}) satisfies Result,\n\t\t\t\t\t),\n\t\t\t\t\tEffect.mapError((cause) => new AppProcessError({ command: [\"git\", ...args].join(\" \"), cause })),\n\t\t\t\t);\n\n\t\tconst run = (cwd: string) => (args: string[]) =>\n\t\t\texecute(cwd)(args).pipe(Effect.orElseSucceed(() => ({ exitCode: 1, text: \"\", stderr: \"\" })));\n\n\t\tconst find = Effect.fn(\"Git.find\")(function* (input: AbsolutePath) {\n\t\t\tconst dotgit = yield* SandboxFs.up(fs, { targets: [\".git\"], start: input }).pipe(\n\t\t\t\tEffect.map((matches) => matches[0]),\n\t\t\t);\n\t\t\tif (!dotgit) return undefined;\n\n\t\t\tconst cwd = path.dirname(dotgit);\n\t\t\tconst git = run(cwd);\n\t\t\tconst topLevel = yield* git([\"rev-parse\", \"--show-toplevel\"]);\n\t\t\tconst commonDir = yield* git([\"rev-parse\", \"--git-common-dir\"]);\n\t\t\tif (commonDir.exitCode !== 0) return undefined;\n\n\t\t\tconst directory = topLevel.exitCode === 0 ? resolvePath(cwd, topLevel.text) : cwd;\n\t\t\treturn {\n\t\t\t\tdirectory: AbsolutePath.make(directory),\n\t\t\t\tstore: AbsolutePath.make(resolvePath(directory, commonDir.text)),\n\t\t\t} satisfies Repo;\n\t\t});\n\n\t\tconst remote = Effect.fn(\"Git.remote\")(function* (repo: Repo, name = \"origin\") {\n\t\t\tconst result = yield* run(repo.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* (repo: Repo) {\n\t\t\tconst result = yield* run(repo.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* run(directory)([\"rev-parse\", \"--git-dir\"]);\n\t\t\tif (result.exitCode !== 0) return undefined;\n\t\t\treturn AbsolutePath.make(resolvePath(directory, result.text));\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\tconst worktree = Effect.fnUntraced(function* (\n\t\t\toperation: \"create\" | \"remove\" | \"list\",\n\t\t\trepo: Repo,\n\t\t\targs: string[],\n\t\t\tworktreeDirectory?: AbsolutePath,\n\t\t\tcwd = repo.directory,\n\t\t) {\n\t\t\tconst result = yield* execute(cwd)(args).pipe(\n\t\t\t\tEffect.mapError(\n\t\t\t\t\t(cause) =>\n\t\t\t\t\t\tnew WorktreeError({\n\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\tdirectory: worktreeDirectory,\n\t\t\t\t\t\t\tmessage: cause.message,\n\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t}),\n\t\t\t\t),\n\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: worktreeDirectory,\n\t\t\t\tmessage: result.stderr.trim() || result.text.trim() || \"Git failed\",\n\t\t\t});\n\t\t});\n\n\t\tconst worktreeCreate = Effect.fn(\"Git.worktreeCreate\")(function* (input: {\n\t\t\trepo: Repo;\n\t\t\tdirectory: AbsolutePath;\n\t\t}) {\n\t\t\tyield* worktree(\n\t\t\t\t\"create\",\n\t\t\t\tinput.repo,\n\t\t\t\t[\"worktree\", \"add\", \"--detach\", input.directory, \"HEAD\"],\n\t\t\t\tinput.directory,\n\t\t\t);\n\t\t});\n\n\t\tconst worktreeRemove = Effect.fn(\"Git.worktreeRemove\")(function* (input: {\n\t\t\trepo: Repo;\n\t\t\tdirectory: AbsolutePath;\n\t\t}) {\n\t\t\tyield* worktree(\n\t\t\t\t\"remove\",\n\t\t\t\tinput.repo,\n\t\t\t\t[\"worktree\", \"remove\", \"--force\", input.directory],\n\t\t\t\tinput.directory,\n\t\t\t\tinput.repo.store,\n\t\t\t);\n\t\t});\n\n\t\tconst worktreeList = Effect.fn(\"Git.worktreeList\")(function* (repo: Repo) {\n\t\t\treturn (yield* worktree(\"list\", repo, [\"worktree\", \"list\", \"--porcelain\"]))\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.filter((line) => line.startsWith(\"worktree \"))\n\t\t\t\t.map((line) => AbsolutePath.make(resolvePath(repo.directory, line.slice(\"worktree \".length).trim())));\n\t\t});\n\n\t\treturn Service.of({\n\t\t\tfind,\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\tworktreeCreate,\n\t\t\tworktreeRemove,\n\t\t\tworktreeList,\n\t\t});\n\t}),\n);\n\n/**\n * Run git inside the given sandbox — local, remote, or virtual. The sandbox\n * supplies both halves: repository discovery walks its filesystem and commands\n * run through its shell, so git can never read files in one place and execute\n * in another.\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 `find` reports no repository.\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\nfunction 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 { createHash } from \"crypto\";\n\nexport function fast(input: string | Buffer): string {\n\treturn createHash(\"sha1\").update(input).digest(\"hex\");\n}\n\nexport function sha256(input: string | Buffer): string {\n\treturn createHash(\"sha256\").update(input).digest(\"hex\");\n}\nexport * as Hash from \"./hash.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\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 const IsGitWorktreeInput = Schema.Struct({\n\tdirectory: AbsolutePath,\n}).annotate({ identifier: \"Copy.IsGitWorktreeInput\" });\nexport type IsGitWorktreeInput = typeof IsGitWorktreeInput.Type;\n\nexport interface Interface {\n\treadonly isGitWorktree: (input: IsGitWorktreeInput) => Effect.Effect<boolean>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/project/copy/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\n\t\tconst isGitWorktree = Effect.fn(\"Copy.isGitWorktree\")(function* (input: IsGitWorktreeInput) {\n\t\t\tconst found = yield* SandboxFs.up(fs, { targets: [\".git\"], start: input.directory });\n\n\t\t\tconst dotGit = found[0];\n\t\t\tif (!dotGit) return false; // not inside a git checkout\n\n\t\t\t// the main checkout keeps `.git` as a directory; a linked worktree\n\t\t\t// has a `.git` file pointing into the shared store's worktrees area\n\t\t\tif (yield* SandboxFs.isDirectory(fs, dotGit)) return false;\n\n\t\t\tconst content = (yield* SandboxFs.readFileSafe(fs, dotGit)) ?? \"\";\n\n\t\t\tconst gitdir = content.match(/^gitdir:\\s*(.+?)\\s*$/m)?.[1];\n\t\t\tif (!gitdir) return false;\n\n\t\t\treturn /[\\\\/]\\.git[\\\\/]worktrees[\\\\/]/.test(gitdir);\n\t\t});\n\n\t\treturn Service.of({ isGitWorktree });\n\t}),\n);\n\nexport const layerWith = <E, RIn>(sandbox: Sandbox.Sandbox<E, RIn>) => layer.pipe(Layer.provide(sandbox));\n\nexport const defaultLayer = (path: string) => layerWith(Sandbox.defaultLayer(path));\n\nexport * as ProjectCopy from \"./copy.ts\";\n","import { Schema } from \"effect\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { AbsolutePath, withStatics } from \"../schema.ts\";\n\n// Represents the project ID type\n// defaults to local\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"Project.ID\"),\n\twithStatics((schema) => ({\n\t\tlocal: schema.make(\"local\"),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\n// Represents identified vcs type and path\n// Example:\n// ```\n// {\n// store: \"/app/code/.git\",\n// type: \"git\"\n// }\n// ```\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\nexport const DirectoriesInput = Schema.Struct({\n\tprojectId: ID,\n}).annotate({ identifier: \"Project.DirectoriesInput\" });\nexport type DirectoriesInput = typeof DirectoriesInput.Type;\n\nexport const Directories = Schema.Array(AbsolutePath).annotate({\n\tidentifier: \"Project.Directories\",\n});\nexport type Directories = typeof Directories.Type;\n\nexport const ProjectDirectory = Schema.Struct({\n\tdirectory: AbsolutePath,\n\tsandboxInstanceId: SandboxInstance.ID,\n\ttype: Schema.Union([Schema.Literal(\"main\"), Schema.Literal(\"root\"), Schema.Literal(\"gitworktree\")]),\n});\nexport type ProjectDirectory = typeof ProjectDirectory.Type;\n\nexport class Info extends Schema.Class<Info>(\"Project.Info\")({\n\tid: ID,\n\tvcs: Schema.optional(Vcs),\n\tname: Schema.String,\n\tdirectory: AbsolutePath,\n}) {}\n\nexport * as ProjectSchema from \"./schema.ts\";\n","import { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport { Model } from \"effect/unstable/schema\";\nimport { SqlClient, SqlSchema } from \"effect/unstable/sql\";\nimport { Database } from \"../db/db.ts\";\nimport { ProjectDirectoryRow, ProjectRow } from \"../db/schema.sql.ts\";\nimport { Git } from \"../git/git.ts\";\nimport { posix as path } from \"../util/posix.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 { Hash } from \"../util/hash.ts\";\nimport { ProjectCopy } from \"./copy.ts\";\nimport { ProjectSchema } from \"./schema.ts\";\n\n/**\n * Row identity for a registered directory. Keyed on the environment as well as\n * the path: `/workspace` in two different sandboxes is two different places,\n * and hashing the path alone would collapse them into one row.\n */\nconst directoryId = (projectId: string, sandboxInstanceId: string, directory: string) =>\n\tHash.fast(JSON.stringify([projectId, sandboxInstanceId, directory]));\n\nexport interface Resolved {\n\tprevious?: ProjectSchema.ID; // previous ID before moving\n\tid: ProjectSchema.ID; // current ID\n\tdirectory: AbsolutePath;\n\tvcs?: ProjectSchema.Vcs;\n\tname: string;\n}\n\nexport interface Interface {\n\treadonly resolve: (input: AbsolutePath) => Effect.Effect<Resolved>;\n\treadonly directories: (input: ProjectSchema.DirectoriesInput) => Effect.Effect<ProjectSchema.ProjectDirectory[]>;\n\treadonly fromDirectory: (input: AbsolutePath) => Effect.Effect<ProjectSchema.Info>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/project/project/Service\") {}\n\nexport const layer = Layer.effect(\n\tService,\n\tEffect.gen(function* () {\n\t\tconst sql = yield* SqlClient.SqlClient;\n\n\t\tconst fs = yield* SandboxIO.FileSystem;\n\t\tconst git = yield* Git.Service;\n\t\tconst copy = yield* ProjectCopy.Service;\n\t\t// Which sandbox instance these directories live in. Rows belonging to\n\t\t// another namespace are invisible here: their paths mean nothing to this\n\t\t// filesystem, so probing them would report absence and delete them.\n\t\tconst { id: instanceId } = yield* SandboxIO.Current;\n\t\t// The storage form of the namespace, resolved once: NULL for the host.\n\t\tconst instanceColumn = SandboxInstance.toColumn(instanceId);\n\n\t\t// `IS`, not `=`: SQLite's `= NULL` never matches, and NULL is the host. One\n\t\t// query serves both cases with no branch here.\n\t\tconst selectDirectories = SqlSchema.findAll({\n\t\t\tRequest: Schema.Struct({ projectId: Schema.String, sandboxInstanceId: Schema.NullOr(Schema.String) }),\n\t\t\tResult: ProjectDirectoryRow,\n\t\t\texecute: ({ projectId, sandboxInstanceId }) =>\n\t\t\t\tsql`SELECT * FROM project_directory WHERE project_id = ${projectId} AND sandbox_instance_id IS ${sandboxInstanceId}`,\n\t\t});\n\n\t\t// Every environment's rows. Only for re-homing during an id migration,\n\t\t// where rows would otherwise cascade-delete with the old project — reads\n\t\t// must stay scoped to the current environment.\n\t\tconst selectAllDirectories = SqlSchema.findAll({\n\t\t\tRequest: Schema.String,\n\t\t\tResult: ProjectDirectoryRow,\n\t\t\texecute: (projectId) => sql`SELECT * FROM project_directory WHERE project_id = ${projectId}`,\n\t\t});\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 insertProject = SqlSchema.void({\n\t\t\tRequest: ProjectRow.insert,\n\t\t\texecute: (row) => sql`INSERT INTO project ${sql.insert(row)}`,\n\t\t});\n\n\t\t// the conflict target is the primary key; only the update timestamp moves\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 updated_at = excluded.updated_at\n\t\t\t`,\n\t\t});\n\n\t\t// tolerates both id and (project_id, directory) conflicts\n\t\tconst insertDirectory = SqlSchema.void({\n\t\t\tRequest: ProjectDirectoryRow.insert,\n\t\t\texecute: (row) => sql`INSERT OR IGNORE INTO project_directory ${sql.insert(row)}`,\n\t\t});\n\n\t\tconst toProjectDirectory = (row: ProjectDirectoryRow): ProjectSchema.ProjectDirectory => {\n\t\t\treturn {\n\t\t\t\tdirectory: AbsolutePath.make(row.directory),\n\t\t\t\t// Public results carry a concrete id; NULL is resolved back to the host.\n\t\t\t\tsandboxInstanceId: SandboxInstance.fromField(row.sandboxInstanceId),\n\t\t\t\ttype: row.type,\n\t\t\t};\n\t\t};\n\n\t\tconst directories = Effect.fn(\"Project.directories\")(function* (input: ProjectSchema.DirectoriesInput) {\n\t\t\tconst rows = yield* selectDirectories({ projectId: input.projectId, sandboxInstanceId: instanceColumn }).pipe(\n\t\t\t\tEffect.orDie,\n\t\t\t);\n\n\t\t\t// Three-way, not two: a row is kept, dropped, or unknown. Only a\n\t\t\t// definitive \"absent\" prunes — a backend that could not answer (expired\n\t\t\t// token, timeout) leaves the row alone rather than destroying a record\n\t\t\t// we may not be able to rebuild.\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.directory).pipe(\n\t\t\t\t\t\tEffect.map((exists) => ({ row, stale: !exists })),\n\t\t\t\t\t\tEffect.orElseSucceed(() => ({ row, stale: false })),\n\t\t\t\t\t),\n\t\t\t\t{ concurrency: \"unbounded\" },\n\t\t\t);\n\n\t\t\tconst validRows = probed.filter((entry) => !entry.stale).map((entry) => entry.row);\n\t\t\tconst staleIDs = probed.filter((entry) => entry.stale).map((entry) => entry.row.id);\n\t\t\tif (staleIDs.length > 0) {\n\t\t\t\tyield* sql`DELETE FROM project_directory WHERE ${sql.in(\"id\", staleIDs)}`.pipe(Effect.orDie);\n\t\t\t}\n\n\t\t\treturn validRows\n\t\t\t\t.toSorted((a, b) => a.directory.localeCompare(b.directory))\n\t\t\t\t.map((row) => toProjectDirectory(row));\n\t\t});\n\n\t\tconst cached = Effect.fnUntraced(function* (dir: string) {\n\t\t\treturn yield* fs.readFile(path.join(dir, \"codework\")).pipe(\n\t\t\t\tEffect.map((value) => value.trim()),\n\t\t\t\tEffect.map((value) => (value ? ProjectSchema.ID.make(value) : undefined)),\n\t\t\t\tEffect.catch(() => Effect.void),\n\t\t\t);\n\t\t});\n\n\t\tconst remote = Effect.fnUntraced(function* (repo: Git.Repo) {\n\t\t\tconst origin = yield* git.remote(repo);\n\t\t\tif (!origin) return undefined;\n\t\t\tconst normalized = url(origin);\n\t\t\tif (!normalized) return undefined;\n\t\t\treturn {\n\t\t\t\tid: ProjectSchema.ID.make(Hash.fast(`git:${normalized}`)),\n\t\t\t\tname: path.basename(normalized),\n\t\t\t};\n\t\t});\n\n\t\tfunction url(input: string) {\n\t\t\tconst value = input.trim();\n\t\t\tif (!value) return undefined;\n\n\t\t\ttry {\n\t\t\t\tconst parsed = new URL(value);\n\t\t\t\tif (parsed.protocol === \"file:\") return undefined;\n\t\t\t\treturn parts(parsed.hostname, parsed.pathname);\n\t\t\t} catch {\n\t\t\t\tconst scp = value.match(/^([^@/:]+@)?([^/:]+):(.+)$/);\n\t\t\t\tif (scp) return parts(scp[2]!, scp[3]!);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tfunction parts(host: string, name: string) {\n\t\t\tconst pathname = name\n\t\t\t\t.replace(/^\\/+/, \"\")\n\t\t\t\t.replace(/\\.git\\/?$/, \"\")\n\t\t\t\t.replace(/\\/+$/, \"\");\n\t\t\tif (!host || !pathname) return undefined;\n\t\t\treturn `${host.toLowerCase()}/${pathname}`;\n\t\t}\n\n\t\tconst root = Effect.fnUntraced(function* (repo: Git.Repo) {\n\t\t\tconst root = (yield* git.roots(repo))[0];\n\t\t\treturn root ? ProjectSchema.ID.make(root) : undefined;\n\t\t});\n\n\t\tconst resolve = Effect.fn(\"Project.resolve\")(function* (input: AbsolutePath) {\n\t\t\tconst repo = yield* git.find(input);\n\t\t\tif (!repo) {\n\t\t\t\tconst local: Resolved = {\n\t\t\t\t\tid: ProjectSchema.ID.local,\n\t\t\t\t\tdirectory: input,\n\t\t\t\t\tname: path.basename(path.normalize(input)),\n\t\t\t\t};\n\t\t\t\treturn local;\n\t\t\t}\n\n\t\t\tconst previous = yield* cached(repo.store);\n\t\t\tconst origin = yield* remote(repo);\n\t\t\tconst id = origin?.id ?? previous ?? (yield* root(repo));\n\t\t\tconst resolved: Resolved = {\n\t\t\t\tid: id ?? ProjectSchema.ID.local,\n\t\t\t\t...(previous ? { previous } : {}),\n\t\t\t\tdirectory: repo.directory,\n\t\t\t\tvcs: { type: \"git\", store: repo.store },\n\t\t\t\tname: origin?.name ?? path.basename(path.normalize(repo.directory)),\n\t\t\t};\n\t\t\treturn resolved;\n\t\t});\n\n\t\tconst migrateProjectId = Effect.fn(\"Project.migrateProjectID\")(function* (\n\t\t\toldID: ProjectSchema.ID | undefined,\n\t\t\tnewID: ProjectSchema.ID,\n\t\t) {\n\t\t\tif (!oldID) return; // nothing to migrate from\n\t\t\tif (oldID === ProjectSchema.ID.local) return; // local project copy are ignored\n\t\t\tif (oldID === newID) return; // just the same\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 oldProject = yield* findProject(oldID);\n\t\t\t\t\t\tif (Option.isNone(oldProject)) return;\n\n\t\t\t\t\t\tconst newProject = yield* findProject(newID);\n\t\t\t\t\t\tif (Option.isNone(newProject)) {\n\t\t\t\t\t\t\tconst row = yield* ProjectRow.insert.makeEffect({\n\t\t\t\t\t\t\t\tid: newID,\n\t\t\t\t\t\t\t\tname: oldProject.value.name,\n\t\t\t\t\t\t\t\tcreatedAt: Model.Override(oldProject.value.createdAt),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tyield* insertProject(row);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// directories cascade-delete with the old project row, so\n\t\t\t\t\t\t// re-home them under the new id (with re-derived row ids)\n\t\t\t\t\t\t// before the delete; directories the new project already\n\t\t\t\t\t\t// registered win the conflict\n\t\t\t\t\t\tconst directories = yield* selectAllDirectories(oldID);\n\t\t\t\t\t\tfor (const row of directories) {\n\t\t\t\t\t\t\tconst rehomed = yield* ProjectDirectoryRow.insert.makeEffect({\n\t\t\t\t\t\t\t\tid: directoryId(newID, SandboxInstance.fromField(row.sandboxInstanceId), row.directory),\n\t\t\t\t\t\t\t\tprojectId: newID,\n\t\t\t\t\t\t\t\tdirectory: row.directory,\n\t\t\t\t\t\t\t\ttype: row.type,\n\t\t\t\t\t\t\t\tsandboxInstanceId: row.sandboxInstanceId,\n\t\t\t\t\t\t\t\tcreatedAt: Model.Override(row.createdAt),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tyield* insertDirectory(rehomed);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tyield* sql`DELETE FROM project WHERE id = ${oldID}`;\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(Effect.orDie);\n\t\t});\n\n\t\tconst saveDirectory = Effect.fn(\"Project.saveDirectory\")(function* (input: {\n\t\t\tprojectId: ProjectSchema.ID;\n\t\t\tdirectory: string;\n\t\t}) {\n\t\t\tif (input.projectId === ProjectSchema.ID.local) return;\n\t\t\tconst isGitWorktree = yield* copy.isGitWorktree({\n\t\t\t\tdirectory: AbsolutePath.make(input.directory),\n\t\t\t});\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\t// \"main\" is per environment: each sandbox has its own primary\n\t\t\t\t\t\t// checkout, so a main elsewhere must not demote this one to root.\n\t\t\t\t\t\tconst hasMain = yield* sql`\n\t\t\t\t\t\t\tSELECT directory FROM project_directory\n\t\t\t\t\t\t\tWHERE project_id = ${input.projectId}\n\t\t\t\t\t\t\t\tAND sandbox_instance_id IS ${instanceColumn}\n\t\t\t\t\t\t\t\tAND type = 'main'\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`;\n\n\t\t\t\t\t\tconst row = yield* ProjectDirectoryRow.insert.makeEffect({\n\t\t\t\t\t\t\tid: directoryId(input.projectId, instanceId, input.directory),\n\t\t\t\t\t\t\tprojectId: input.projectId,\n\t\t\t\t\t\t\tdirectory: AbsolutePath.make(input.directory),\n\t\t\t\t\t\t\ttype: isGitWorktree ? \"gitworktree\" : hasMain.length > 0 ? \"root\" : \"main\",\n\t\t\t\t\t\t\tsandboxInstanceId: SandboxInstance.toField(instanceId),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tyield* insertDirectory(row);\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.pipe(\n\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\tEffect.logWarning(\"project directory persistence failed\", {\n\t\t\t\t\t\t\tprojectId: input.projectId,\n\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t});\n\n\t\tconst fromDirectory = Effect.fn(\"Project.fromDirectory\")(function* (directory: string) {\n\t\t\tconst data = yield* resolve(AbsolutePath.make(directory));\n\t\t\tconst projectId = ProjectSchema.ID.make(data.id);\n\n\t\t\t// conditionally migrates previous cached projectId to new one\n\t\t\tyield* migrateProjectId(data.previous ? ProjectSchema.ID.make(data.previous) : undefined, projectId);\n\n\t\t\tconst existing = yield* findProject(projectId).pipe(Effect.orDie);\n\t\t\tconst name = Option.match(existing, {\n\t\t\t\tonNone: () => data.name,\n\t\t\t\tonSome: (row) => row.name,\n\t\t\t});\n\n\t\t\t// on conflict only the update timestamp moves; the stored name and\n\t\t\t// creation time stay as they are\n\t\t\tconst row = yield* ProjectRow.insert.makeEffect({ id: projectId, name }).pipe(Effect.orDie);\n\t\t\tyield* upsertProject(row).pipe(Effect.orDie);\n\n\t\t\tyield* saveDirectory({ projectId: projectId, directory: data.directory });\n\n\t\t\tconst result: ProjectSchema.Info = {\n\t\t\t\tid: projectId,\n\t\t\t\tname,\n\t\t\t\tvcs: data.vcs ?? undefined,\n\t\t\t\tdirectory: data.directory,\n\t\t\t};\n\n\t\t\treturn result;\n\t\t});\n\n\t\treturn Service.of({ resolve, directories, fromDirectory });\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(Git.layer),\n\t\tLayer.provide(ProjectCopy.layer),\n\t\tLayer.provide(sandbox),\n\t\t// Plain database: the host needs no row, and the foreign key is skipped on\n\t\t// NULL, so nothing has to exist before a host directory can be written.\n\t\t// Any other namespace is registered by whoever created it.\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 { Project } from \"../project/project.ts\";\nimport { ProjectSchema } from \"../project/schema.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\nimport { SandboxIO } from \"../sandbox/io.ts\";\nimport { Sandbox } from \"../sandbox/sandbox.ts\";\nimport { AbsolutePath } from \"../schema.ts\";\n\n/**\n * Where work happens: a directory, qualified by the namespace it lives in.\n *\n * The pair is the key. A path alone does not name a place — `/app/repo` on the\n * host and `/app/repo` inside a remote sandbox are different trees wearing the\n * same spelling — so everything scoped to a location carries both halves.\n * Sessions sharing a pair share the project and its registered directories;\n * `main`, `root`, and worktree relationships stay a Project concern beneath it.\n *\n * With the host the second half is constant, so a Location degenerates to\n * exactly what a path-keyed runtime gives you.\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\tdirectory: AbsolutePath,\n\tsandboxInstanceId: SandboxInstance.ID,\n\tproject: Schema.Struct({\n\t\tid: ProjectSchema.ID,\n\t\tname: Schema.String,\n\t\tvcs: Schema.optional(ProjectSchema.Vcs),\n\t\tdirectory: AbsolutePath,\n\t}),\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.fromDirectory(directory);\n\t\t\treturn Service.of({\n\t\t\t\t// `directory` is pwd; `project.directory` is the repository root found\n\t\t\t\t// by walking up from it. Frequently different, and never an input.\n\t\t\t\tdirectory,\n\t\t\t\tsandboxInstanceId: instance.id,\n\t\t\t\tproject: {\n\t\t\t\t\tid: resolved.id,\n\t\t\t\t\tname: resolved.name,\n\t\t\t\t\tvcs: resolved.vcs,\n\t\t\t\t\tdirectory: resolved.directory,\n\t\t\t\t},\n\t\t\t});\n\t\t}),\n\t);\n\nexport const layerWith = <E, RIn>(ref: Ref, sandbox: Sandbox.Sandbox<E, RIn>) =>\n\tlayer(ref).pipe(Layer.provideMerge(Project.layerWith(sandbox)), Layer.provide(sandbox));\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 { ID as SessionId } from \"../session/schema.ts\";\nimport type { 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| 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/** Accepts interruption of active work. Idle interruption returns false. */\n\treadonly interrupt: (sessionId: SessionSchema.ID) => 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/** Stops work owned by this process, waiting for its cleanup. Idle is a no-op. */\n\treadonly interrupt: (sessionId: SessionSchema.ID) => Effect.Effect<void>;\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\t// A Control interrupt preserves the blocking SDK contract even though the\n\t\t// coordinator acknowledges interruption as soon as the owner accepts it.\n\t\tconst interrupt = Effect.fn(\"Control.interrupt\")((sessionId: SessionSchema.ID) =>\n\t\t\tEffect.uninterruptible(execution.interrupt(sessionId).pipe(Effect.andThen(execution.awaitIdle(sessionId)))),\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","/*\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/** Accepts interruption of active work without waiting for cleanup to settle. */\n\treadonly interrupt: (key: Key, reason?: Reason) => Effect.Effect<boolean>;\n\t/** Resolves once no execution is active for the key. 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 interrupt = (key: Key, reason?: Reason): Effect.Effect<boolean> =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst execution = executions.get(key);\n\t\t\t\tif (execution === undefined || execution.stopping) return 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 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 true;\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, Effect, Layer, Option } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\nimport { Git } from \"../git/git.ts\";\nimport { Location } from \"../location/location.ts\";\nimport { ProjectCopy } from \"../project/copy.ts\";\nimport { Project } from \"../project/project.ts\";\nimport { SandboxController } from \"../sandbox/control.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.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 type { ID as SessionId } 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 coordinator = yield* RunCoordinator.make<SessionId, Runner.RunError>({\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* Effect.die(`session not found: ${sessionId}`);\n\t\t\t\tconst row = session.value;\n\t\t\t\tconst instanceId = SandboxInstance.fromField(row.sandboxInstanceId);\n\t\t\t\tconst mount = sandbox.mount(instanceId, { cwd: row.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 mounted = Layer.succeedContext(mountContext);\n\t\t\t\t\tconst database = Layer.succeed(SqlClient.SqlClient, sql);\n\t\t\t\t\tconst projectDependencies = Layer.merge(Git.layer, ProjectCopy.layer).pipe(Layer.provide(mounted));\n\t\t\t\t\tconst project = Project.layer.pipe(\n\t\t\t\t\t\tLayer.provide(projectDependencies),\n\t\t\t\t\t\tLayer.provide(mounted),\n\t\t\t\t\t\tLayer.provide(database),\n\t\t\t\t\t);\n\t\t\t\t\tconst location = Location.layer().pipe(Layer.provide(project), Layer.provide(mounted));\n\t\t\t\t\tconst locationContext = yield* Layer.build(location);\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(\"runner 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 { Predicate } from \"effect\";\n\n/** Merge data objects only; executable runtime objects keep their identity. */\nconst dataObject = (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 dataObject(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, dataObject(previous) && dataObject(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","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});\nexport const Patch = Schema.Struct({\n\t$schema: Schema.optional(Schema.String),\n\tmodel: Schema.optional(Model),\n});\nexport type Patch = typeof Patch.Type;\n\nexport interface Info {\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\tmodel: {\n\t\tprovider: \"openai\",\n\t\tid: \"gpt-5.6-luna\",\n\t\tthinkingLevel: \"high\",\n\t\ttoolExecution: \"sequential\",\n\t\toptions: { timeoutMs: 90_000, maxRetries: 2 },\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 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\n/** Resolve the configured model and start aikit's provider stream. */\nexport const open: Open = Effect.fn(\"LLM.open\")(function* (input, signal) {\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 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 { 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","/*\n * @file Host discovery and loading for `.codework/config/settings.json`.\n *\n * Three files 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.config>/settings.json` -- the user's own, `~/.codework/config` by default\n * 2. `<startup cwd>/.codework/config/settings.json` -- committed with the project\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.config`, 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-project or per-sandbox settings file,\n * and no parent-directory search. The startup directory is captured once, so later `cd` or\n * a session pointed elsewhere changes nothing.\n *\n * `load` re-reads all three 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 * A missing file is ordinary. A malformed or unreadable one warns and contributes nothing,\n * so a typo in one layer cannot stop the layers around it from applying.\n */\n\nimport { Context, Effect, Layer, Schema, SchemaIssue } from \"effect\";\nimport { homedir } from \"node:os\";\nimport { Global } from \"../global.ts\";\nimport { fileSystem, hostPath } from \"../host.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/** Host startup directory, independent of the session/sandbox cwd. */\n\treadonly cwd?: string;\n}\n\nexport function paths(config: string, cwd: string, custom?: string): ReadonlyArray<string> {\n\tconst expanded =\n\t\tcustom === \"~\" ? homedir() : custom?.startsWith(\"~/\") ? hostPath.join(homedir(), custom.slice(2)) : custom;\n\treturn [\n\t\thostPath.join(config, \"settings.json\"),\n\t\thostPath.join(cwd, Global.appConfigDir, \"config\", \"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\nexport const parse = Effect.fn(\"Settings.parse\")(function* (path: string, source: string) {\n\tconst json = yield* Effect.try({\n\t\t// Native parsing preserves syntax offsets; Schema validates the normalized value below.\n\t\t// oxlint-disable-next-line effecttsgo/prefer-schema-over-json\n\t\t// @effect-diagnostics-next-line preferSchemaOverJson:off\n\t\ttry: (): unknown => JSON.parse(source),\n\t\tcatch: (error) => {\n\t\t\tconst message = error instanceof SyntaxError ? error.message : \"\";\n\t\t\tconst position = /position (\\d+)/.exec(message);\n\t\t\tconst offset = position === null ? undefined : Number(position[1]);\n\t\t\tconst before = offset === undefined ? undefined : source.slice(0, offset).split(\"\\n\");\n\t\t\tconst location = before === undefined ? \"\" : ` at ${before.length}:${(before.at(-1)?.length ?? 0) + 1}`;\n\t\t\treturn new SettingsError({ path, reason: \"parse\", detail: `Invalid JSON${location}` });\n\t\t},\n\t});\n\treturn yield* Schema.decodeUnknownEffect(Patch)(normalize(json)).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/** Await fresh host files at each exchange. No cache, mutation, or reload API. */\n\treadonly load: Effect.Effect<Info>;\n}\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/settings/settings/Service\") {}\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\tconst files = paths(global.config, hostPath.resolve(options.cwd ?? process.cwd()), options.userConfigDir);\n\t\t\tconst load = Effect.fn(\"Settings.load\")(function* () {\n\t\t\t\tlet settings = merge(defaults);\n\t\t\t\tfor (const path of files) {\n\t\t\t\t\tconst patch = yield* fileSystem.readFileString(path).pipe(\n\t\t\t\t\t\tEffect.mapError((error) => new SettingsError({ path, reason: \"read\", detail: error.reason._tag })),\n\t\t\t\t\t\tEffect.flatMap((source) => parse(path, source)),\n\t\t\t\t\t\tEffect.catch((error) =>\n\t\t\t\t\t\t\terror.reason === \"read\" && error.detail === \"NotFound\"\n\t\t\t\t\t\t\t\t? Effect.succeed({})\n\t\t\t\t\t\t\t\t: Effect.logWarning(`Settings: ${error.path}: ${error.reason}: ${error.detail}`).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.as({}),\n\t\t\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\tsettings = merge(settings, patch);\n\t\t\t\t}\n\t\t\t\treturn settings;\n\t\t\t});\n\t\t\treturn Service.of({ load: load() });\n\t\t}),\n\t);\n\nexport { defaults } from \"./schema.ts\";\nexport * as Settings from \"./settings.ts\";\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, type FileSystem, type Scope } from \"effect\";\nimport { randomBytes } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { 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): string {\n\treturn posix.join(tmpdir(), `${prefix}-${randomBytes(8).toString(\"hex\")}.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\tthis.tempFilePath = defaultTempFilePath(this.tempFilePrefix);\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/tools/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/tools/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(\n\t\t\t\t\t\t\t(chunk): ToolShellEvent =>\n\t\t\t\t\t\t\t\tchunk._tag === \"exit\"\n\t\t\t\t\t\t\t\t\t? { _tag: \"Exit\", exitCode: chunk.exitCode }\n\t\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/**\n * Expected failures become a tool-error result fed back to the model (\"return\");\n * \"error\" lets them hit the calling effect's error channel. Defaults to\n * \"return\" in {@link define}.\n *\n * \"return\" — almost always, for agent tools.\n * \tA bash non-zero exit, a file-not-found, a bad-patch — the model should see these and adapt.\n *\n * \"error\" — the rare \"this failure is fatal to the run\"\n * \tcase: e.g. an unrecoverable auth/quota error where letting the model keep looping is pointless.\n */\nexport type FailureMode = \"return\" | \"error\";\n\n/** Per-call metadata handed to a handler instead of positional args. */\nexport interface ToolCallContext {\n\treadonly callID: string;\n\treadonly toolName: string;\n\treadonly rawArgs: Record<string, unknown>;\n}\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\treadonly failureMode: FailureMode;\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 failureMode?: FailureMode;\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\tfailureMode: input.failureMode ?? \"return\",\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, Option, Ref, Schema, Stream } from \"effect\";\nimport { randomBytes } from \"node:crypto\";\nimport { tmpdir } from \"node:os\";\nimport { fileSystem } from \"../host.ts\";\nimport { posix } from \"../util/posix.ts\";\nimport { Accumulator, type OutputSnapshot } from \"./accumulator.ts\";\nimport { ToolProgress } from \"./progress.ts\";\nimport { type IToolShell, ToolShell } from \"./shell.ts\";\nimport * as Tool from \"./tool.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, type TruncationResult } from \"./truncate.ts\";\n\n/**\n * The bash tool — the worked example of the design. 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\tfailureMode: \"return\",\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.suspend(() => {\n\t\tconst path = posix.join(tmpdir(), `codework-bash-${randomBytes(6).toString(\"hex\")}.log`);\n\t\treturn fileSystem.writeFileString(path, content).pipe(Effect.as(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","import { Message } from \"@codeworksh/aikit\";\nimport { Cause, Duration, Effect, Exit, Option, Queue, Ref, Result, Schedule, Schema, Scope } from \"effect\";\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 (Effect Schema) → run handler (scoped, exit) →\n * encode typed Success/Failure into aikit's message protocol → complete terminal part.\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 → run error (re-raised as a defect)\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\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`; a `failureMode: \"error\"` tool propagates a {@link ToolExecutionError}\n\t * retaining its declared failure as `cause`, and undeclared failures/defects propagate as defects.\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, ToolExecutionError, 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, ToolExecutionError> =>\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 declared, expected failure. \"error\" opts it into the caller's error\n\t\t\t// channel as ToolExecutionError; \"return\" (default) encodes the original\n\t\t\t// failure into a model-facing tool error result.\n\t\t\tif (def.failureMode === \"error\") {\n\t\t\t\treturn yield* executionError.value;\n\t\t\t}\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// Undeclared failure or genuine defect → the loop is broken, not the tool.\n\t\treturn yield* Effect.die(Cause.squash(cause));\n\t});\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>): Executor => {\n\tconst impls = new Map<string, RegisteredTool>();\n\tfor (const tool of tools) {\n\t\tconst name = 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, tool);\n\t}\n\n\tconst wire = tools.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, ToolExecutionError, RProgress> =>\n\t\tEffect.gen(function* () {\n\t\t\tconst impl = impls.get(call.name);\n\t\t\tif (impl === 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 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\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\t// True while an onProgress write is in flight, so \"drained\" means the queue is empty\n\t\t\t// AND the last sink write finished — not merely dequeued.\n\t\t\tconst activeProgress = yield* Ref.make(false);\n\n\t\t\tconst onProgress = options?.onProgress;\n\t\t\tconst progressQueue = onProgress\n\t\t\t\t? yield* Queue.sliding<ProgressEvent>(options?.progressBuffer ?? DEFAULT_PROGRESS_BUFFER)\n\t\t\t\t: undefined;\n\n\t\t\t// Best-effort delivery off the hot path: swallow (log-drop) sink failures, never fail the\n\t\t\t// tool. This is the only place onProgress runs, so its RProgress/error live here. Typed\n\t\t\t// explicitly so `RProgress` is pinned through `Effect.gen`'s requirement inference.\n\t\t\tconst forkDrain: Effect.Effect<void, never, RProgress | Scope.Scope> =\n\t\t\t\tprogressQueue && onProgress\n\t\t\t\t\t? Queue.take(progressQueue).pipe(\n\t\t\t\t\t\t\tEffect.flatMap((event) =>\n\t\t\t\t\t\t\t\tRef.set(activeProgress, true).pipe(\n\t\t\t\t\t\t\t\t\tEffect.andThen(onProgress(event).pipe(Effect.ignore)),\n\t\t\t\t\t\t\t\t\tEffect.ensuring(Ref.set(activeProgress, false)),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tEffect.forever,\n\t\t\t\t\t\t\tEffect.forkScoped,\n\t\t\t\t\t\t\tEffect.asVoid,\n\t\t\t\t\t\t)\n\t\t\t\t\t: Effect.void;\n\t\t\tyield* forkDrain;\n\n\t\t\t// report is fast + infallible: set latest, then a non-blocking offer (sliding drops the\n\t\t\t// oldest when full). No sink latency reaches the tool.\n\t\t\tconst report = Effect.fn(\"ToolExecutor.reportProgress\")(function* (partial: ToolProgressPartial) {\n\t\t\t\tyield* Ref.set(latest, Option.some(partial));\n\t\t\t\tif (progressQueue === undefined) return;\n\t\t\t\tconst now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n\t\t\t\tyield* Queue.offer(progressQueue, { partial, toolCall: running(call, partial, now), ctx });\n\t\t\t});\n\t\t\tconst progress = ToolProgress.of({ report });\n\n\t\t\t// The handler keeps its OWN inner scope, so its resources release the moment it finishes\n\t\t\t// — not after the drain grace (which is bounded by the outer `Effect.scoped` below).\n\t\t\tconst exit = yield* impl\n\t\t\t\t.handler(decoded.success, ctx)\n\t\t\t\t.pipe(Effect.scoped, Effect.provideService(ToolProgress, progress), Effect.exit);\n\n\t\t\t// Graceful bounded drain on NORMAL completion: wait until the queue is empty AND no sink\n\t\t\t// write is in flight, bounded by progressDrainGrace. Skipped on interruption (snappy abort).\n\t\t\tconst interrupted = Exit.isFailure(exit) && Cause.hasInterrupts(exit.cause);\n\t\t\tif (progressQueue && !interrupted) {\n\t\t\t\tconst drained = Effect.gen(function* () {\n\t\t\t\t\tconst size = yield* Queue.size(progressQueue);\n\t\t\t\t\tconst active = yield* Ref.get(activeProgress);\n\t\t\t\t\treturn size === 0 && !active;\n\t\t\t\t});\n\t\t\t\tyield* drained.pipe(\n\t\t\t\t\tEffect.repeat({ schedule: Schedule.spaced(DRAIN_POLL), until: (done) => done }),\n\t\t\t\t\tEffect.timeout(options?.progressDrainGrace ?? DEFAULT_DRAIN_GRACE),\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn yield* encodeOutcome(def, call, exit, latest);\n\t\t}).pipe(Effect.scoped);\n\n\treturn { wire, handle };\n};\n","import 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>): Registry => {\n\tconst byName = new Map<string, RegisteredTool>();\n\tfor (const tool of tools) byName.set(tool.definition.name, tool);\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((tool) => tool.definition));\n\tconst names = Object.freeze(effective.map((tool) => 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)?.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/tools/registry/ToolRegistry\",\n) {}\n\n/** Provide a catalog of registered tools as the {@link ToolRegistry} service. */\nexport const layer = (tools: ReadonlyArray<RegisteredTool>): Layer.Layer<ToolRegistry> =>\n\tLayer.succeed(ToolRegistry, ToolRegistry.of(make(tools)));\n","/*\n * @file Pure system-prompt construction.\n *\n * Nothing here reads a service, a clock, or a filesystem. Given the same inputs\n * it returns the same string, byte for byte -- which is what lets the prompt be\n * asserted in a test and cached by a provider across a turn's continuations.\n *\n * The chain has three caller slots:\n *\n * foundation --promptCustom?--> base\n * -> tools + guidelines\n * -> promptSystemAppend\n * -> working directory\n * -> promptSystemOverride(rendered) -> final\n *\n * `promptSystemOverride` is applied by the caller of {@link build}, not here: it\n * may be async, and this module stays pure.\n */\n\nimport type { Model } from \"@codeworksh/aikit\";\nimport type { SandboxIO } from \"../sandbox/io.ts\";\nimport type { Location } from \"../location/location.ts\";\nimport type { AnyToolDef } from \"../tools/tool.ts\";\nimport type { ToolExecutionMode } from \"./state.ts\";\n\n/** The default coding-agent foundation, used unless `promptCustom` replaces it. */\nexport const 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 */\nexport const 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\nexport interface BuildInput {\n\t/**\n\t * The effective tool set, in registry order. Only tools carrying a\n\t * `promptSnippet` reach the rendered index; the rest stay callable but\n\t * unlisted.\n\t */\n\treadonly tools: ReadonlyArray<AnyToolDef>;\n\t/** The working directory, always `Location.directory` */\n\treadonly directory: string;\n\t/** Replaces {@link foundation} when supplied. */\n\treadonly promptCustom?: string;\n\t/** Appended after the tool sections, before the working-directory line. */\n\treadonly promptSystemAppend?: string;\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 registry order, which is the same order the index renders in and\n * the same order the provider receives definitions in -- one ordering, not three.\n */\nexport const guidelines = (tools: ReadonlyArray<AnyToolDef>): ReadonlyArray<string> => {\n\tconst seen = new Set<string>();\n\tconst collected: string[] = [];\n\tconst add = (value: string) => {\n\t\tconst line = normalize(value);\n\t\tif (line.length === 0 || seen.has(line)) return;\n\t\tseen.add(line);\n\t\tcollected.push(line);\n\t};\n\tfor (const tool of tools) for (const line of tool.promptGuidelines ?? []) add(line);\n\tfor (const line of standingGuidelines) add(line);\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 */\nexport const 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\nexport const build = (input: BuildInput): 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 * What the override sees. The rendered prompt plus the runtime facts it was\n * rendered from, so a caller can rebuild any part of it rather than only append.\n *\n * `tools` is the same resolved set the provider receives, which is what makes a\n * full override viable without losing the index.\n *\n * Conversation messages are deliberately absent. A hook that could read the\n * transcript is a provider-step concern, not runtime state.\n */\nexport interface PromptSystemOverrideInput {\n\treadonly systemPrompt: string;\n\treadonly tools: ReadonlyArray<AnyToolDef>;\n\treadonly sandbox: SandboxIO.Identity;\n\treadonly location: Location.Info;\n\treadonly provider: string;\n\treadonly model: string;\n\treadonly thinkingLevel: Model.ThinkingLevel;\n\treadonly toolExecution: ToolExecutionMode;\n}\n\n/**\n * The final link in the chain. Its return value is the prompt, verbatim.\n *\n * Sync or async: a caller integrating a non-Effect SDK should not have to reach\n * for Effect to change a string. A throw or rejection becomes a typed\n * `State.SnapshotError`, never a defect.\n */\nexport type PromptSystemOverride = (input: PromptSystemOverrideInput) => string | PromiseLike<string>;\n\nexport * as StatePrompt from \"./prompt.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 { 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 { bashTool } from \"../tools/bash.ts\";\nimport { make as makeRegistry, type Resolved } from \"../tools/registry.ts\";\nimport { fromSandboxShell } from \"../tools/shell.ts\";\nimport * as Tool from \"../tools/tool.ts\";\nimport { StatePrompt } from \"./prompt.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/** Replaces the default foundation prose. */\n\treadonly promptCustom?: string;\n\t/** Appended after the rendered tool sections. */\n\treadonly promptSystemAppend?: string;\n\t/** Owns the final prompt outright. Sync or async. */\n\treadonly promptSystemOverride?: StatePrompt.PromptSystemOverride;\n\t/**\n\t * Registered after the built-in Bash tool, so the registry's\n\t * last-registration-wins rule lets a caller intentionally replace Bash by\n\t * name.\n\t *\n\t * TODO(sanchitrk): check if our assumption is correct here? overriding with same name allowed.\n\t * requires fixing if needed within tool registry\n\t */\n\treadonly tools?: ReadonlyArray<Tool.RegisteredTool>;\n\t/** Built-in tool names enabled for this session. Omitted keeps the Bash default. */\n\treadonly builtinTools?: ReadonlyArray<\"bash\">;\n\treadonly provider?: string;\n\treadonly model?: string;\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n\treadonly toolExecution?: ToolExecutionMode;\n}\n\n/**\n * The prompt override threw or rejected.\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\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 thinkingLevel: Model.ThinkingLevel;\n\treadonly request: RequestOptions;\n\t/** Matched file attributes; catalog resolution stays at the LLM boundary. */\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<Snapshot, SnapshotError, SandboxIO.Provides | Location.Service>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/harness/state/state/Service\") {}\n\n/**\n * Run a caller's override, converting a synchronous throw or a rejected promise\n * into {@link SnapshotError}.\n */\nconst applyOverride = Effect.fn(\"State.applyOverride\")(function* (\n\tsessionId: SessionId,\n\toverride: StatePrompt.PromptSystemOverride,\n\tinput: StatePrompt.PromptSystemOverrideInput,\n) {\n\tconst fail = (cause: unknown) =>\n\t\tnew SnapshotError({\n\t\t\tsessionId,\n\t\t\treason: \"`promptSystemOverride` callback failed\",\n\t\t\tcause,\n\t\t});\n\tconst result = yield* Effect.try({\n\t\ttry: () => override(input),\n\t\tcatch: fail,\n\t});\n\tif (typeof result === \"string\") return result;\n\treturn yield* Effect.tryPromise({ try: () => result, catch: fail });\n});\n\nexport const layer = (options: Options = {}) => {\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\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\tconst configured = compose(yield* settings.load, 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\tpromptSystemOverride,\n\t\t\t\t\t\ttools: callerTools = [],\n\t\t\t\t\t\tbuiltinTools = [\"bash\"],\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\t/*\n\t\t\t\t\t * Bash is bound to the shell of the mount that is open right now.\n\t\t\t\t\t * `ToolShell.local()` would look equivalent and be wrong: it executes on\n\t\t\t\t\t * the host, bypassing whichever in-memory or remote namespace the session\n\t\t\t\t\t * actually selected.\n\t\t\t\t\t *\n\t\t\t\t\t * Capturing the service and re-providing it keeps the binding valid for\n\t\t\t\t\t * the whole exchange -- the drain owns the mount for longer than any turn\n\t\t\t\t\t * inside it, so a handler captured here is still executable when a later\n\t\t\t\t\t * turn calls it.\n\t\t\t\t\t */\n\t\t\t\t\tconst shell = yield* SandboxIO.Shell;\n\t\t\t\t\tconst mountedShell = fromSandboxShell.pipe(Layer.provide(Layer.succeed(SandboxIO.Shell, shell)));\n\n\t\t\t\t\t// Bash first, caller tools after: last registration wins, so a caller can\n\t\t\t\t\t// replace Bash by name on purpose.\n\t\t\t\t\tconst builtins = builtinTools.includes(\"bash\") ? [Tool.provide(bashTool, mountedShell)] : [];\n\t\t\t\t\tconst registry = makeRegistry([...builtins, ...callerTools]);\n\t\t\t\t\tconst resolved = registry.resolve();\n\n\t\t\t\t\tconst rendered = StatePrompt.build({\n\t\t\t\t\t\ttools: resolved.defs,\n\t\t\t\t\t\tdirectory: location.directory,\n\t\t\t\t\t\t...(promptCustom === undefined ? {} : { promptCustom }),\n\t\t\t\t\t\t...(promptSystemAppend === undefined ? {} : { promptSystemAppend }),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst systemPrompt =\n\t\t\t\t\t\tpromptSystemOverride === undefined\n\t\t\t\t\t\t\t? rendered\n\t\t\t\t\t\t\t: yield* applyOverride(sessionId, promptSystemOverride, {\n\t\t\t\t\t\t\t\t\tsystemPrompt: rendered,\n\t\t\t\t\t\t\t\t\ttools: resolved.defs,\n\t\t\t\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\t\t\t\tlocation,\n\t\t\t\t\t\t\t\t\tprovider,\n\t\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\t\tthinkingLevel,\n\t\t\t\t\t\t\t\t\ttoolExecution,\n\t\t\t\t\t\t\t\t});\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\tsystemPrompt,\n\t\t\t\t\t\ttools: resolved,\n\t\t\t\t\t\tprovider,\n\t\t\t\t\t\tmodel,\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 { 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 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 \"the turn failed for an unknown reason\";\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\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.catchCause((cause) =>\n\t\t\t\t\t\t\t\t\t\tCause.hasInterruptsOnly(cause)\n\t\t\t\t\t\t\t\t\t\t\t? Effect.interrupt\n\t\t\t\t\t\t\t\t\t\t\t: Effect.map(\n\t\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\t(now) => errorPart(call, cause, now),\n\t\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.hasInterruptsOnly(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\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.hasInterruptsOnly(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 { findPackageJSON } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport { Effect, Schema } from \"effect\";\nimport { fileSystem, hostPath } from \"../host.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\ninterface PackageManifest {\n\treadonly exports?: unknown;\n\treadonly module?: unknown;\n\treadonly main?: unknown;\n}\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 selectCondition = (value: unknown, conditions: ReadonlyArray<string>): string | undefined => {\n\tif (typeof value === \"string\") return value;\n\tif (Array.isArray(value)) {\n\t\tfor (const candidate of value) {\n\t\t\tconst selected = selectCondition(candidate, conditions);\n\t\t\tif (selected !== undefined) return selected;\n\t\t}\n\t\treturn undefined;\n\t}\n\tif (!isRecord(value)) return undefined;\n\tfor (const condition of conditions) {\n\t\tconst selected = selectCondition(value[condition], conditions);\n\t\tif (selected !== undefined) return selected;\n\t}\n\treturn undefined;\n};\n\nconst exportedTarget = (\n\tmanifest: PackageManifest,\n\tkey: string,\n\tconditions: ReadonlyArray<string>,\n): string | undefined => {\n\tconst exports = manifest.exports;\n\tif (typeof exports === \"string\" || Array.isArray(exports))\n\t\treturn key === \".\" ? selectCondition(exports, conditions) : undefined;\n\tif (!isRecord(exports)) {\n\t\tif (key !== \".\") return undefined;\n\t\treturn typeof manifest.module === \"string\"\n\t\t\t? manifest.module\n\t\t\t: typeof manifest.main === \"string\"\n\t\t\t\t? manifest.main\n\t\t\t\t: \"./index.js\";\n\t}\n\tconst hasSubpaths = Object.keys(exports).some((name) => name.startsWith(\".\"));\n\tif (!hasSubpaths) return selectCondition(key === \".\" ? exports : undefined, conditions);\n\tconst exact = selectCondition(exports[key], conditions);\n\tif (exact !== undefined) return exact;\n\tfor (const pattern of Object.keys(exports)\n\t\t.filter((name) => name.includes(\"*\"))\n\t\t.sort((a, b) => b.length - a.length)) {\n\t\tconst [prefix, suffix = \"\"] = pattern.split(\"*\");\n\t\tif (!key.startsWith(prefix!) || !key.endsWith(suffix)) continue;\n\t\tconst match = key.slice(prefix!.length, key.length - suffix.length);\n\t\tconst target = selectCondition(exports[pattern], conditions);\n\t\tif (target !== undefined) return target.replaceAll(\"*\", match);\n\t}\n\treturn undefined;\n};\n\nconst official = new Set([\"@codeworksh/harness/sandboxes/vercel\", \"@codeworksh/harness/sandboxes/daytona\"]);\n\nexport const packageResolver = (\n\tbase = process.cwd(),\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 parsed = splitPackage(specifier)!;\n\t\tconst packageJson = yield* Effect.try({\n\t\t\ttry: () => findPackageJSON(parsed.name, pathToFileURL(hostPath.resolve(base, \"package.json\"))),\n\t\t\tcatch: (reason) => new SandboxDriverLoadError({ specifier, phase: \"resolve\", reason: String(reason) }),\n\t\t});\n\t\tif (packageJson === undefined) {\n\t\t\treturn yield* new SandboxDriverLoadError({\n\t\t\t\tspecifier,\n\t\t\t\tphase: \"resolve\",\n\t\t\t\treason: `installed package was not found: ${parsed.name}`,\n\t\t\t});\n\t\t}\n\t\tconst source = yield* fileSystem\n\t\t\t.readFileString(packageJson)\n\t\t\t.pipe(\n\t\t\t\tEffect.mapError(\n\t\t\t\t\t(reason) => new SandboxDriverLoadError({ specifier, phase: \"resolve\", reason: String(reason) }),\n\t\t\t\t),\n\t\t\t);\n\t\tconst decoded = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(source).pipe(\n\t\t\tEffect.mapError(\n\t\t\t\t(reason) => new SandboxDriverLoadError({ specifier, phase: \"resolve\", reason: String(reason) }),\n\t\t\t),\n\t\t);\n\t\tconst manifest: PackageManifest = isRecord(decoded) ? decoded : {};\n\t\tconst target = exportedTarget(manifest, parsed.key, conditions);\n\t\tif (target === undefined || !target.startsWith(\"./\")) {\n\t\t\treturn yield* new SandboxDriverLoadError({\n\t\t\t\tspecifier,\n\t\t\t\tphase: \"resolve\",\n\t\t\t\treason: `package export is missing or unsupported: ${parsed.key}`,\n\t\t\t});\n\t\t}\n\t\tconst root = hostPath.dirname(packageJson);\n\t\tconst location = hostPath.resolve(root, target);\n\t\tif (location !== root && !location.startsWith(`${root}${hostPath.sep}`)) {\n\t\t\treturn yield* new SandboxDriverLoadError({\n\t\t\t\tspecifier,\n\t\t\t\tphase: \"resolve\",\n\t\t\t\treason: \"package export resolves outside its package root\",\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tspecifier,\n\t\t\turl: pathToFileURL(location).href,\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\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())(specifier);\n\tconst imported = yield* Effect.tryPromise({\n\t\ttry: () => (options.import ?? ((url) => import(/* @vite-ignore */ url)))(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 { 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\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\tconst configuredDatabase = options.database ?? (yield* Database.locationConfig);\n\t\t\tconst global = Global.layerWith(paths);\n\t\t\tconst database = Database.layer(Database.resolveDatabaseLocation(configuredDatabase, paths.data));\n\t\t\tconst configured = yield* SandboxDriverLoader.loadAll(options.sandboxes ?? []);\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()),\n\t\t\t\tLayer.provideMerge(\n\t\t\t\t\tSettings.layer(options.userConfigDir === undefined ? {} : { userConfigDir: options.userConfigDir }),\n\t\t\t\t),\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(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 } from \"effect\";\nimport { SandboxController } from \"../sandbox/control.ts\";\nimport { SandboxDriver } from \"../sandbox/driver.ts\";\nimport { SandboxDriverRegistrationError } 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\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\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 { DateTime, Effect, Option, Stream } from \"effect\";\nimport { SqlClient } from \"effect/unstable/sql\";\nimport * as Control from \"../control.ts\";\nimport * as Event from \"../event/event.ts\";\nimport type { EventSchema } from \"../event/schema.ts\";\nimport * as SandboxController from \"../sandbox/control.ts\";\nimport { SandboxInstance as SandboxInstanceSchema } from \"../sandbox/instance.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 { StatePrompt } from \"../state/prompt.ts\";\nimport type { State } from \"../state/state.ts\";\nimport type { RegisteredTool } from \"../tools/tool.ts\";\nimport type { Info as SandboxInfo } from \"./sandbox.ts\";\nimport type { bash } from \"./tools.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 builtins?: ReadonlyArray<typeof bash>;\n\treadonly extras?: ReadonlyArray<RegisteredTool>;\n\treadonly execution?: State.ToolExecutionMode;\n}\n\nexport interface SystemPromptConfig {\n\treadonly custom?: string;\n\treadonly append?: string;\n\treadonly override?: StatePrompt.PromptSystemOverride;\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 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\treadonly interrupt: () => ReturnType<Control.Interface[\"interrupt\"]>;\n\treadonly events: (options?: { readonly after?: number }) => Stream.Stream<EventSchema.Payload>;\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?.extras === undefined ? {} : { tools: input.tools.extras }),\n\t...(input.tools?.builtins === undefined ? {} : { builtinTools: input.tools.builtins }),\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\t...(input.systemPrompt?.override === undefined ? {} : { promptSystemOverride: input.systemPrompt.override }),\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\tconst sandboxId = SandboxInstanceSchema.fromField(row.sandboxInstanceId);\n\t\tconst sandbox =\n\t\t\tsandboxId === SandboxInstanceSchema.ID.local\n\t\t\t\t? undefined\n\t\t\t\t: Option.getOrUndefined(yield* sandboxes.get(sandboxId));\n\t\treturn {\n\t\t\tid,\n\t\t\ttitle: row.title,\n\t\t\tdirectory: AbsolutePath.make(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\tinterrupt: () => control.interrupt(id),\n\t\tevents: (options = {}) => events.stream({ sessionId: id, ...options }),\n\t\tpath: () => sessions.path(id),\n\t} satisfies Handle;\n});\n\nconst ensureLocalProject = Effect.fn(\"Session.ensureLocalProject\")(function* () {\n\tconst sql = yield* SqlClient.SqlClient;\n\tconst now = DateTime.toEpochMillis(yield* DateTime.now);\n\tyield* sql`\n\t\tINSERT INTO project (id, name, created_at, updated_at)\n\t\tVALUES ('local', 'local', ${now}, ${now})\n\t\tON CONFLICT(id) DO NOTHING\n\t`.pipe(Effect.orDie);\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\tconst directory = yield* sandboxes.resolveCwd(sandboxId, input.directory);\n\tyield* ensureLocalProject();\n\tyield* sessions.create({\n\t\tid,\n\t\tprojectId: \"local\",\n\t\tslug: id,\n\t\ttitle: input.title ?? \"Session\",\n\t\tdirectory: AbsolutePath.make(directory),\n\t\tsandboxInstanceId: sandboxId,\n\t});\n\tyield* runtime.set(id, runtimeBindings(input));\n\treturn yield* makeHandle(id);\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 * tools, prompt overrides, 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","export const bash = \"bash\" as const;\n\nexport * as Tools from \"./tools.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAaA,OAAK,OAAO,OAAO,MAAM,OAAO,aAAa,KAAK,CAAC,CAAC,CAAC,KACjE,OAAO,M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make","resolve","layer","layerWith","layer","Str","path","Global.resolve","defaultLayer","reasonOf","ID","define","Info","ID","Status","Info","RepoSchema.Vcs","ID","Info","ProjectSchema.ID","SandboxInstance.ID","Model","EventSchema.ID","ProjectSchema.Status","SandboxInstance.ID","SandboxInstance.Kind","SandboxInstance.Ownership","SandboxInstance.Status","SandboxInstance.PersistedError","SpaceSchema.Kind","SpaceSchema.Status","SessionSchema.IDFromDb","Error","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","Hash.fast","SandboxInstance.toColumn","Service","fromRow","SpaceSchema.Info","SandboxInstance.fromField","layer","SandboxIO.FileSystem","SandboxIO.Current","SandboxInstance.toField","Service","SessionSchema.AssistantEnvelopeUsage","SessionSchema.MessageEnvelopeIdentity","decodeCompactionData","SessionSchema.CompactionData","decodeJsonObject","SessionSchema.JsonObject","encodeJsonObject","layer","Event.Service","Space.fromRow","EventList.SessionForked","defaultLayer","Database.defaultLayer","SessionSchema.JsonObject","parseJson","SessionSchema.CompactionData","Service","layer","Session.Service","Session.SessionNotFoundError","Buffer","make","SandboxFileSystem.isNotFoundError","layer","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","layer","Local.Vfs","Process.host","reserved","make","SandboxDriver.erase","layer","layer","make","SandboxInstance.ID","Local.layer","HostExe.layer","EnvNodeJSDefault.layer","SandboxInstance.PersistedError","encodeUnknownJson","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","make","transport","Local.Vfs","Local.layer","EnvBash.transport","Local.Vfs","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","SandboxDriver.RuntimeConfigBase","make","providerError","SandboxDriver.driver","EnvInMemory.make","make","Seed.initialize","Local.Vfs","layer","Process.host","Process.unsupported","SandboxDriver.AbsolutePath","make","EnvSqldb.layer","providerError","SandboxDriver.driver","EnvSqldb.make","SandboxIO.mount","Local.layer","HostExe.layer","defaultLayer","EnvNodeJSDefault.layer","SandboxIO.host","Service","layer","SandboxIO.Shell","path","SandboxInstance.ID","Service","normalize","layer","SandboxIO.FileSystem","Git.Service","SandboxFs.up","path","SandboxFs.realpath","SandboxFs.readFileSafe","Hash.fast","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","path","SandboxFs.up","Space.id","Ref","SpaceSchema.Info","ProjectSchema.Info","Service","layer","SandboxIO.Current","Project.Service","Repo.layer","Worktree.layer","Space.layer","Git.layer","Database.defaultLayer","Sandbox.defaultLayer","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","parse","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","make","register","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","makeTools","makePrompt","makeCatalog","Service","layer","Global.appConfigDir","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","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"],"sources":["../../src/session/schema.ts","../../src/host.ts","../../src/util/home.ts","../../src/global.ts","../../src/db/migrations.ts","../../src/db/db.ts","../../src/event/schema.ts","../../src/repo/schema.ts","../../src/project/schema.ts","../../src/session/prompt/schema.ts","../../src/space/schema.ts","../../src/db/schema.sql.ts","../../src/session/message/schema.ts","../../src/session/failure.ts","../../src/event/list.ts","../../src/event/manifest.ts","../../src/event/event.ts","../../src/util/hash.ts","../../src/space/space.ts","../../src/session/session.ts","../../src/context/errors.ts","../../src/context/codec.ts","../../src/context/assemble.ts","../../src/context/context.ts","../../src/sandbox/utils/process.ts","../../src/sandbox/fs/vfs.ts","../../src/sandbox/fs/nodejs.ts","../../src/sandbox/registry.ts","../../src/sandbox/shell/host.ts","../../src/sandbox/store.ts","../../src/sandbox/control.ts","../../src/sandbox/utils/seed.ts","../../src/sandbox/fs/inmemory.ts","../../src/sandbox/shell/justbash.ts","../../src/sandbox/virtual.ts","../../src/sandbox/drivers/memory.ts","../../src/sandbox/fs/sqldb.ts","../../src/sandbox/drivers/sqldb.ts","../../src/sandbox/sandbox.ts","../../src/git/git.ts","../../src/location/error.ts","../../src/sandbox/fs/util.ts","../../src/repo/repo.ts","../../src/worktree/worktree.ts","../../src/project/project.ts","../../src/location/location.ts","../../src/runner/run.ts","../../src/runner/execution.ts","../../src/session/input/schema.ts","../../src/session/input/input.ts","../../src/control.ts","../../src/event/registry.ts","../../src/settings/merge.ts","../../src/util/module.ts","../../src/plugin/package.ts","../../src/plugin/loader.ts","../../src/plugin/catalog.ts","../../src/plugin/plugin.ts","../../src/plugin/builtin/prompt/default.ts","../../src/tool/truncate.ts","../../src/tool/accumulator.ts","../../src/tool/progress.ts","../../src/tool/shell.ts","../../src/tool/error.ts","../../src/tool/tool.ts","../../src/plugin/builtin/tool/bash.ts","../../src/plugin/builtin.ts","../../src/runner/coordinator.ts","../../src/runner/execute.ts","../../src/runner/event.ts","../../src/settings/schema.ts","../../src/settings/resolve.ts","../../src/runner/llm.ts","../../src/plugin/context.ts","../../src/plugin/tool/schema.ts","../../src/util/error.ts","../../src/tool/executor.ts","../../src/tool/registry.ts","../../src/plugin/prompt/registry.ts","../../src/plugin/tool/registry.ts","../../src/plugin/registry.ts","../../src/plugin/host.ts","../../src/session/runtime.ts","../../src/settings/settings.ts","../../src/state/state.ts","../../src/runner/loop.ts","../../src/sandbox/loader.ts","../../src/session/projector.ts","../../src/session/live.ts","../../src/effect/harness.ts","../../src/effect/sandbox.ts","../../src/effect/session.ts","../../src/plugin/prompt/schema.ts","../../src/plugin/index.ts"],"sourcesContent":["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 { 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 { 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 { 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 { 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 { Effect, Layer } from \"effect\";\nimport type { ChildProcessSpawner } from \"effect/unstable/process\";\nimport { Database } from \"../db/db.ts\";\nimport { posix as path } from \"../util/posix.ts\";\nimport { SandboxController } from \"./control.ts\";\nimport { SandboxDriver } from \"./driver.ts\";\nimport { SandboxDriverRegistry } from \"./registry.ts\";\nimport { MemorySandboxDriver } from \"./drivers/memory.ts\";\nimport { SqldbSandboxDriver } from \"./drivers/sqldb.ts\";\nimport { EnvNodeJSDefault } from \"./fs/nodejs.ts\";\nimport { Local } from \"./fs/vfs.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\nimport { HostExe } from \"./shell/host.ts\";\n\n// re-export from sandbox\nexport { SandboxController } from \"./control.ts\";\nexport { SandboxDriver } from \"./driver.ts\";\nexport * as DaytonaSandboxDriver from \"../sandboxes/daytona/index.ts\";\nexport { MemorySandboxDriver } from \"./drivers/memory.ts\";\nexport { SqldbSandboxDriver } from \"./drivers/sqldb.ts\";\nexport * as VercelSandboxDriver from \"../sandboxes/vercel/index.ts\";\nexport { SandboxError } from \"./errors.ts\";\nexport { EnvInMemory } from \"./fs/inmemory.ts\";\nexport { EnvNodeJSDefault } from \"./fs/nodejs.ts\";\nexport { EnvSqldb } from \"./fs/sqldb.ts\";\nexport { SandboxInstance } from \"./instance.ts\";\nexport { SandboxIO } from \"./io.ts\";\nexport { SandboxResource } from \"./resource.ts\";\nexport { HostExe } from \"./shell/host.ts\";\nexport { EnvBash } from \"./shell/justbash.ts\";\nexport { Process } from \"./utils/process.ts\";\n\n/**\n * What every sandbox provides, wherever it runs: a filesystem, a way to execute\n * commands, and the identity of the instance those act on. Consumers depend on\n * these three services and nothing else, so a local VFS-backed sandbox and a\n * remote provider are interchangeable.\n *\n * The identity is part of the contract because anything persisted about a\n * sandbox has to be scoped to it — paths repeat across namespaces, so\n * `/workspace` alone never names a place.\n */\nexport type Provides = SandboxIO.Provides;\n\n/** A sandbox is any Layer providing the runtime services above. */\nexport type Sandbox<E = never, RIn = never> = Layer.Layer<Provides, E, RIn>;\n\n/**\n * The OS primitives a local backend supplies — a VFS to build the filesystem on\n * and a process spawner to build the shell on. This is local construction\n * detail, not part of the sandbox contract: remote providers implement\n * {@link Provides} directly and never produce these.\n */\nexport type LocalPrimitives = Local.Vfs | ChildProcessSpawner.ChildProcessSpawner;\n\n/** A local backend: the raw primitives, before they are assembled into a sandbox. */\nexport type LocalBackend<E = never, RIn = never> = Layer.Layer<LocalPrimitives, E, RIn>;\n\n/**\n * Assemble a local backend into a sandbox with a **real host shell** — the\n * right choice whenever commands must invoke actual binaries (`git`, package\n * managers). For a sandbox whose shell should stay inside the VFS, use\n * `EnvBash.services` instead, which wires just-bash over the same tree.\n */\nexport const services = <E, RIn>(backend: LocalBackend<E, RIn>, identity: SandboxIO.Identity) =>\n\tLayer.provideMerge(\n\t\tSandboxIO.mount(identity),\n\t\tLayer.provideMerge(Layer.merge(Local.layer, HostExe.layer()), backend),\n\t);\n\nconst controllerLayer = (...drivers: ReadonlyArray<SandboxDriver.Registration>) => {\n\tconst dependencies = Layer.merge(Database.layer(\":memory:\"), SandboxDriverRegistry.layer(...drivers));\n\treturn Layer.provide(SandboxController.layer(), dependencies);\n};\n\n/** Default sandbox: the real OS filesystem and processes, mounted at `cwd`. */\nexport const defaultLayer = (cwd?: string) => services(EnvNodeJSDefault.layer(), SandboxIO.host(cwd));\n\n// Named constructors choose backend and identity together. Low-level assemblers\n// require an explicit id because a custom backend's namespace cannot be inferred.\n\n/**\n * The host machine: real filesystem, real processes. Identity is always `local`;\n * cwd defaults to the host process directory, matching Flue's local adapter.\n */\nexport const local = (cwd?: string) => defaultLayer(cwd);\n\n/**\n * An in-process VFS with just-bash over it — no host disk, no host processes.\n * Each call is a distinct namespace and says so, and none of them survive the\n * process.\n */\nexport const memory = (options?: { readonly instanceId?: SandboxInstance.ID; readonly cwd?: string }) => {\n\tconst memory = MemorySandboxDriver.make();\n\tconst mountCwd = SandboxIO.resolveMountCwd(\"/\", options?.cwd);\n\treturn Layer.unwrap(\n\t\tEffect.map(SandboxController.Controller, (controller) =>\n\t\t\tcontroller.createAndMount(\n\t\t\t\t{\n\t\t\t\t\tdriver: memory.driver,\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(\"/\"),\n\t\t\t\t\t\tinitializeCwd: SandboxDriver.AbsolutePath.make(mountCwd),\n\t\t\t\t\t},\n\t\t\t\t\tinstanceId: options?.instanceId,\n\t\t\t\t},\n\t\t\t\t{ cwd: mountCwd },\n\t\t\t),\n\t\t),\n\t).pipe(Layer.provide(controllerLayer(memory.driver)), Layer.orDie);\n};\n\n/**\n * A sqlite-backed VFS with just-bash over it. With a `location` the file is the\n * state and survives the process; without one the database is in memory and\n * dies with it. Either way the identity is minted unless the caller names one —\n * a backing file can be re-opened, but only its registrar knows under which ID.\n */\nexport const sqldb = (options?: {\n\treadonly location?: string;\n\treadonly instanceId?: SandboxInstance.ID;\n\treadonly cwd?: string;\n}) => {\n\tconst location = options?.location === undefined ? undefined : path.resolve(options.location);\n\tconst sqldb = SqldbSandboxDriver.make();\n\tconst mountCwd = SandboxIO.resolveMountCwd(\"/\", options?.cwd);\n\treturn Layer.unwrap(\n\t\tEffect.map(SandboxController.Controller, (controller) =>\n\t\t\tcontroller.createAndMount(\n\t\t\t\t{\n\t\t\t\t\tdriver: sqldb.driver,\n\t\t\t\t\tconfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(\"/\"),\n\t\t\t\t\t\tinitializeCwd: SandboxDriver.AbsolutePath.make(mountCwd),\n\t\t\t\t\t\t...(location === undefined ? {} : { location }),\n\t\t\t\t\t},\n\t\t\t\t\tinstanceId: options?.instanceId,\n\t\t\t\t},\n\t\t\t\t{ cwd: mountCwd },\n\t\t\t),\n\t\t),\n\t).pipe(Layer.provide(controllerLayer(sqldb.driver)), Layer.orDie);\n};\n\nexport * as Sandbox from \"./sandbox.ts\";\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","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","/*\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 { 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\nexport const parse = Effect.fn(\"Settings.parse\")(function* (path: string, source: string) {\n\tconst json = yield* Effect.try({\n\t\t// Native parsing preserves syntax offsets; Schema validates the normalized value below.\n\t\t// oxlint-disable-next-line effecttsgo/prefer-schema-over-json\n\t\t// @effect-diagnostics-next-line preferSchemaOverJson:off\n\t\ttry: (): unknown => JSON.parse(source),\n\t\tcatch: (error) => {\n\t\t\tconst message = error instanceof SyntaxError ? error.message : \"\";\n\t\t\tconst position = /position (\\d+)/.exec(message);\n\t\t\tconst offset = position === null ? undefined : Number(position[1]);\n\t\t\tconst before = offset === undefined ? undefined : source.slice(0, offset).split(\"\\n\");\n\t\t\tconst location = before === undefined ? \"\" : ` at ${before.length}:${(before.at(-1)?.length ?? 0) + 1}`;\n\t\t\treturn new SettingsError({ path, reason: \"parse\", detail: `Invalid JSON${location}` });\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","export interface PromptRegistry {\n\treadonly set: (systemPrompt: string) => void;\n\treadonly get: () => string | undefined;\n}\n","export type { PluginOptions, PluginRef } from \"./catalog.ts\";\nexport type { Config, Events, PromptResolver, SharedPluginContext } from \"./context.ts\";\nexport { SetupError } from \"./host.ts\";\nexport { PreparationError } from \"./loader.ts\";\nexport { InstallError } from \"./package.ts\";\nexport { define, type Mount, type Plugin } from \"./plugin.ts\";\nexport * as Prompt from \"./prompt/schema.ts\";\nexport type { PluginRegistry } from \"./registry.ts\";\nexport * as Tool from \"./tool/schema.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAaA,OAAK,OAAO,OAAO,MAAM,OAAO,aAAa,KAAK,CAAC,CAAC,CAAC,KACjE,OAAO,MAAM,YAAY,GACzB,aAAa,YAAY;CACxB,YAAY,OAAgB;EAC3B,IAAI,CAAC,IAAI,OAAO,OAAO,KAAK,SAAS,OAAO,CAAC;EAC7C,IAAI,CAAC,GAAG,WAAW,KAAK,GAAG,MAAM,IAAI,MAAM,MAAM,GAAG,yBAAyB;EAC7E,OAAO,OAAO,KAAK,EAAE;CACtB;CACA,cAAc,OAAO,KAAK,SAAS,OAAO,CAAC;AAC5C,EAAE,CACH;AAGA,MAAa,WAAW,OAAO,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;;;;;;AAOrE,MAAa,kBAAkB,OAAO,SAAS,CAAC,QAAQ,UAAU,CAAC;AAKnE,MAAa,aAAa,OAAO,eAAe,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC;AAE5F,MAAa,0BAA0B,OAAO,eAC7C,OAAO,OAAO,EACb,WAAW,OAAO,OACnB,CAAC,CACF;AAGA,MAAa,iBAAiB,OAAO,eACpC,OAAO,OAAO;CACb,SAAS,OAAO;CAEhB,kBAAkB,OAAO,OAAO,OAAO,MAAM;CAC7C,cAAc;AACf,CAAC,CACF;AAQA,MAAa,QAAQ,OAAO,OAAO;CAClC,OAAO;CACP,QAAQ;CACR,WAAW;CACX,YAAY;CACZ,aAAa;CACb,MA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