@codeworksh/harness 0.0.1-dev.20260824145955 → 0.0.1-dev.20260824173147
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/README.md +11 -1
- package/cli/index.mjs +19 -14
- package/cli/index.mjs.map +1 -1
- package/effect.d.mts +1 -1
- package/effect.mjs +1 -1
- package/package.json +1 -1
- package/{session-m-xcehZ7.mjs → session-CF1B0VEr.mjs} +18 -11
- package/{session-m-xcehZ7.mjs.map → session-CF1B0VEr.mjs.map} +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-m-xcehZ7.mjs","names":["AbsolutePath","ID","Usage","Service","make","build","layer","layer","Str","Global.resolve","defaultLayer","reasonOf","ID","define","ID","Model","EventSchema.ID","SandboxInstance.ID","SandboxInstance.Kind","SandboxInstance.Ownership","SandboxInstance.Status","SandboxInstance.PersistedError","AbsolutePath","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","ConfigChangeData","SessionSchema.CompactionData","Service","layer","Session.Service","Session.SessionNotFoundError","Service","withCwd","path","Shell","FileSystem","SandboxFileSystem.Service","ShellTag","SandboxInstance.ID","SandboxInstance.Status","SandboxInstance.PersistedError","errorMessage","layer","Buffer","make","SandboxFileSystem.isNotFoundError","layer","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","layer","Shell","layer","Local.Vfs","Process.host","make","SandboxInstance.ID","Local.layer","HostExe.layer","EnvNodeJSDefault.layer","SandboxInstance.PersistedError","encodeUnknownJson","make","SandboxDriver.Registry","SandboxStore.make","SandboxIO.resolveMountCwd","SandboxInstance.isMountable","SandboxIO.FileSystem","SandboxIO.Shell","SandboxIO.Current","SandboxFileSystem.withCwd","shellWithCwd","layer","Buffer","make","Seed.initialize","Buffer","Shell","make","transport","Local.Vfs","Local.layer","EnvBash.transport","transport","Local.Vfs","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","SandboxDriver.RuntimeConfigBase","make","SandboxDriver.driver","EnvInMemory.make","transport","make","Seed.initialize","Local.Vfs","layer","Process.host","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","make","EnvSqldb.layer","SandboxDriver.driver","EnvSqldb.make","transport","resolvePath","make","Service","DEFAULT_CWD","SandboxIO.resolveMountCwd","SandboxInstance.PersistedError","Remote","statsFrom","providerFrom","Buffer","exec","execArgv","transport","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","resourceLayer","SandboxResource.Service","CreateConfig","RuntimeConfig","SandboxDriver.AbsolutePath","name","statusFrom","make","SandboxDriver.driver","EnvDaytona.mountCwd","EnvDaytona.transport","SandboxInstance.PersistedError","Buffer","SandboxFileSystem.isNotFoundError","stream","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","SandboxResource.Service","SandboxDriver.AbsolutePath","make","EnvVercel.credentialsFrom","SandboxDriver.driver","EnvVercel.createSandbox","EnvVercel.transport","AbsolutePath","Service","layer","SandboxIO.FileSystem","SandboxIO.Shell","SandboxFs.up","path","AbsolutePath","Service","layer","SandboxIO.FileSystem","SandboxFs.up","SandboxFs.isDirectory","SandboxFs.readFileSafe","AbsolutePath","SandboxInstance.ID","Info","Hash.fast","Service","layer","SandboxIO.FileSystem","Git.Service","ProjectCopy.Service","SandboxIO.Current","SandboxInstance.toColumn","AbsolutePath","SandboxInstance.fromField","path","Model","SandboxInstance.toField","Ref","AbsolutePath","SandboxInstance.ID","ProjectSchema.ID","ProjectSchema.Vcs","Service","layer","SandboxIO.Current","Project.Service","SandboxInstance.ID","SessionMessageSchema.ID","EventList.TurnAbortCause","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","Runner.ProviderTurnError","Runner.ModelNotFoundError","aikitStream","make","make","Shell","make","register","Tool.define","Tool.implement","endTime","make","Executor.make","Service","layer","layer","SessionRuntime.Service","SessionContext.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","Runner.TurnError","EventList.TurnAborted","run","layer","Event.Service","SessionInput.make","Session.Service","EventList.ConfigChanged","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.resolveLocation","SandboxDriver.layer","SandboxController.layer","Loop.layer","LLM.make","State.layer","SessionRuntime.layer","Context.layer","SessionLive.layer","Event.layer","SandboxDriver.Registry","create","SandboxController.Controller","get","MemorySandboxDriver.make","SqldbSandboxDriver.make","VercelSandboxDriver.make","DaytonaSandboxDriver.make","SessionStore.Service","Control.Service","Event.Service","SandboxController.Controller","SessionStore.SessionNotFoundError","SandboxInstanceSchema.fromField","AbsolutePath","create","SessionRuntime.Service","EventList.ConfigChanged"],"sources":["../../src/schema.ts","../../src/session/schema.ts","../../src/host.ts","../../src/posix.ts","../../src/global.ts","../../src/db/migrations.ts","../../src/db/db.ts","../../src/event/schema.ts","../../src/sandbox/instance.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/fs/filesystem.ts","../../src/sandbox/shell/shell.ts","../../src/sandbox/io.ts","../../src/sandbox/errors.ts","../../src/sandbox/driver.ts","../../src/sandbox/fs/vfs.ts","../../src/sandbox/shell/host.ts","../../src/sandbox/utils/process.ts","../../src/sandbox/fs/nodejs.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/fs/remote.ts","../../src/sandbox/resource.ts","../../src/sandbox/providers/daytona.ts","../../src/sandbox/drivers/daytona.ts","../../src/sandbox/providers/vercel.ts","../../src/sandbox/drivers/vercel.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/runner/llm.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/session/runtime.ts","../../src/state/prompt.ts","../../src/state/state.ts","../../src/runner/loop.ts","../../src/session/projector.ts","../../src/session/live.ts","../../src/effect/harness.ts","../../src/effect/sandbox.ts","../../src/effect/session.ts"],"sourcesContent":["import { Message } from \"@codeworksh/aikit\";\nimport { Option, Schema, SchemaGetter, DateTime } from \"effect\";\nimport type { Static, TSchema } from \"typebox\";\nimport TypeBoxSchema from \"typebox/schema\";\n\nconst aikitValidators = new WeakMap<TSchema, ReturnType<typeof TypeBoxSchema.Compile>>();\n\nconst aikitValidatorFor = <T extends TSchema>(schema: T): ReturnType<typeof TypeBoxSchema.Compile<T>> => {\n\tconst cached = aikitValidators.get(schema) as ReturnType<typeof TypeBoxSchema.Compile<T>> | undefined;\n\tif (cached !== undefined) return cached;\n\tconst compiled = TypeBoxSchema.Compile(schema);\n\taikitValidators.set(schema, compiled);\n\treturn compiled;\n};\n\nconst aikitErrorPath = (error: {\n\treadonly instancePath?: string;\n\treadonly params?: Record<string, unknown>;\n}): string => {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\tconst required = error.params?.requiredProperties;\n\treturn Array.isArray(required) ? required.join(\", \") : \"root\";\n};\n\nconst validateAikitSchema = <T extends TSchema>(schema: T, value: unknown, label: string): Static<T> => {\n\tconst validator = aikitValidatorFor(schema);\n\tif (validator.Check(value)) return value;\n\n\tconst [, issues] = validator.Errors(value);\n\tconst details = issues.map((issue) => ` - ${aikitErrorPath(issue)}: ${issue.message}`).join(\"\\n\") || \"unknown error\";\n\tthrow new Error(`validation failed for ${label}\\n${details}`);\n};\n\n/** Validate an aikit message without coercing or rewriting durable data. */\nexport const validateAikitMessage = (value: unknown, label: string): Message.Message =>\n\tvalidateAikitSchema(Message.MessageSchema, value, label);\n\nexport const validateAikitUserMessage = (value: unknown, label: string): Message.UserMessage =>\n\tvalidateAikitSchema(Message.UserMessageSchema, value, label);\n\nexport const validateAikitAssistantMessage = (value: unknown, label: string): Message.AssistantMessage =>\n\tvalidateAikitSchema(Message.AssistantMessageSchema, value, label);\n\nexport const validateAikitToolCallTerminalPart = (value: unknown, label: string): Message.ToolCallTerminalPart =>\n\tvalidateAikitSchema(Message.ToolCallTerminalPartSchema, value, label);\n\nexport const isAikitAssistantMessage = (value: unknown): value is Message.AssistantMessage =>\n\taikitValidatorFor(Message.AssistantMessageSchema).Check(value);\n\nexport const isAikitToolCallTerminalPart = (value: unknown): value is Message.ToolCallTerminalPart =>\n\taikitValidatorFor(Message.ToolCallTerminalPartSchema).Check(value);\n\n/**\n * Integer greater than zero.\n */\nexport const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\n\n/**\n * Integer greater than or equal to zero.\n */\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Cost greater than or equal with finite value\n */\nexport const NonNegativeCost = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Relative file path (e.g., `src/components/Button.tsx`).\n */\nexport const RelativePath = Schema.String.pipe(Schema.brand(\"RelativePath\"));\nexport type RelativePath = Schema.Schema.Type<typeof RelativePath>;\n\n/**\n * Absolute file path (e.g., `/home/user/projects/myapp/src/main.ts`).\n */\nexport const AbsolutePath = Schema.String.pipe(Schema.brand(\"AbsolutePath\"));\nexport type AbsolutePath = Schema.Schema.Type<typeof AbsolutePath>;\n\n/**\n * Optional public JSON field that can hold explicit `undefined` on the type\n * side but encodes it as an omitted key, matching legacy `JSON.stringify`.\n */\nexport const optional = <S extends Schema.Top>(schema: S) =>\n\tSchema.optionalKey(schema).pipe(\n\t\tSchema.decodeTo(Schema.optional(schema), {\n\t\t\tdecode: SchemaGetter.passthrough({ strict: false }),\n\t\t\tencode: SchemaGetter.transformOptional(Option.filter((value) => value !== undefined)),\n\t\t}),\n\t);\n\n/**\n * Strip `readonly` from a nested type. Stand-in for `effect`'s `Types.DeepMutable`\n * until `effect:core/x228my` (\"Types.DeepMutable widens unknown to `{}`\") lands.\n *\n * The upstream version falls through `unknown` into `{ -readonly [K in keyof T]: ... }`\n * where `keyof unknown = never`, so `unknown` collapses to `{}`. This local\n * version gates the object branch on `extends object` (which `unknown` does\n * not) so `unknown` passes through untouched.\n *\n * Primitive bailout matches upstream — without it, branded strings like\n * `string & Brand<\"SessionID\">` fall into the object branch and get their\n * prototype methods walked.\n *\n * Tuple branch preserves readonly tuples (e.g. `ConfigPlugin.Spec`'s\n * `readonly [string, Options]`); the general array branch would otherwise\n * widen them to unbounded arrays.\n */\nexport type DeepMutable<T> = T extends string | number | boolean | bigint | symbol | Function\n\t? T\n\t: T extends readonly [unknown, ...unknown[]]\n\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t: T extends readonly (infer U)[]\n\t\t\t? DeepMutable<U>[]\n\t\t\t: T extends object\n\t\t\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t\t\t: T;\n\n/**\n * Attach static methods to a schema object. Designed to be used with `.pipe()`:\n *\n * @example\n * export const Foo = fooSchema.pipe(\n * withStatics((schema) => ({\n * zero: schema.make(0),\n * from: Schema.decodeUnknownOption(schema),\n * }))\n * )\n */\nexport const withStatics =\n\t<S extends object, M extends Record<string, unknown>>(methods: (schema: S) => M) =>\n\t(schema: S): S & M =>\n\t\tObject.assign(schema, methods(schema));\n\n/**\n * Nominal wrapper for scalar types. The class itself is a valid schema —\n * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc.\n *\n * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type`\n * of a field using this newtype resolves to `Self` rather than the underlying\n * branded phantom. Without that override, passing a class instance to code\n * typed against `Schema.Schema.Type<FieldSchema>` would require a cast even\n * though the values are structurally equivalent at runtime.\n *\n * @example\n * class QuestionID extends Newtype<QuestionID>()(\"QuestionID\", Schema.String) {\n * static make(id: string): QuestionID {\n * return this.make(id)\n * }\n * }\n *\n * Schema.decodeEffect(QuestionID)(input)\n */\nexport function Newtype<Self>() {\n\treturn <const Tag extends string, S extends Schema.Top>(tag: Tag, schema: S) => {\n\t\tabstract class Base {\n\t\t\tdeclare readonly _newtype: Tag;\n\n\t\t\tstatic make(value: Schema.Schema.Type<S>): Self {\n\t\t\t\treturn value as unknown as Self;\n\t\t\t}\n\t\t}\n\n\t\tObject.setPrototypeOf(Base, schema);\n\n\t\treturn Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & {\n\t\t\treadonly make: (value: Schema.Schema.Type<S>) => Self;\n\t\t} & Omit<Schema.Opaque<Self, S, {}>, \"make\" | \"~type.make\"> & {\n\t\t\t\treadonly \"~type.make\": Self;\n\t\t\t};\n\t};\n}\n\nexport const DateTimeUtcFromMillis = Schema.Finite.pipe(\n\tSchema.decodeTo(Schema.DateTimeUtc, {\n\t\tdecode: SchemaGetter.transform((value) => DateTime.makeUnsafe(value)),\n\t\tencode: SchemaGetter.transform((value) => DateTime.toEpochMillis(value)),\n\t}),\n);\n","import { Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { NonNegativeCost, NonNegativeInt, withStatics } from \"../schema.ts\";\n\n// Session identity. Branded so a session ID is not interchangeable with an\n// entry, part, or workspace ID at the type level — service signatures take\n// `SessionSchema.ID`, never a bare `string`.\n//\n// `create` mints a new one; `ascending` adopts an ID that came from outside\n// (a persisted row, a request payload) and rejects a foreign prefix rather\n// than branding it silently. uuidv7 keeps IDs lexicographically sortable by\n// creation time, so `ORDER BY id` is `ORDER BY created`.\nexport const ID = Schema.String.check(Schema.isStartsWith(\"ses\")).pipe(\n\tSchema.brand(\"Session.ID\"),\n\twithStatics((schema) => ({\n\t\tascending: (id?: string) => {\n\t\t\tif (!id) return schema.make(\"ses_\" + uuidv7());\n\t\t\tif (!id.startsWith(\"ses\")) throw new Error(`ID ${id} does not start with ses`);\n\t\t\treturn schema.make(id);\n\t\t},\n\t\tcreate: () => schema.make(\"ses_\" + uuidv7()),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\nexport const IDFromDb = Schema.String.pipe(Schema.brand(\"Session.ID\"));\n\n// 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 } from \"@effect/platform-node\";\nimport { Effect, FileSystem } 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","import { Effect, Path } from \"effect\";\n\n/** Shared POSIX path implementation for sandbox and remote-runtime paths. */\nexport const posix = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));\n","import { Config, Context, Effect, Layer } from \"effect\";\nimport * as os from \"node:os\";\nimport { fileSystem } from \"./host.ts\";\nimport { posix } from \"./posix.ts\";\n\nexport const configDir = \".codework\";\nexport const app = \"codework\";\n\nconst defaultHome = posix.join(os.homedir(), configDir);\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 agent: 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\tagent: input.agent ?? posix.join(home, \"agent\"),\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.agent, { 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 \"../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 resolveLocation(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 resolveLocation(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 { Option, Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { withStatics } from \"../schema.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\n\n/**\n * A Sandbox instance is a **durable filesystem namespace** plus whatever compute\n * acts on it — a device in Unix terms, which exists whether or not anything has\n * it mounted. `Sandbox.Controller` is the only thing that creates,\n * stops, or destroys one; this module is just its identity and state model.\n *\n * The application ID is deliberately separate from the driver's own resource\n * locator: callers never parse a Vercel name or a Daytona ID, driver formats may\n * change, and a destroyed resource must stay identifiable in Project/Session\n * history. A missing resource is never recreated under an existing ID — a new\n * resource is a new namespace and therefore a new ID.\n */\n\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"SandboxInstance.ID\"),\n\twithStatics((schema) => ({\n\t\t/**\n\t\t * The host. Reserved, and never written to a column — see {@link toColumn}.\n\t\t * It exists at runtime so nothing has to branch on \"is this the host\": it is\n\t\t * what identity reads, what logs show, and what the transport cache keys on.\n\t\t */\n\t\tlocal: schema.make(\"local\"),\n\t\t/** A fresh identity for a namespace nothing has named yet. */\n\t\tcreate: () => schema.make(`sbx_${uuidv7()}`),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\n/**\n * The storage boundary for namespace references, in one place.\n *\n * The host filesystem exists whether or not a row describes it, so it gets no\n * row and `NULL` is the only spelling of it — the Unix analogue is exact, since\n * `/` has no entry in the mount table you consult to find other mounts. That\n * makes a session or directory writable before any namespace is registered (the\n * foreign key is skipped on NULL), makes `SET sandbox_instance_id = NULL` a\n * meaningful \"revert to the host\", and leaves the host impossible to tombstone,\n * collect, or destroy, because there is nothing to point at.\n *\n * Two SQLite consequences ride on this and break correctness silently if missed:\n * unique indexes treat NULLs as distinct, so every uniqueness constraint\n * spanning a namespace column coalesces to `'local'`; and `= NULL` never\n * matches, so namespace-scoped reads use `IS`.\n */\nexport const toColumn = (id: ID): string | null => (id === ID.local ? null : id);\nexport const fromColumn = (value: string | null): ID => (value === null ? ID.local : ID.make(value));\n\n/**\n * The same mapping for row models, whose optional columns are `Option` rather\n * than `null`. Kept beside {@link toColumn} so the boundary stays one place:\n * `toColumn`/`fromColumn` for SQL parameters, these for `Model.FieldOption`.\n */\nexport const toField = (id: ID): Option.Option<ID> => (id === ID.local ? Option.none() : Option.some(id));\nexport const fromField = (value: Option.Option<ID>): ID => Option.getOrElse(value, () => ID.local);\n\n/**\n * Filesystem-class taxonomy, mirroring Unix: disk, tmpfs/procfs, NFS/CIFS.\n * Stored on the row rather than derived from the registered driver, so reading\n * an instance never depends on the registry — which matters most when a driver\n * is *not* configured and you need to list or clean up its rows.\n */\nexport const Kind = Schema.Literals([\"local\", \"virtual\", \"remote\"]);\nexport type Kind = typeof Kind.Type;\n\nexport const Ownership = Schema.Literals([\"managed\", \"external\"]);\nexport type Ownership = typeof Ownership.Type;\n\n/**\n * Lifecycle state, in ZFS pool vocabulary. This is the **last observed** value,\n * not live driver truth: Daytona auto-stops and auto-archives, Vercel sandboxes\n * expire on their own timeout, so drift is normal. `stateObservedAt` carries the\n * freshness and `Controller.refresh` updates it without waking anything.\n *\n * `removed` and `unavail` are deliberately distinct. `removed` means we deleted\n * it; `unavail` means the driver claims it is gone. A \"not found\" is frequently a\n * misclassification — wrong region, wrong API url, a revoked key answering 404,\n * eventual consistency right after create — so it must never be recorded as if we\n * had destroyed the resource ourselves.\n */\nexport const Status = Schema.Literals([\n\t\"provisioning\",\n\t\"online\",\n\t\"offline\",\n\t\"suspending\",\n\t\"removing\",\n\t\"removed\",\n\t\"unavail\",\n\t\"faulted\",\n]);\nexport type Status = typeof Status.Type;\n\n/**\n * The statuses a `mount` may proceed from. This is the predicate every\n * conditional write depends on, so it is enumerated once here rather than\n * restated as prose at each call site.\n *\n * `offline` qualifies because mounting wakes.\n * `faulted` qualifies because a fault is a *usability* condition, not an identity one — see {@link Status}.\n *\n * There is no `resuming`: it would exist to be observed by nothing, since\n * mounting wakes, `offline` is already mountable, and waking is not destructive\n * so it needs no claim. `suspending` and `removing` stay because they *are*\n * compare-and-set claims, blocking a concurrent mount mid-destruction.\n */\nexport const mountable: ReadonlySet<Status> = new Set<Status>([\"online\", \"offline\", \"faulted\"]);\n\nexport const isMountable = (status: Status): boolean => mountable.has(status);\n\n/**\n * Reference state, derived — never stored. `busy` carries its `umount` meaning:\n * something holds this and destruction must not proceed unforced.\n *\n * `pinned` is the kernel sense of the word: never reclaimable. It short-circuits\n * counting entirely for instances that cannot be stopped or destroyed (the local\n * host), which is what keeps them out of any future collector by construction\n * rather than by an ownership check happening to catch them.\n */\nexport const Usage = Schema.Literals([\"idle\", \"busy\", \"pinned\"]);\nexport type Usage = typeof Usage.Type;\n\n/** Sanitized driver failure. The only error shape allowed to be persisted or logged. */\nexport const PersistedError = Schema.Struct({\n\tname: Schema.String,\n\tmessage: Schema.String,\n\tcode: Schema.optional(Schema.String),\n});\nexport type PersistedError = typeof PersistedError.Type;\n\n/** Durable metadata, safe to return and persist. Assembled by the control plane. */\nexport interface Info {\n\treadonly id: ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: Kind;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly ownership: Ownership;\n\treadonly status: Status;\n\treadonly usage: Usage;\n\t/** References held by *this* control plane. Process-local; see the transport cache. */\n\treadonly refCount: number;\n\treadonly providerStatus: Option.Option<string>;\n\treadonly metadata: Readonly<Record<string, string>>;\n\treadonly lastError: Option.Option<PersistedError>;\n\treadonly createdAt: Date;\n\treadonly updatedAt: Date;\n\treadonly stateObservedAt: Date;\n\treadonly lastMountedAt: Option.Option<Date>;\n\treadonly lastUnmountedAt: Option.Option<Date>;\n\treadonly lastUsedAt: Option.Option<Date>;\n\treadonly removedAt: Option.Option<Date>;\n}\n\nexport * as SandboxInstance from \"./instance.ts\";\n","import { Schema } from \"effect\";\nimport { withStatics } from \"../../schema.ts\";\n\n// TODO: add support for diff input types\n// as supported by packages/aikit\nexport const Prompt = Schema.Struct({\n\ttext: Schema.String,\n})\n\t.annotate({ identifier: \"Prompt\" })\n\t.pipe(\n\t\twithStatics((schema) => ({\n\t\t\tequivalence: Schema.toEquivalence(schema),\n\t\t\tfromUserMessage: (input: Pick<Prompt, \"text\">) =>\n\t\t\t\tschema.make({\n\t\t\t\t\ttext: input.text,\n\t\t\t\t}),\n\t\t})),\n\t);\nexport type Prompt = typeof Prompt.Type;\n\nexport const Delivery = Schema.Literals([\"steer\", \"followUp\"]);\nexport type Delivery = typeof Delivery.Type;\n\nexport * as PromptSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { 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, optional } 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\nexport 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});\nexport 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\tConfigChanged,\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","// API that deals with event\n\nimport { Effect, Context, Layer, Option, PubSub, Cause, 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 { EventSchema } from \"./schema.ts\";\nimport { EventManifest } from \"./manifest.ts\";\nimport type { Data, Definition, ID, Payload } 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\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\tdurable: new Map<string, Set<PubSub.PubSub<void>>>(),\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\tyield* Effect.forEach(\n\t\t\t\t\tpubsub.durable.values(),\n\t\t\t\t\t(wakes) => Effect.forEach(wakes, PubSub.shutdown, { discard: true }),\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\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\t// Durable subscribers carry no payload -- they re-read from their own\n\t\t\t\t// cursor, so one content-free wake per aggregate is enough.\n\t\t\t\tyield* Effect.forEach(pubsub.durable.get(aggregateId) ?? [], (wake) => PubSub.publish(wake, undefined), {\n\t\t\t\t\tdiscard: true,\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 tail = streamAll().pipe(\n\t\t\t\tStream.filter((event) => (event.data as { readonly sessionId?: unknown }).sessionId === input.sessionId),\n\t\t\t);\n\t\t\tif (input.after === undefined) return tail;\n\n\t\t\tconst history = Stream.paginate(\n\t\t\t\tinput.after,\n\t\t\t\tEffect.fn(\"Event.stream.history\")(function* (after) {\n\t\t\t\t\tconst page = yield* readAggregate({\n\t\t\t\t\t\taggregateId: input.sessionId,\n\t\t\t\t\t\tafter,\n\t\t\t\t\t\tlimit: 100,\n\t\t\t\t\t\tmanifest: EventManifest.Manifest,\n\t\t\t\t\t});\n\t\t\t\t\tconst last = page.events.at(-1);\n\t\t\t\t\tconst next =\n\t\t\t\t\t\tpage.hasMore && last?.durable !== undefined ? Option.some(last.durable.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\t\t\treturn history.pipe(\n\t\t\t\tStream.map((event) => event as Payload),\n\t\t\t\tStream.concat(tail),\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 EntryType,\n\tentryStates,\n\tentryTypes,\n\ttype EntryState,\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 EntryType,\n\ttype EntryState,\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\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, Model } 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 EffectiveConfig {\n\treadonly model?: {\n\t\treadonly providerId: string;\n\t\treadonly modelId: string;\n\t};\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n}\n\nexport interface Snapshot {\n\treadonly sessionId: string;\n\treadonly leafEntryId: string | null;\n\treadonly messages: ReadonlyArray<Message.Message>;\n\treadonly config: EffectiveConfig;\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 ConfigChangeData = Schema.fromJsonString(\n\tSchema.Struct({\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\nconst decodeSyntheticData = Schema.decodeUnknownEffect(SyntheticData);\nconst decodeCompactionData = Schema.decodeUnknownEffect(SessionSchema.CompactionData);\nconst decodeBranchSummaryData = Schema.decodeUnknownEffect(BranchSummaryData);\nconst decodeCustomData = Schema.decodeUnknownEffect(CustomData);\nconst decodeConfigChangeData = Schema.decodeUnknownEffect(ConfigChangeData);\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 model: EffectiveConfig[\"model\"];\n\tlet thinkingLevel: Model.ThinkingLevel | undefined;\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\tmodel = { providerId: message.provider.id, modelId: message.model };\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\tcase \"configChange\": {\n\t\t\t\tconst data = yield* decodeConfigChangeData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tif (data.model !== undefined) model = data.model;\n\t\t\t\tif (data.thinkingLevel !== undefined) thinkingLevel = data.thinkingLevel;\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\tconfig: {\n\t\t\t...(model === undefined ? {} : { model }),\n\t\t\t...(thinkingLevel === undefined ? {} : { thinkingLevel }),\n\t\t},\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 \"../../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, Schema } from \"effect\";\nimport { posix } from \"../../posix.ts\";\n\n/**\n * The runtime filesystem contract, independent of any backend.\n *\n * Two surfaces, deliberately:\n * - {@link Provider} is what a backend implements — plain promises that reject,\n * matching every SDK we wrap.\n * - {@link Interface} is what the harness consumes — Effect with a typed error\n * channel and tracing spans. {@link fromProvider} bridges the two exactly\n * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.\n *\n * Implementations:\n * - Local:\n * implement it over a VFS (`./local`);\n * local filesystem use OS primitives; hence have broader filesytem capabilities.\n *\n * - Remote:\n * implement it over a provider (`./remote`).\n * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.\n *\n * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the\n * backend cannot report them — never fabricated.\n *\n * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`\n * separators on both the host and inside a sandbox — Windows is not supported,\n * so no translation layer exists. Consumers must use the shared Effect POSIX\n * path implementation, never the platform default, or a host running the harness would\n * impose its own flavour on a remote sandbox's paths. Relative paths resolve\n * against the backend's configured `cwd`.\n */\n\nexport class OperationUnsupportedError extends Schema.TaggedError<OperationUnsupportedError>()(\n\t\"OperationUnsupportedError\",\n\t{\n\t\toperation: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n/** A backend operation failed. `cause` carries the provider's own rejection. */\nexport class FileSystemError extends Schema.TaggedError<FileSystemError>()(\"SandboxFileSystemError\", {\n\tmethod: Schema.String,\n\tpath: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface FileStat {\n\treadonly isFile: boolean;\n\treadonly isDirectory: boolean;\n\treadonly isSymbolicLink?: boolean;\n\treadonly size?: number;\n\treadonly mtime?: Date;\n}\n\nexport interface RmOptions {\n\treadonly recursive?: boolean;\n\treadonly force?: boolean;\n}\n\n/** Whether a provider failure means the path itself is definitively absent. */\nexport const isNotFoundError = (cause: unknown) => {\n\tconst code = (cause as NodeJS.ErrnoException | undefined)?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n};\n\n/**\n * The backend-facing contract. Backends author plain promises and let them\n * reject; {@link fromProvider} turns rejections into typed failures.\n */\nexport interface Provider {\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly readFileBuffer: (path: string) => Promise<Uint8Array>;\n\t/**\n\t * Write the file. Parents may be missing — do not create them here;\n\t * {@link fromProvider} owns that guarantee for every backend.\n\t */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Promise<void>;\n\treadonly stat: (path: string) => Promise<FileStat>;\n\treadonly readdir: (path: string) => Promise<string[]>;\n\treadonly exists: (path: string) => Promise<boolean>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n\treadonly rm: (path: string, options?: RmOptions) => Promise<void>;\n\t/**\n\t * Metadata for the directory entry itself rather than a symlink's target.\n\t * Optional: a backend whose `stat` has mixed symlink semantics implements it\n\t * so symlink identity is asked for explicitly, never inferred.\n\t */\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\n/**\n * The consumer-facing contract. `exists` distinguishes \"absent\" from \"could not\n * tell\": a backend failure is a typed failure, not `false`, so a caller acting\n * on absence never acts on a network blip. Use `SandboxFs.existsOrFalse` where\n * a best-effort answer really is wanted.\n */\nexport interface Interface {\n\treadonly readFile: (path: string) => Effect.Effect<string, FileSystemError>;\n\treadonly readFileBuffer: (path: string) => Effect.Effect<Uint8Array, FileSystemError>;\n\t/** Creates missing parent directories, on every backend. */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Effect.Effect<void, FileSystemError>;\n\treadonly stat: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n\treadonly readdir: (path: string) => Effect.Effect<string[], FileSystemError>;\n\treadonly exists: (path: string) => Effect.Effect<boolean, FileSystemError>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Effect.Effect<void, FileSystemError>;\n\treadonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;\n\t// `lstat` is present only when the backend supports it; check before calling.\n\treadonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n}\n\n/** The runtime filesystem service — the live {@link Interface} for the active sandbox. */\nexport class Service extends Context.Service<Service, Interface>()(\n\t\"@codeworksh/harness/sandbox/fs/filesystem/Service\",\n) {}\n\n/**\n * Reject `rm` options a provider does not implement, before any mutation. Only\n * `recursive` and `force` are part of the contract; anything else is refused\n * loudly rather than silently ignored.\n */\nexport const validateRmOptions = (\n\toptions: RmOptions | undefined,\n\toperation = \"rm\",\n): Effect.Effect<void, OperationUnsupportedError> =>\n\tEffect.suspend(() => {\n\t\tfor (const option of Object.keys((options ?? {}) as Record<string, unknown>)) {\n\t\t\tif (option === \"recursive\" || option === \"force\") continue;\n\t\t\treturn Effect.fail(new OperationUnsupportedError({ operation, message: `Unsupported rm option: ${option}` }));\n\t\t}\n\t\treturn Effect.void;\n\t});\n\n/**\n * Lift a {@link Provider} into the runtime {@link Interface}: one place that\n * converts rejections into {@link FileSystemError}, validates `rm` options,\n * creates missing parents on write, and names a tracing span per operation.\n */\nexport const fromProvider = (provider: Provider): Interface => {\n\tconst attempt = <A>(method: string, path: string, run: () => Promise<A>) =>\n\t\tEffect.tryPromise({ try: run, catch: (cause) => new FileSystemError({ method, path, cause }) });\n\n\t// The parent-creation guarantee, installed once for every backend instead of\n\t// re-implemented per provider: anything that reaches `Interface` reaches it\n\t// through here, so a backend cannot forget it.\n\t//\n\t// Lazy by design — try the write first, so the happy path stays a single call\n\t// and no remote backend pays a round-trip per write. A failure is usually a\n\t// missing parent, so create it and retry once. The mkdir's own error is\n\t// dropped on purpose: when the write failed for some other reason (EACCES,\n\t// EROFS, a dropped connection), the retry reproduces it, and *that* is the\n\t// failure the caller must see rather than a misleading mkdir error standing\n\t// in for it.\n\tconst writeCreatingParents = (path: string, content: string | Uint8Array) => {\n\t\tconst write = attempt(\"writeFile\", path, () => provider.writeFile(path, content));\n\t\tconst parent = posix.dirname(path);\n\t\treturn write.pipe(\n\t\t\tEffect.catch(() =>\n\t\t\t\tattempt(\"mkdir\", parent, () => provider.mkdir(parent, { recursive: true })).pipe(\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.andThen(write),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\treturn {\n\t\treadFile: Effect.fn(\"SandboxFileSystem.readFile\")((path: string) =>\n\t\t\tattempt(\"readFile\", path, () => provider.readFile(path)),\n\t\t),\n\t\treadFileBuffer: Effect.fn(\"SandboxFileSystem.readFileBuffer\")((path: string) =>\n\t\t\tattempt(\"readFileBuffer\", path, () => provider.readFileBuffer(path)),\n\t\t),\n\t\twriteFile: Effect.fn(\"SandboxFileSystem.writeFile\")(writeCreatingParents),\n\t\tstat: Effect.fn(\"SandboxFileSystem.stat\")((path: string) => attempt(\"stat\", path, () => provider.stat(path))),\n\t\t// carried through only when the backend actually implements it\n\t\t...(provider.lstat === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlstat: Effect.fn(\"SandboxFileSystem.lstat\")((path: string) =>\n\t\t\t\t\t\tattempt(\"lstat\", path, () => provider.lstat!(path)),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treaddir: Effect.fn(\"SandboxFileSystem.readdir\")((path: string) =>\n\t\t\tattempt(\"readdir\", path, () => provider.readdir(path)),\n\t\t),\n\t\t// A backend that cannot answer fails; it does not report \"absent\". A\n\t\t// caller acting on absence — deleting a record, say — must not be told\n\t\t// the path is gone because a token expired or a request timed out.\n\t\texists: Effect.fn(\"SandboxFileSystem.exists\")((path: string) =>\n\t\t\tattempt(\"exists\", path, () => provider.exists(path)),\n\t\t),\n\t\tmkdir: Effect.fn(\"SandboxFileSystem.mkdir\")((path: string, options?: { recursive?: boolean }) =>\n\t\t\tattempt(\"mkdir\", path, () => provider.mkdir(path, options)),\n\t\t),\n\t\trm: Effect.fn(\"SandboxFileSystem.rm\")((path: string, options?: RmOptions) =>\n\t\t\tvalidateRmOptions(options).pipe(Effect.andThen(attempt(\"rm\", path, () => provider.rm(path, options)))),\n\t\t),\n\t};\n};\n\n/**\n * Bind a cwd-neutral filesystem to one mount's working directory.\n *\n * The counterpart of `Shell.withCwd`, and the reason relative paths mean the\n * same thing to both: a shared transport stays rooted at the namespace root, so\n * resolution happens here, per mount, rather than inside a VFS whose `chdir` is\n * global state two mounts would fight over.\n */\nexport const withCwd = (fs: Interface, cwd: string): Interface => {\n\tconst at = (path: string) => posix.resolve(cwd, path);\n\treturn {\n\t\treadFile: (path) => fs.readFile(at(path)),\n\t\treadFileBuffer: (path) => fs.readFileBuffer(at(path)),\n\t\twriteFile: (path, content) => fs.writeFile(at(path), content),\n\t\tstat: (path) => fs.stat(at(path)),\n\t\treaddir: (path) => fs.readdir(at(path)),\n\t\texists: (path) => fs.exists(at(path)),\n\t\tmkdir: (path, options) => fs.mkdir(at(path), options),\n\t\trm: (path, options) => fs.rm(at(path), options),\n\t\t// carried through only when the backend implements it, so a caller can\n\t\t// still detect absence by checking the property\n\t\t...(fs.lstat === undefined ? {} : { lstat: (path: string) => fs.lstat!(at(path)) }),\n\t};\n};\n\nexport * as SandboxFileSystem from \"./filesystem.ts\";\n","import { Context, type Effect, Schema, type Stream } from \"effect\";\nimport { posix as path } from \"../../posix.ts\";\n\n/**\n * The pluggable execution contract. Local sandboxes usually get a Shell through\n * just-bash over the local `Local.Vfs`; remote sandboxes provide their own\n * native Shell. Either way the rest of the harness depends only on this service\n * tag.\n */\n\nexport class ShellError extends Schema.TaggedError<ShellError>()(\"ShellError\", {\n\tcommand: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface ExecResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number;\n}\n\n/**\n * One options shape for every entry point. `cwd` is the operation-level\n * override: it wins over the mount's working directory, and a relative value\n * resolves against it. Neither mutates shared state, so concurrent commands in\n * one mount can run in different directories.\n */\nexport interface ShellOptions {\n\treadonly env?: Record<string, string>;\n\treadonly cwd?: string;\n}\n\n/**\n * A streamed chunk of command output, terminated by a single `exit` carrying the\n * exit code. (A backend-level mirror of the tool layer's event; kept here so\n * `sandbox/` does not depend on `tools/`.)\n */\nexport type ExecChunk =\n\t| { readonly _tag: \"stdout\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"stderr\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"exit\"; readonly exitCode: number };\n\n/**\n * The command-execution capability a sandbox exposes. For an in-process\n * backend this is just-bash; for a remote backend it is the sandbox's own\n * shell. The {@link Shell} service tag carries this interface.\n */\nexport interface ISandboxExe {\n\treadonly exec: (command: string, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Run a program with an explicit argument vector, bypassing shell word\n\t * splitting. Callers that build commands from untrusted values — branch\n\t * names, file paths — must use this instead of interpolating into\n\t * {@link exec}, where a space or `$(…)` would change what runs.\n\t *\n\t * Backends whose transport only accepts a string quote the vector with\n\t * {@link quote}; backends that spawn directly pass it through untouched.\n\t */\n\treadonly execArgv: (argv: ReadonlyArray<string>, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Optional streaming output: stdout/stderr chunks then a terminal `exit`.\n\t * Backends that can stream (e.g. Vercel) implement it; `ToolShell.fromSandboxShell`\n\t * bridges it to `ToolShell.stream` so the bash tool streams over them too.\n\t */\n\treadonly stream?: (command: string, options?: ShellOptions) => Stream.Stream<ExecChunk, ShellError>;\n}\n\ntype MountFactory = (cwd: string) => ISandboxExe;\n\n/**\n * Mount-local shell factories are attached out-of-band so the public Shell\n * contract stays about command execution only.\n *\n * Most transports are safely shared and need only the cwd wrapper below.\n * Stateful in-process interpreters use this hook to construct one interpreter\n * per mount while retaining the underlying filesystem transport. This tag must\n * remain on the outermost wrapper consumed by {@link withCwd}; wrapper helpers\n * such as {@link fromExec} must propagate it when they return a new object.\n */\nconst mountFactories = new WeakMap<object, MountFactory>();\n\nexport const perMount = (transport: ISandboxExe, make: MountFactory): ISandboxExe => {\n\tmountFactories.set(transport, make);\n\treturn transport;\n};\n\n/**\n * POSIX single-quote escaping: wrap in `'…'` and rewrite each embedded quote as\n * `'\\''`. Everything inside single quotes is literal to the shell, so this is\n * safe for arbitrary bytes.\n */\nexport const quote = (value: string) => `'${value.replace(/'/g, `'\\\\''`)}'`;\n\n/** Render an argument vector as one shell-safe command string. */\nexport const quoteArgv = (argv: ReadonlyArray<string>) => argv.map(quote).join(\" \");\n\n/**\n * Resolve a per-command cwd against the sandbox cwd. Passing a relative cwd\n * straight to a host or remote process API would otherwise resolve it against\n * that API's own default, which need not be the filesystem's configured cwd.\n */\nexport const resolveCwd = (base: string | undefined, cwd: string | undefined) => {\n\tif (cwd === undefined || path.isAbsolute(cwd) || base === undefined) return cwd ?? base;\n\treturn path.resolve(base, cwd);\n};\n\n/**\n * Complete a string-only backend: `execArgv` quotes the vector and runs it\n * through `exec`. Backends that spawn a real argument vector (Vercel) implement\n * `execArgv` themselves instead, so the args never meet a shell parser at all.\n *\n * `cwd` rides the options rather than a `cd <dir> && …` prefix. Every backend\n * we wrap takes a working directory natively, and the prefix form cannot tell a\n * failed `cd` from a failed command — both arrive as one exit code.\n */\nexport const fromExec = (backend: Omit<ISandboxExe, \"execArgv\">): ISandboxExe => {\n\tconst wrapped: ISandboxExe = {\n\t\t...backend,\n\t\texecArgv: (argv, options) => backend.exec(quoteArgv(argv), options),\n\t};\n\tconst mountFactory = mountFactories.get(backend);\n\treturn mountFactory === undefined ? wrapped : perMount(wrapped, (cwd) => fromExec(mountFactory(cwd)));\n};\n\n/**\n * Bind a cwd-neutral backend to one mount's working directory.\n *\n * The transport is shared between mounts and must stay rooted at the namespace\n * root, so the directory cannot live inside it: two mounts at different\n * directories would otherwise see each other's. This wrapper is per mount, and\n * an operation-level `cwd` still wins — resolved against the mount's, so a\n * relative one means what it reads like.\n */\nexport const withCwd = (backend: ISandboxExe, cwd: string): ISandboxExe => {\n\tconst mounted = mountFactories.get(backend)?.(cwd) ?? backend;\n\tconst at = (options?: ShellOptions): ShellOptions => {\n\t\tconst resolvedCwd = resolveCwd(cwd, options?.cwd);\n\t\treturn { ...options, ...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }) };\n\t};\n\tconst stream = mounted.stream;\n\treturn {\n\t\texec: (command, options) => mounted.exec(command, at(options)),\n\t\texecArgv: (argv, options) => mounted.execArgv(argv, at(options)),\n\t\t...(stream === undefined ? {} : { stream: (command, options) => stream(command, at(options)) }),\n\t};\n};\n\n/** Execution service — the live {@link ISandboxExe} for the active sandbox. */\nexport class Shell extends Context.Service<Shell, ISandboxExe>()(\"@codeworksh/harness/sandbox/shell/shell\") {}\n","import { Context, Effect, Layer as EffectLayer } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\nimport { SandboxFileSystem } from \"./fs/filesystem.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { type ISandboxExe, Shell as ShellTag, withCwd as shellWithCwd } from \"./shell/shell.ts\";\n\n/**\n * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and\n * working directory they act on.\n *\n * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and\n * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and\n * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so\n * a host directory, an in-memory VFS, and a remote microVM are interchangeable\n * behind one contract.\n *\n * The mount neither creates nor destroys infrastructure. `SandboxInstance` is\n * the durable namespace it acts on — a device, which exists whether or not\n * anything has it mounted — and `Sandbox.Controller` is the only path that\n * creates, stops, or destroys one.\n */\n\n/**\n * The filesystem tag. Re-exported here so consumers import one namespace —\n * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for\n * the module that happens to define it. Code *inside* `sandbox/` keeps importing\n * the tag directly, since `io.ts` is built on top of it.\n */\nexport const FileSystem = SandboxFileSystem.Service;\nexport type FileSystem = SandboxFileSystem.Service;\n\n/** The shell tag. Re-exported here so consumers import one namespace. */\nexport const Shell = ShellTag;\nexport type Shell = ShellTag;\n\n/**\n * What a mount sees: immutable identity, plus the working directory resolved for\n * *this* mount.\n *\n * Nothing mutable belongs here. `status`, `usage`, and reference counts all\n * change while a mount is open, so a mount-time snapshot of them would be wrong\n * by construction — runtime code that needs live management state asks the\n * control plane. The driver's own resource locator is likewise absent: consumers\n * never parse a Vercel name or a Daytona id.\n */\nexport interface Identity {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: SandboxInstance.Kind;\n\t/** Absolute, and always a path in *this* namespace. */\n\treadonly cwd: string;\n}\n\n/** Identity and working directory of the current mount. */\nexport class Current extends Context.Service<Current, Identity>()(\"@codeworksh/harness/sandbox/io/Current\") {}\n\n/** Everything a mount provides. */\nexport type Provides = Current | SandboxFileSystem.Service | ShellTag;\n\n/** A built mount. */\nexport type Layer<E = never, RIn = never> = EffectLayer.Layer<Provides, E, RIn>;\n\n/**\n * Resolve a mount's cwd without consulting ambient process state.\n *\n * The default is supplied by the namespace adapter:\n * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.\n * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The\n * result is therefore always the one concrete absolute path `Current` requires.\n *\n * A non-absolute default throws rather than failing typed. It is the one\n * defect-level guard in this module, and deliberately so:\n * Adapters reading a value from a provider call this inside their own error channel,\n * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).\n */\nexport const resolveMountCwd = (defaultCwd: string, cwd?: string): string => {\n\tif (!posix.isAbsolute(defaultCwd)) {\n\t\tthrow new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);\n\t}\n\t// `resolve`, not `normalize`: normalize keeps a trailing slash, and `cwd` is\n\t// persisted — `Location.directory` and `project_directory`'s hash would read\n\t// `/workspace/` and `/workspace` as two directories and keep a row for each.\n\t//\n\t// A provider-reported default (`getWorkDir()`) or a config value is free to\n\t// carry one, so it is stripped here rather than at every reader.\n\tif (cwd === undefined) return posix.resolve(defaultCwd);\n\treturn posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);\n};\n\n/**\n * Bind a cwd-neutral transport to one mount.\n *\n * The transport underneath is shared between\n * mounts and stays rooted at the namespace root, and everything directory-shaped\n * happens here, once per mount. Two mounts of one namespace at different working\n * directories therefore coexist without seeing or moving each other's.\n *\n * It consumes the same two tags it provides — the transport is supplied by the\n * layer this is composed over, not by itself.\n */\nexport const mount = (identity: Identity): EffectLayer.Layer<Provides, never, SandboxFileSystem.Service | ShellTag> =>\n\tEffectLayer.mergeAll(\n\t\tEffectLayer.succeed(Current, identity),\n\t\tEffectLayer.effect(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tEffect.map(SandboxFileSystem.Service, (fs) => SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t),\n\t\tEffectLayer.effect(\n\t\t\tShellTag,\n\t\t\tEffect.map(ShellTag, (shell: ISandboxExe) => shellWithCwd(shell, identity.cwd)),\n\t\t),\n\t);\n\n/**\n * Just the identity tag, with no filesystem or shell beneath it. For consumers\n * assembled from stubs — a test that runs `Project` over a fake filesystem still\n * needs to know which namespace it is in.\n */\nexport const identityLayer = (identity: Identity) => EffectLayer.succeed(Current, identity);\n\n/** The host identity alone. See {@link identityLayer}. */\nexport const hostLayer = (cwd?: string) => identityLayer(host(cwd));\n\n/**\n * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working\n * directory selects where relative paths resolve, it does not make a second host\n * namespace — two mounts rooted at different directories still agree on absolute\n * paths.\n *\n * The host adapter defaults to `process.cwd()`, matching the OS process it wraps.\n * This is the one namespace where that coordinate is intrinsically valid; remote\n * and virtual adapters must never inherit it.\n */\nexport const host = (cwd?: string): Identity => ({\n\tid: SandboxInstance.ID.local,\n\tdriver: \"local\" as SandboxDriver.Name,\n\tkind: \"local\",\n\tcwd: resolveMountCwd(process.cwd(), cwd),\n});\n\n/**\n * A VFS-backed namespace. The id is minted per call unless one is named, because\n * building one of these builds a fresh VFS: N unnamed calls are N distinct\n * namespaces, none of which outlives the process. A file-backed store is the\n * exception — its file is the state, so whoever knows the file supplies the id\n * it was registered under.\n */\nexport const virtual = (input: {\n\treadonly driver: string;\n\treadonly id?: SandboxInstance.ID;\n\treadonly defaultCwd?: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id ?? SandboxInstance.ID.create(),\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"virtual\",\n\tcwd: resolveMountCwd(input.defaultCwd ?? \"/\", input.cwd),\n});\n\n/**\n * A provider-hosted namespace. The id is always supplied: a remote resource's\n * durable identity is minted and recorded by whoever provisioned it, never\n * derived here from the provider's own locator.\n */\nexport const remote = (input: {\n\treadonly driver: string;\n\treadonly id: SandboxInstance.ID;\n\t/** Namespace-intrinsic default supplied or discovered by the driver. */\n\treadonly defaultCwd: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id,\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"remote\",\n\tcwd: resolveMountCwd(input.defaultCwd, input.cwd),\n});\n\nexport * as SandboxIO from \"./io.ts\";\n","import { Schema } from \"effect\";\nimport { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Lifecycle errors are confined to the control plane. Once a mount succeeds,\n * consumers continue to see only FileSystemError and ShellError.\n */\nexport class SandboxNotFoundError extends Schema.TaggedError<SandboxNotFoundError>()(\"SandboxNotFoundError\", {\n\tid: SandboxInstance.ID,\n}) {}\n\nexport class SandboxDriverNotRegisteredError extends Schema.TaggedError<SandboxDriverNotRegisteredError>()(\n\t\"SandboxDriverNotRegisteredError\",\n\t{\n\t\tdriver: Schema.String,\n\t},\n) {}\n\nexport class SandboxDriverRegistrationError extends Schema.TaggedError<SandboxDriverRegistrationError>()(\n\t\"SandboxDriverRegistrationError\",\n\t{\n\t\tdriver: Schema.String,\n\t\treason: Schema.String,\n\t},\n) {}\n\nexport class SandboxBusyError extends Schema.TaggedError<SandboxBusyError>()(\"SandboxBusyError\", {\n\tid: SandboxInstance.ID,\n\trefCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nexport class SandboxMustBeStoppedError extends Schema.TaggedError<SandboxMustBeStoppedError>()(\n\t\"SandboxMustBeStoppedError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\tstatus: SandboxInstance.Status,\n\t},\n) {}\n\nexport class SandboxRemovedError extends Schema.TaggedError<SandboxRemovedError>()(\"SandboxRemovedError\", {\n\tid: SandboxInstance.ID,\n\tremovedAt: Schema.optional(Schema.DateTimeUtc),\n}) {}\n\nexport class SandboxUnavailError extends Schema.TaggedError<SandboxUnavailError>()(\"SandboxUnavailError\", {\n\tid: SandboxInstance.ID,\n\treason: Schema.String,\n}) {}\n\nexport class SandboxUnsupportedError extends Schema.TaggedError<SandboxUnsupportedError>()(\"SandboxUnsupportedError\", {\n\tid: SandboxInstance.ID,\n\tdriver: Schema.String,\n\toperation: Schema.String,\n}) {}\n\nexport class SandboxTransitionConflictError extends Schema.TaggedError<SandboxTransitionConflictError>()(\n\t\"SandboxTransitionConflictError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\texpected: Schema.Array(SandboxInstance.Status),\n\t\tactual: SandboxInstance.Status,\n\t},\n) {}\n\n/**\n * A lifecycle failure safe to serialize, persist, or log.\n *\n * The raw SDK defect is deliberately absent from the schema. It is retained on\n * a non-enumerable symbol by {@link providerError}, so Effect's default\n * formatting and JSON serialization cannot expose credentials nested in it.\n */\nexport class SandboxProviderError extends Schema.TaggedError<SandboxProviderError>()(\"SandboxProviderError\", {\n\tdriver: Schema.String,\n\toperation: Schema.String,\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nconst rawCause = Symbol(\"@codework/sandbox/provider/error/raw/cause\");\nconst missingResource = Symbol(\"@codework/sandbox/provider/error/missing/resource\");\n\nexport const providerErrorCause = (error: SandboxProviderError): unknown =>\n\t(error as SandboxProviderError & { readonly [rawCause]?: unknown })[rawCause];\n\nexport const providerErrorIsNotFound = (error: SandboxProviderError): boolean =>\n\t(error as SandboxProviderError & { readonly [missingResource]?: boolean })[missingResource] === true;\n\nexport type Redactor = (value: string) => string;\n\nconst REDACTED = \"<redacted>\";\n\n/**\n * Conservative text redaction shared by every driver sanitizer.\n *\n * Disclaimer: This can really leak. Its never safe\n *\n * Configured secrets are removed exactly. Common authorization/header and URL\n * query shapes are masked as a second line of defence for values the caller did\n * not explicitly seed.\n *\n * Note: add support for diff regex as needed.\n */\nexport const makeRedactor = (secrets: Iterable<string> = []): Redactor => {\n\tconst configured = [...secrets].filter((secret) => secret.length > 0).sort((a, b) => b.length - a.length);\n\treturn (value) => {\n\t\tlet redacted = value;\n\t\tfor (const secret of configured) redacted = redacted.replaceAll(secret, REDACTED);\n\t\treturn redacted\n\t\t\t.replace(/\\b(authorization\\s*:\\s*(?:bearer|basic)\\s+)[^\\s,;]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b((?:api[-_]?key|token|secret|password)\\s*[=:]\\s*)[^\\s,;&]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/([?&](?:access_token|api_key|token|secret|password)=)[^&#\\s]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\\b/g, REDACTED);\n\t};\n};\n\nconst errorCode = (cause: unknown): string | undefined => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"code\" in cause)) return undefined;\n\tconst code = cause.code;\n\treturn typeof code === \"string\" || typeof code === \"number\" ? String(code) : undefined;\n};\n\nconst errorName = (cause: unknown): string => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"name\" in cause) || typeof cause.name !== \"string\")\n\t\treturn \"Error\";\n\treturn cause.name;\n};\n\nconst errorMessage = (cause: unknown): string => {\n\tif (typeof cause === \"object\" && cause !== null && \"message\" in cause && typeof cause.message === \"string\")\n\t\treturn cause.message;\n\treturn String(cause);\n};\n\nexport const sanitizeError = (cause: unknown, redact: Redactor = makeRedactor()): SandboxInstance.PersistedError => {\n\tconst code = errorCode(cause);\n\treturn {\n\t\tname: redact(errorName(cause)),\n\t\tmessage: redact(errorMessage(cause)),\n\t\t...(code === undefined ? {} : { code: redact(code) }),\n\t};\n};\n\nexport const providerError = (input: {\n\treadonly driver: string;\n\treadonly operation: string;\n\treadonly cause: unknown;\n\treadonly redact?: Redactor;\n\treadonly notFound?: boolean;\n}): SandboxProviderError => {\n\tconst error = new SandboxProviderError({\n\t\tdriver: input.driver,\n\t\toperation: input.operation,\n\t\tsanitized: sanitizeError(input.cause, input.redact),\n\t});\n\tObject.defineProperty(error, rawCause, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.cause,\n\t\twritable: false,\n\t});\n\tObject.defineProperty(error, missingResource, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.notFound === true,\n\t\twritable: false,\n\t});\n\treturn error;\n};\n\nexport type SandboxMountError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxRemovedError\n\t| SandboxProviderError;\n\nexport type SandboxCreateError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxProviderError;\n\nexport type SandboxRegisterError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxProviderError;\n\nexport type SandboxReadError = never;\n\nexport type SandboxRefreshError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxUnsupportedError\n\t| SandboxProviderError;\n\nexport type SandboxWakeError = SandboxRefreshError | SandboxRemovedError;\n\nexport type SandboxStopError = SandboxWakeError | SandboxBusyError | SandboxTransitionConflictError;\n\nexport type SandboxDestroyError = SandboxStopError | SandboxMustBeStoppedError;\n\nexport * as SandboxError from \"./errors.ts\";\n","import { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport {\n\tSandboxDriverNotRegisteredError,\n\tSandboxDriverRegistrationError,\n\ttype SandboxProviderError,\n} from \"./errors.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\n\n/** Open driver identity. Adding a driver never extends a union in core. */\nexport const Name = Schema.String.check(Schema.isNonEmpty()).pipe(Schema.brand(\"SandboxDriver.Name\"));\nexport type Name = typeof Name.Type;\n\n/** A path whose coordinate system is the mounted namespace. */\nexport const AbsolutePath = Schema.String.check(Schema.isStartsWith(\"/\")).pipe(\n\tSchema.brand(\"SandboxDriver.AbsolutePath\"),\n);\nexport type AbsolutePath = typeof AbsolutePath.Type;\n\nexport const RuntimeConfigBase = Schema.Struct({\n\tdefaultCwd: AbsolutePath,\n});\nexport interface RuntimeConfigBase extends Schema.Schema.Type<typeof RuntimeConfigBase> {}\n\nexport interface Capabilities {\n\treadonly reattach: boolean;\n\treadonly wake: boolean;\n\treadonly stop: boolean;\n\treadonly destroy: boolean;\n\treadonly cancels: boolean;\n}\n\nexport interface Observed {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus?: string | undefined;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface Provisioned<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly providerResourceId?: string | undefined;\n\treadonly providerStatus?: string | undefined;\n\treadonly runtimeConfig: RuntimeConfig;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface RuntimeInput<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly id: SandboxInstance.ID;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly runtimeConfig: RuntimeConfig;\n}\n\nexport interface Driver<CreateConfig, RuntimeConfig extends RuntimeConfigBase> {\n\treadonly name: Name;\n\treadonly kind: SandboxInstance.Kind;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<CreateConfig, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfig, unknown>;\n\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: CreateConfig;\n\t}) => Effect.Effect<Provisioned<RuntimeConfig>, SandboxProviderError>;\n\n\treadonly runtimeConfigFor: (input: {\n\t\treadonly providerResourceId: string;\n\t\treadonly overrides?: Partial<RuntimeConfig> | undefined;\n\t}) => Effect.Effect<RuntimeConfig, SandboxProviderError>;\n\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfig>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nexport type Definition<CreateConfig, RuntimeConfig extends RuntimeConfigBase> = Pick<\n\tDriver<CreateConfig, RuntimeConfig>,\n\t\"name\" | \"createConfigCodec\" | \"runtimeConfigCodec\"\n>;\n\n/**\n * The registry's type-erased shape. Erasure happens once at registration;\n * untrusted values still cross the registered driver's codecs before reaching\n * its typed implementation.\n */\nexport interface Registered {\n\treadonly name: Name;\n\treadonly kind: SandboxInstance.Kind;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<unknown, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfigBase, unknown>;\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: unknown;\n\t}) => Effect.Effect<Provisioned<RuntimeConfigBase>, SandboxProviderError>;\n\treadonly runtimeConfigFor: (input: {\n\t\treadonly providerResourceId: string;\n\t\treadonly overrides?: Readonly<Record<string, unknown>> | undefined;\n\t}) => Effect.Effect<RuntimeConfigBase, SandboxProviderError>;\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfigBase>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nconst erase = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tdriver: Driver<CreateConfig, RuntimeConfig>,\n): Registered => ({\n\tname: driver.name,\n\tkind: driver.kind,\n\tcapabilities: driver.capabilities,\n\tcreateConfigCodec: driver.createConfigCodec as Schema.Codec<unknown, unknown>,\n\truntimeConfigCodec: driver.runtimeConfigCodec as Schema.Codec<RuntimeConfigBase, unknown>,\n\tcreate: (input) => driver.create({ instanceId: input.instanceId, config: input.config as CreateConfig }),\n\truntimeConfigFor: (input) =>\n\t\tdriver.runtimeConfigFor({\n\t\t\tproviderResourceId: input.providerResourceId,\n\t\t\t...(input.overrides === undefined ? {} : { overrides: input.overrides as Partial<RuntimeConfig> }),\n\t\t}),\n\tattach: (input) => driver.attach(input as RuntimeInput<RuntimeConfig>),\n\t...(driver.inspect === undefined\n\t\t? {}\n\t\t: { inspect: (input: RuntimeInput<RuntimeConfigBase>) => driver.inspect!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.wake === undefined\n\t\t? {}\n\t\t: { wake: (input: RuntimeInput<RuntimeConfigBase>) => driver.wake!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.stop === undefined\n\t\t? {}\n\t\t: { stop: (input: RuntimeInput<RuntimeConfigBase>) => driver.stop!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.destroy === undefined\n\t\t? {}\n\t\t: { destroy: (input: RuntimeInput<RuntimeConfigBase>) => driver.destroy!(input as RuntimeInput<RuntimeConfig>) }),\n});\n\nexport interface RegistryService {\n\treadonly names: ReadonlySet<Name>;\n\treadonly find: (name: Name) => Option.Option<Registered>;\n\treadonly get: (name: Name) => Effect.Effect<Registered, SandboxDriverNotRegisteredError>;\n\treadonly decodeCreateConfig: (\n\t\tname: Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n\treadonly decodeRuntimeConfig: (\n\t\tname: Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<RuntimeConfigBase, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n\treadonly encodeRuntimeConfig: (\n\t\tname: Name,\n\t\tinput: RuntimeConfigBase,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n}\n\nexport class Registry extends Context.Service<Registry, RegistryService>()(\n\t\"@codeworksh/harness/sandbox/driver/Registry\",\n) {}\n\nconst codecFailure = (driver: Name, reason: unknown) =>\n\tnew SandboxDriverRegistrationError({ driver, reason: String(reason) });\n\nexport interface Registration {\n\treadonly registered: Registered;\n}\n\n/**\n * Creates in-memory driver registry map and throws for invalid state operations.\n * Exposes registry services methods to work with.\n */\nexport const makeRegistry = (\n\tdrivers: ReadonlyArray<Registration>,\n): Effect.Effect<RegistryService, SandboxDriverRegistrationError> =>\n\tEffect.gen(function* () {\n\t\tconst entries = new Map<Name, Registered>();\n\t\tfor (const registration of drivers) {\n\t\t\tconst driver = registration.registered;\n\t\t\tif (entries.has(driver.name)) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.name,\n\t\t\t\t\treason: \"duplicate driver registration\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (driver.capabilities.destroy && !driver.capabilities.stop) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.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 [\"wake\", \"stop\", \"destroy\"] as const) {\n\t\t\t\tif (driver.capabilities[operation] !== (driver[operation] !== undefined)) {\n\t\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\t\tdriver: driver.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\tentries.set(driver.name, erase(driver));\n\t\t}\n\n\t\t// `find` safely returns undefined if nothing\n\t\t// `get` throws\n\t\tconst find = (name: Name) => Option.fromUndefinedOr(entries.get(name));\n\t\tconst get = (name: Name) =>\n\t\t\tEffect.fromOption(find(name)).pipe(\n\t\t\t\tEffect.mapError(() => new SandboxDriverNotRegisteredError({ driver: name })),\n\t\t\t);\n\n\t\tconst decodeCreateConfig = Effect.fn(\"SandboxDriver.Registry.decodeCreateConfig\")(function* (\n\t\t\tname: Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(driver.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: Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(driver.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: Name,\n\t\t\tinput: RuntimeConfigBase,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.encodeUnknownEffect(driver.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\tfind,\n\t\t\tget,\n\t\t\tdecodeCreateConfig,\n\t\t\tdecodeRuntimeConfig,\n\t\t\tencodeRuntimeConfig,\n\t\t});\n\t});\n\n/**\n * Register a static set of drivers for one process-lifetime control plane.\n *\n * `driver()` preserves the concrete driver at its definition site; this layer\n * is the only erasure boundary.\n */\nexport const layer = (...drivers: ReadonlyArray<Registration>) => Layer.effect(Registry, makeRegistry(drivers));\n\nexport const driver = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tvalue: Driver<CreateConfig, RuntimeConfig>,\n): Driver<CreateConfig, RuntimeConfig> & Registration =>\n\tObject.assign(value, {\n\t\tregistered: erase(value),\n\t});\n\nexport * as SandboxDriver from \"./driver.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 \"../../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 { 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 { 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","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, 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 {\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 { Local } from \"./fs/vfs.ts\";\nimport { HostExe } from \"./shell/host.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\nimport { EnvNodeJSDefault } from \"./fs/nodejs.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* SandboxDriver.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\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 \"../../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 \"../../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 CreateConfig {\n\treadonly defaultCwd: SandboxDriver.AbsolutePath;\n\treadonly initializeCwd?: SandboxDriver.AbsolutePath | undefined;\n}\n\nexport interface RuntimeConfig extends SandboxDriver.RuntimeConfigBase {}\n\nexport const CreateConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n});\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\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\tEnvInMemory.make({ cwd: config.initializeCwd ?? config.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: config.defaultCwd },\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t),\n\t\truntimeConfigFor: ({ providerResourceId }) =>\n\t\t\tEffect.fail(\n\t\t\t\tproviderError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation: \"runtimeConfigFor\",\n\t\t\t\t\tcause: new Error(`memory resources cannot be reattached: ${providerResourceId}`),\n\t\t\t\t\tnotFound: true,\n\t\t\t\t}),\n\t\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 \"../../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 CreateConfig {\n\treadonly defaultCwd: SandboxDriver.AbsolutePath;\n\treadonly initializeCwd?: SandboxDriver.AbsolutePath | undefined;\n\treadonly location?: string | undefined;\n}\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: SandboxDriver.AbsolutePath,\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n\tlocation: Schema.optional(Schema.String),\n});\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\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 location = config.location === undefined ? undefined : posix.resolve(config.location);\n\t\t\treturn EnvSqldb.make(location, { cwd: config.initializeCwd ?? config.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: config.defaultCwd,\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 { posix } from \"../../posix.ts\";\nimport { SandboxFileSystem } from \"./filesystem.ts\";\n\n// The provider contract and FileStat live in `filesystem.ts` (the single source of truth, VFS-free).\n// A remote provider implements this Interface; `make` wraps\n// it into the same runtime surface the local vfs backend exposes.\nexport type FileStat = SandboxFileSystem.FileStat;\n\n// Remote-aware callers can opt into metadata that is not part of the generic\n// SandboxFileSystem surface. In particular, `stat` keeps the familiar\n// provider-level meaning, while `lstat` explicitly asks for the directory entry\n// itself so symlink identity is not inferred from a method with mixed provider\n// semantics.\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\t/**\n\t * Optional remote working directory for relative paths. When omitted, relative\n\t * paths are passed through so the remote provider can use its own default cwd.\n\t */\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/**\n * Wrap a remote provider into the runtime filesystem surface: resolve relative\n * paths against `cwd`, and nothing else. Parent creation and `rm` option\n * validation are the runtime's job and live in `SandboxFileSystem.fromProvider`,\n * which every backend passes through — putting them here would cover only the\n * backends that happen to use this wrapper.\n */\nexport const make = (provider: Interface, options?: Options): Interface => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\t// option validation happens in `fromProvider`, before any mutation\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t};\n};\n\nexport const withProvider = make;\n\nexport * as RemoteFileSystem from \"./remote.ts\";\n","import { Context } from \"effect\";\n\n/**\n * The driver's own locator for the attached resource — a Vercel sandbox name, a\n * Daytona sandbox id.\n *\n * Deliberately *not* on `SandboxIO.Current`: consumers never parse one,\n * and keeps it separate from the application id precisely so a driver's format can\n * change without touching identity.\n *\n * It exists for the control plane, which records it as `provider_resource_id`,\n * and for tests that reattach to the same resource.\n *\n * One tag for every driver rather than one per driver. A mount has exactly one\n * driver, so there is nothing to disambiguate, and the control plane has to read\n * the locator without knowing which driver produced it — keeps the\n * driver name open, so anything keyed on a closed `\"vercel\" | \"daytona\"` set is\n * a bug waiting for the third driver.\n */\nexport class Service extends Context.Service<Service, { readonly providerResourceId: string }>()(\n\t\"@codeworksh/harness/sandbox/resource/Service\",\n) {}\n\nexport * as SandboxResource from \"./resource.ts\";\n","/* oxlint-disable effecttsgo/async-function -- Daytona's SDK boundary is Promise-based. */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../posix.ts\";\nimport { sanitizeError } from \"../errors.ts\";\nimport { SandboxFileSystem } from \"../fs/filesystem.ts\";\nimport { RemoteFileSystem } from \"../fs/remote.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { SandboxIO } from \"../io.ts\";\nimport { SandboxResource } from \"../resource.ts\";\nimport { type ISandboxExe, quote, quoteArgv, resolveCwd, Shell, ShellError } from \"../shell/shell.ts\";\n\ntype CodeLanguage = import(\"@daytona/sdk\").CodeLanguage;\ntype Daytona = import(\"@daytona/sdk\").Daytona;\ntype FileInfo = import(\"@daytona/sdk\").FileInfo;\ntype Image = import(\"@daytona/sdk\").Image;\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\n/** Fallback when Daytona cannot report a snapshot/image-specific work directory. */\nexport const DEFAULT_CWD = \"/home/daytona\";\n\n/**\n * The mount cwd for a Daytona namespace.\n *\n * An absolute override replaces the namespace default outright, so the\n * `getWorkDir()` round-trip is skipped: it would discover a value we then throw\n * away. Otherwise the sandbox's own work directory is the default, and\n * {@link DEFAULT_CWD} covers a snapshot or image that reports none.\n *\n * Taken as a thunk rather than read off the sandbox so all three branches are\n * testable without provisioning one — this decides where every Daytona mount\n * roots, and §8.1 makes a wrong answer here resolve silently rather than fail.\n */\nexport const mountCwd = async (\n\tcwd: string | undefined,\n\tgetWorkDir: () => Promise<string | undefined>,\n): Promise<string> => {\n\tconst defaultCwd = posix.isAbsolute(cwd ?? \"\") ? DEFAULT_CWD : ((await getWorkDir()) ?? DEFAULT_CWD);\n\treturn SandboxIO.resolveMountCwd(defaultCwd, cwd);\n};\n\nexport class DaytonaError extends Schema.TaggedError<DaytonaError>()(\"DaytonaError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nexport interface Options {\n\t/** API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n\treadonly apiKey?: string | undefined;\n\t/** API URL. Falls back to `DAYTONA_API_URL` / the SDK default. */\n\treadonly apiUrl?: string | undefined;\n\t/** Target region. Falls back to `DAYTONA_TARGET` / the SDK default. */\n\treadonly target?: string | undefined;\n\t/** Reuse an existing sandbox by id or name instead of creating one. */\n\treadonly sandboxId?: string | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Image (registry reference or declarative `Image`) to create the sandbox from. */\n\treadonly image?: string | Image | undefined;\n\t/** Runtime used for code execution. Defaults to `\"typescript\"`. */\n\treadonly language?: CodeLanguage | string | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** Resource allocation (cpu / memory / disk). */\n\treadonly resources?: Resources | undefined;\n\t/** OS user to run as inside the sandbox. */\n\treadonly user?: string | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `getWorkDir()`;\n\t * omitted values use it, with `/home/daytona` as the provider fallback.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Idle minutes before the sandbox auto-stops. */\n\treadonly autoStopInterval?: number | undefined;\n\t/** Per-command timeout in seconds. 0 means no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n\treadonly cwd: string;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandbox/providers/daytona/Remote\") {}\n\nconst assertCommandSucceeded = (command: string, result: { exitCode: number; result?: string }) => {\n\tif (result.exitCode !== 0) throw new Error(result.result || `command failed (${result.exitCode}): ${command}`);\n};\n\nconst dateFrom = (value: string | undefined) => {\n\tif (value === undefined) return undefined;\n\treturn Option.getOrUndefined(DateTime.make(value).pipe(Option.map(DateTime.toDateUtc)));\n};\n\nexport const createSandbox = (daytona: Daytona, options: Options) => {\n\tconst base = {\n\t\tlanguage: options.language ?? \"typescript\",\n\t\t...(options.envVars === undefined ? {} : { envVars: options.envVars }),\n\t\t...(options.user === undefined ? {} : { user: options.user }),\n\t\t...(options.autoStopInterval === undefined ? {} : { autoStopInterval: options.autoStopInterval }),\n\t\tautoDeleteInterval: -1,\n\t};\n\treturn options.image !== undefined\n\t\t? daytona.create({\n\t\t\t\t...base,\n\t\t\t\timage: options.image,\n\t\t\t\t...(options.resources === undefined ? {} : { resources: options.resources }),\n\t\t\t})\n\t\t: daytona.create({ ...base, ...(options.snapshot === undefined ? {} : { snapshot: options.snapshot }) });\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Daytona } = await import(\"@daytona/sdk\");\n\t\t\t\tconst daytona = new Daytona({\n\t\t\t\t\t...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),\n\t\t\t\t\t...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n\t\t\t\t\t...(options.target === undefined ? {} : { target: options.target }),\n\t\t\t\t});\n\t\t\t\tconst sandbox = options.sandboxId\n\t\t\t\t\t? await daytona.get(options.sandboxId)\n\t\t\t\t\t: await createSandbox(daytona, options);\n\t\t\t\treturn {\n\t\t\t\t\tsandbox,\n\t\t\t\t\tcwd: await mountCwd(options.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t};\n\t\t\t},\n\t\t\tcatch: (cause) => new DaytonaError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\nexport const statsFrom = (info: FileInfo): RemoteFileSystem.FileStat => {\n\tconst symlink = info.mode === undefined ? undefined : info.mode.startsWith(\"l\");\n\tconst mtime = dateFrom(info.modifiedAt ?? info.modTime);\n\n\t// omit size/mtime/isSymbolicLink the toolbox did not report — never fabricate\n\treturn {\n\t\tisFile: !info.isDir && symlink !== true,\n\t\tisDirectory: info.isDir,\n\t\t...(symlink === undefined ? {} : { isSymbolicLink: symlink }),\n\t\t...(info.size === undefined ? {} : { size: info.size }),\n\t\t...(mtime === undefined ? {} : { mtime }),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\"\n>;\n\nconst providerFrom = (sandbox: RemoteSandbox, options: Options) => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: async (path: string) => (await sandbox.fs.downloadFile(path)).toString(\"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.downloadFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.uploadFile(typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content), path),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.getFileDetails(path)),\n\t\t// The toolbox file-details endpoint follows symlinks. Detect the entry\n\t\t// with the sandbox shell first so lstat never reports target metadata as\n\t\t// if it described the link itself.\n\t\tlstat: async (path: string) => {\n\t\t\tconst command = `test -L ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tif (result.exitCode === 0) {\n\t\t\t\treturn { isFile: false, isDirectory: false, isSymbolicLink: true };\n\t\t\t}\n\t\t\tif (result.exitCode === 1) return statsFrom(await sandbox.fs.getFileDetails(path));\n\t\t\tassertCommandSucceeded(command, result);\n\t\t\tthrow new Error(`unreachable lstat result for ${path}`);\n\t\t},\n\t\treaddir: async (path: string) => (await sandbox.fs.listFiles(path)).map((entry) => entry.name),\n\t\t// Only a genuine 404 means \"absent\". Auth, rate-limit, and transport\n\t\t// failures propagate: a caller that deletes records on absence must not\n\t\t// be told a path is gone because the API was briefly unreachable.\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.getFileDetails(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tconst { DaytonaNotFoundError } = await import(\"@daytona/sdk\");\n\t\t\t\tif (cause instanceof DaytonaNotFoundError) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tif (!mkdirOptions?.recursive) {\n\t\t\t\tawait sandbox.fs.createFolder(path, \"755\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst command = `mkdir -p ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tassertCommandSucceeded(command, result);\n\t\t},\n\t\trm: async (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) => {\n\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.deleteFile(path, rmOptions?.recursive);\n\t\t\t} catch (cause) {\n\t\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t};\n\n\treturn filesystem;\n};\n\n// Daytona's execute API folds stderr into `result` and reports a single exit\n// code, so the shell surfaces the combined output as stdout and leaves stderr\n// empty rather than inventing a split.\nconst runCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\topts?: { env?: Record<string, string>; cwd?: string },\n) =>\n\tEffect.tryPromise({\n\t\ttry: () =>\n\t\t\tsandbox.process.executeCommand(command, resolveCwd(options.cwd, opts?.cwd), opts?.env, options.execTimeout),\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t}).pipe(Effect.map((response) => ({ stdout: response.result ?? \"\", stderr: \"\", exitCode: response.exitCode })));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\trunCommand(sandbox, options, command, opts);\n\n// `executeCommand` takes a single string, so the vector is quoted here rather\n// than spawned; the per-call cwd rides the toolbox's own cwd argument instead\n// of a `cd` prefix.\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) =>\n\t\trunCommand(sandbox, options, quoteArgv(argv), opts);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn SandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, mounted), { cwd }));\n\t\t}),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn Shell.of({ exec: exec(sandbox, mounted), execArgv: execArgv(sandbox, mounted) });\n\t\t}),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * Mount wrappers supply an absolute cwd to every public operation. Internal\n * filesystem helper commands already receive absolute paths, so the transport\n * itself keeps no mutable working-directory state and owns no resource\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Daytona's locator is the sandbox id. See `SandboxResource` for why this is a\n// shared tag rather than a Daytona-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.id })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, ({ cwd }) =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"daytona\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Daytona sandbox provides the runtime filesystem service directly plus\n * the sandbox's native remote shell. It intentionally does not provide VFS:\n * remote filesystems have no synchronous filesystem surface.\n */\nexport const layer = (options: Options = {}): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, DaytonaError> =>\n\tLayer.mergeAll(filesystemLayer(options), shellLayer(options), identityLayer(options), resourceLayer).pipe(\n\t\tLayer.provide(remote(options)),\n\t);\n\nexport const services = layer;\n\nexport * as EnvDaytona from \"./daytona.ts\";\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { makeRedactor, providerError, type SandboxProviderError } from \"../errors.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { EnvDaytona } from \"../providers/daytona.ts\";\n\nexport interface ClientOptions {\n\treadonly apiKey?: string | undefined;\n\treadonly apiUrl?: string | undefined;\n\treadonly target?: string | undefined;\n}\n\nexport const ResourcesConfig = Schema.Struct({\n\tcpu: Schema.optional(Schema.Finite),\n\tgpu: Schema.optional(Schema.Finite),\n\tmemory: Schema.optional(Schema.Finite),\n\tdisk: Schema.optional(Schema.Finite),\n});\nexport type ResourcesConfig = typeof ResourcesConfig.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\timage: Schema.optional(Schema.String),\n\tlanguage: Schema.optional(Schema.String),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tresources: Schema.optional(ResourcesConfig),\n\tuser: Schema.optional(Schema.String),\n\tcwd: Schema.optional(Schema.String),\n\tautoStopInterval: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tuser: Schema.optional(Schema.String),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"daytona\");\ntype DaytonaSdk = typeof import(\"@daytona/sdk\");\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\nconst statusFrom = (\n\tstate: RemoteSandbox[\"state\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => {\n\tconst providerStatus = state ?? \"unknown\";\n\treturn {\n\t\tstatus:\n\t\t\tstate === \"stopped\" || state === \"archived\"\n\t\t\t\t? \"offline\"\n\t\t\t\t: state === \"stopping\" || state === \"archiving\" || state === \"snapshotting\" || state === \"destroying\"\n\t\t\t\t\t? \"suspending\"\n\t\t\t\t\t: state === \"destroyed\"\n\t\t\t\t\t\t? \"unavail\"\n\t\t\t\t\t\t: state === \"error\" || state === \"build_failed\" || state === \"unknown\"\n\t\t\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t\t\t: \"online\",\n\t\tproviderStatus,\n\t};\n};\n\nconst shouldWake = (sandbox: RemoteSandbox): boolean => sandbox.state === \"stopped\" || sandbox.state === \"archived\";\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst redact = makeRedactor([client.apiKey ?? \"\"]);\n\tconst daytona = (sdk: DaytonaSdk) =>\n\t\tnew sdk.Daytona({\n\t\t\t...(client.apiKey === undefined ? {} : { apiKey: client.apiKey }),\n\t\t\t...(client.apiUrl === undefined ? {} : { apiUrl: client.apiUrl }),\n\t\t\t...(client.target === undefined ? {} : { target: client.target }),\n\t\t});\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: (sdk: DaytonaSdk) => Promise<A>,\n\t): Effect.Effect<A, SandboxProviderError> =>\n\t\tEffect.suspend(() => {\n\t\t\tlet sdk: DaytonaSdk | undefined;\n\t\t\treturn Effect.tryPromise({\n\t\t\t\ttry: () =>\n\t\t\t\t\timport(\"@daytona/sdk\").then((loaded) => {\n\t\t\t\t\t\tsdk = loaded;\n\t\t\t\t\t\treturn run(loaded);\n\t\t\t\t\t}),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\tredact,\n\t\t\t\t\t\tnotFound: sdk !== undefined && cause instanceof sdk.DaytonaNotFoundError,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t});\n\n\tconst get = (providerResourceId: string, operation: string) =>\n\t\tattempt(operation, (sdk) => daytona(sdk).get(providerResourceId));\n\n\tconst refresh = (sandbox: RemoteSandbox, operation: string) =>\n\t\tattempt(operation, () => sandbox.refreshData()).pipe(Effect.as(sandbox));\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.state),\n\t\tmetadata: {\n\t\t\ttarget: sandbox.target,\n\t\t},\n\t});\n\n\tconst wake = (sandbox: RemoteSandbox, operation: string) =>\n\t\tshouldWake(sandbox)\n\t\t\t? attempt(operation, () => sandbox.start()).pipe(Effect.map(() => sandbox))\n\t\t\t: Effect.succeed(sandbox);\n\n\tconst runtime = (\n\t\tdefaultCwd: string,\n\t\tinput: { readonly user?: string | undefined; readonly execTimeout?: number | undefined },\n\t) => ({\n\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(defaultCwd),\n\t\t...(input.user === undefined ? {} : { user: input.user }),\n\t\t...(input.execTimeout === undefined ? {} : { execTimeout: input.execTimeout }),\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\t// Installed SDK 0.187.0 has no cancellation signal on\n\t\t\t// executeCommand; session execution cannot carry cwd/env safely.\n\t\t\tcancels: false,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst base = {\n\t\t\t\t\tlanguage: config.language ?? \"typescript\",\n\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t...(config.user === undefined ? {} : { user: config.user }),\n\t\t\t\t\t...(config.autoStopInterval === undefined ? {} : { autoStopInterval: config.autoStopInterval }),\n\t\t\t\t\tautoDeleteInterval: -1,\n\t\t\t\t\tlabels: {\n\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst sandbox = yield* attempt(\"create\", (loaded) => {\n\t\t\t\t\tconst sdk = daytona(loaded);\n\t\t\t\t\treturn config.image === undefined\n\t\t\t\t\t\t? sdk.create({ ...base, ...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }) })\n\t\t\t\t\t\t: sdk.create({\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\timage: config.image,\n\t\t\t\t\t\t\t\t...(config.resources === undefined ? {} : { resources: config.resources as Resources }),\n\t\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst defaultCwd = yield* attempt(\"create.cwd\", () =>\n\t\t\t\t\tEnvDaytona.mountCwd(config.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.state);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.id,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: runtime(defaultCwd, config),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttarget: sandbox.target,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst sandbox = yield* get(providerResourceId, \"runtimeConfigFor\");\n\t\t\t\tconst defaultCwd =\n\t\t\t\t\toverrides?.defaultCwd ??\n\t\t\t\t\tSandboxDriver.AbsolutePath.make(\n\t\t\t\t\t\tyield* attempt(\"runtimeConfigFor.cwd\", () =>\n\t\t\t\t\t\t\tEnvDaytona.mountCwd(undefined, () => sandbox.getWorkDir()),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdefaultCwd,\n\t\t\t\t\t...(overrides?.user === undefined ? { user: sandbox.user } : { user: overrides.user }),\n\t\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t\t};\n\t\t\t}),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst sandbox = yield* get(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t);\n\t\t\t\t\tyield* wake(sandbox, \"attach.wake\");\n\t\t\t\t\treturn EnvDaytona.transport(\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(refresh(sandbox, \"inspect.refresh\"), observed),\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(wake(sandbox, \"wake.start\"), observed),\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nexport * as DaytonaSandboxDriver from \"./daytona.ts\";\n","/* oxlint-disable effecttsgo/async-function -- Vercel's sandbox SDK boundary is Promise-based. */\nimport { Context, Effect, Layer, Schema, Stream } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { sanitizeError } from \"../errors.ts\";\nimport { SandboxFileSystem } from \"../fs/filesystem.ts\";\nimport { RemoteFileSystem } from \"../fs/remote.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { SandboxIO } from \"../io.ts\";\nimport { SandboxResource } from \"../resource.ts\";\nimport {\n\ttype ExecChunk,\n\ttype ExecResult,\n\ttype ISandboxExe,\n\tquoteArgv,\n\tresolveCwd,\n\tShell,\n\tShellError,\n} from \"../shell/shell.ts\";\n\nconst utf8 = new TextEncoder();\ntype Command = import(\"@vercel/sandbox\").Command;\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\n/** Vercel's namespace-intrinsic working directory. */\nexport const DEFAULT_CWD = \"/vercel/sandbox\";\n\nexport class VercelError extends Schema.TaggedError<VercelError>()(\"VercelError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\n/**\n * Vercel API credentials. Either all three are provided together or none are:\n * when omitted, the SDK resolves them from the `VERCEL_OIDC_TOKEN` env var\n * (the token's payload carries the project and team ids).\n */\nexport interface Credentials {\n\treadonly token: string;\n\treadonly teamId: string;\n\treadonly projectId: string;\n}\n\nexport interface Options {\n\t/** Auth token (OIDC or access token). Falls back to `VERCEL_OIDC_TOKEN`. */\n\treadonly token?: string | undefined;\n\t/** Team id. Derived from the OIDC token when omitted. */\n\treadonly teamId?: string | undefined;\n\t/** Project id. Derived from the OIDC token when omitted. */\n\treadonly projectId?: string | undefined;\n\t/** Reuse an existing sandbox by name instead of creating one. */\n\treadonly sandboxName?: string | undefined;\n\t/** Explicit name for a newly created sandbox. */\n\treadonly name?: string | undefined;\n\t/** Provider-side diagnostic labels (maximum five). */\n\treadonly tags?: Record<string, string> | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot id to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Source to seed the sandbox filesystem from (git or tarball). */\n\treadonly source?:\n\t\t| {\n\t\t\t\treadonly type: \"git\";\n\t\t\t\treadonly url: string;\n\t\t\t\treadonly revision?: string | undefined;\n\t\t\t\treadonly depth?: number | undefined;\n\t\t }\n\t\t| { readonly type: \"tarball\"; readonly url: string };\n\t/** Runtime used by the sandbox. Defaults to the SDK default (`node24`). */\n\treadonly runtime?: string | undefined;\n\t/** Ports to expose from the sandbox (max 4). */\n\treadonly ports?: number[] | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** vCPU allocation (memory scales at 2048 MB per vCPU). */\n\treadonly vcpus?: number | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `/vercel/sandbox`;\n\t * omitted values use that namespace default.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Milliseconds before the sandbox auto-terminates. */\n\treadonly timeout?: number | undefined;\n\t/** Per-command timeout in milliseconds. Omit for no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandbox/providers/vercel/Remote\") {}\n\n// Vercel requires all three credential fields together or none — partial\n// credentials are rejected by the SDK — so only forward them when complete.\nexport const credentialsFrom = (options: Options): Credentials | undefined =>\n\toptions.token !== undefined && options.teamId !== undefined && options.projectId !== undefined\n\t\t? { token: options.token, teamId: options.teamId, projectId: options.projectId }\n\t\t: undefined;\n\nexport const createSandbox = async (options: Options, creds: Credentials | undefined = credentialsFrom(options)) => {\n\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\tconst withCreds = <T extends object>(params: T) => (creds ? { ...params, ...creds } : params);\n\tconst source =\n\t\toptions.source?.type === \"git\"\n\t\t\t? {\n\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\turl: options.source.url,\n\t\t\t\t\t...(options.source.revision === undefined ? {} : { revision: options.source.revision }),\n\t\t\t\t\t...(options.source.depth === undefined ? {} : { depth: options.source.depth }),\n\t\t\t\t}\n\t\t\t: options.source;\n\tconst base = {\n\t\t...(options.name === undefined ? {} : { name: options.name }),\n\t\t...(options.tags === undefined ? {} : { tags: options.tags }),\n\t\t...(options.envVars === undefined ? {} : { env: options.envVars }),\n\t\t...(options.ports === undefined ? {} : { ports: options.ports }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.vcpus === undefined ? {} : { resources: { vcpus: options.vcpus } }),\n\t};\n\treturn options.snapshot !== undefined\n\t\t? Sandbox.create(withCreds({ ...base, source: { type: \"snapshot\" as const, snapshotId: options.snapshot } }))\n\t\t: Sandbox.create(\n\t\t\t\twithCreds({\n\t\t\t\t\t...base,\n\t\t\t\t\t...(options.runtime === undefined ? {} : { runtime: options.runtime }),\n\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t}),\n\t\t\t);\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\t\t\t\tconst creds = credentialsFrom(options);\n\t\t\t\tconst sandbox = options.sandboxName\n\t\t\t\t\t? await Sandbox.get(creds ? { ...creds, name: options.sandboxName } : { name: options.sandboxName })\n\t\t\t\t\t: await createSandbox(options, creds);\n\t\t\t\treturn { sandbox };\n\t\t\t},\n\t\t\tcatch: (cause) => new VercelError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\ninterface Stats {\n\treadonly size: number;\n\treadonly mtime: Date;\n\treadonly isFile: () => boolean;\n\treadonly isDirectory: () => boolean;\n\treadonly isSymbolicLink: () => boolean;\n}\n\nexport const statsFrom = (stats: Stats): RemoteFileSystem.FileStat => {\n\tconst mtime = stats.mtime;\n\n\t// omit size/mtime the stat could not report — never fabricate\n\treturn {\n\t\tisFile: stats.isFile(),\n\t\tisDirectory: stats.isDirectory(),\n\t\tisSymbolicLink: stats.isSymbolicLink(),\n\t\t...(Number.isFinite(stats.size) ? { size: stats.size } : {}),\n\t\t...(mtime instanceof Date && !Number.isNaN(mtime.getTime()) ? { mtime } : {}),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\"\n>;\n\n// The Vercel `fs` surface is `node:fs/promises`-compatible, so the provider\n// maps almost directly. The `RemoteFileSystem.make` wrapper resolves relative\n// paths against `cwd` and guarantees parent creation on `writeFile`.\nconst providerFrom = (sandbox: RemoteSandbox): RemoteFilesystemProvider => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: (path: string) => sandbox.fs.readFile(path, \"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.readFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.writeFile(path, typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content)),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.stat(path)),\n\t\t// Keep symlink identity explicit: Vercel's `stat` follows symlinks\n\t\t// (`stat -L`), so remote-aware callers must ask for `lstat` when they\n\t\t// need the entry itself instead of the target's metadata.\n\t\tlstat: async (path: string) => statsFrom(await sandbox.fs.lstat(path)),\n\t\t// `withFileTypes` lists via `find`, which includes dotfiles (`.git` …);\n\t\t// the bare `readdir` shells out to `ls -1` and would drop them.\n\t\treaddir: async (path: string) => (await sandbox.fs.readdir(path, { withFileTypes: true })).map((e) => e.name),\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tif (SandboxFileSystem.isNotFoundError(cause)) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tawait sandbox.fs.mkdir(\n\t\t\t\tpath,\n\t\t\t\tmkdirOptions?.recursive === undefined ? {} : { recursive: mkdirOptions.recursive },\n\t\t\t);\n\t\t},\n\t\t// `rm -f` is native, so force/recursive delegate straight through; the\n\t\t// wrapper has already rejected any unsupported option before we get here.\n\t\trm: (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) =>\n\t\t\tsandbox.fs.rm(path, {\n\t\t\t\t...(rmOptions?.recursive === undefined ? {} : { recursive: rmOptions.recursive }),\n\t\t\t\t...(rmOptions?.force === undefined ? {} : { force: rmOptions.force }),\n\t\t\t}),\n\t};\n\n\treturn filesystem;\n};\n\n// Arbitrary command strings run through `sh -c` to match the single-string\n// contract the rest of the harness expects. Commands run **detached** so the\n// returned `Command` exposes `kill`/`logs`/`wait`: a `cwd`/`env` is threaded in,\n// and the per-command `execTimeout` is a server-side SIGKILL deadline.\nconst spawn = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => spawnArgv(sandbox, options, [\"sh\", \"-c\", command], env, cwd);\n\n// Vercel spawns a program with a real argument vector, so `execArgv` needs no\n// quoting at all — the args never pass through a shell.\nconst spawnArgv = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\targv: ReadonlyArray<string>,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => {\n\tconst resolvedCwd = resolveCwd(options.cwd, cwd);\n\treturn sandbox.runCommand({\n\t\tcmd: argv[0]!,\n\t\targs: argv.slice(1),\n\t\t...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }),\n\t\t...(env === undefined ? {} : { env }),\n\t\tdetached: true,\n\t\t...(options.execTimeout === undefined ? {} : { timeoutMs: options.execTimeout }),\n\t});\n};\n\n// Acquire a detached command and register its kill as a scope finalizer, so an\n// interrupt / timeout from the consumer actually terminates the remote process\n// (best-effort SIGKILL) instead of leaving it running server-side.\n// `command` labels failures only; the spawn itself is supplied by the caller so\n// string and argv execution share one kill finalizer.\nconst acquireWith = (command: string, run: () => Promise<Command>) =>\n\tEffect.acquireRelease(Effect.tryPromise({ try: run, catch: (cause) => new ShellError({ command, cause }) }), (cmd) =>\n\t\tEffect.promise(() => cmd.kill(\"SIGKILL\").catch(() => {})),\n\t);\n\n// Vercel reports stdout and stderr separately with a distinct exit code, so the\n// shell surfaces both streams faithfully.\nconst collect = (command: string) => (cmd: Command) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<ExecResult> => {\n\t\t\tconst result = await cmd.wait();\n\t\t\tconst [stdout, stderr] = await Promise.all([result.stdout(), result.stderr()]);\n\t\t\treturn { stdout, stderr, exitCode: result.exitCode };\n\t\t},\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t});\n\nconst acquireCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n) => acquireWith(command, () => spawn(sandbox, options, command, env, cwd));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) => {\n\t\t// quoted for the error label only — the spawn passes argv through untouched\n\t\tconst command = quoteArgv(argv);\n\t\treturn acquireWith(command, () => spawnArgv(sandbox, options, argv, opts?.env, opts?.cwd)).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\t};\n\n// Streaming output via `Command.logs` (an async generator of stdout/stderr\n// entries), followed by the exit code from `wait`. The kill finalizer fires when\n// the consuming scope closes (interrupt / timeout).\nconst stream =\n\t(sandbox: RemoteSandbox, options: Options): NonNullable<ISandboxExe[\"stream\"]> =>\n\t(command, opts) =>\n\t\tStream.unwrap(\n\t\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\t\tEffect.map((cmd) => {\n\t\t\t\t\tconst logs = Stream.fromAsyncIterable(cmd.logs(), (cause) => new ShellError({ command, cause })).pipe(\n\t\t\t\t\t\tStream.map((log): ExecChunk => ({ _tag: log.stream, bytes: utf8.encode(log.data) })),\n\t\t\t\t\t);\n\t\t\t\t\tconst exit = Stream.fromEffect(\n\t\t\t\t\t\tEffect.tryPromise({ try: () => cmd.wait(), catch: (cause) => new ShellError({ command, cause }) }),\n\t\t\t\t\t).pipe(Stream.map((finished): ExecChunk => ({ _tag: \"exit\", exitCode: finished.exitCode })));\n\t\t\t\t\treturn Stream.concat(logs, exit);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tSandboxFileSystem.fromProvider(\n\t\t\t\tRemoteFileSystem.make(providerFrom(sandbox), options.cwd === undefined ? undefined : { cwd: options.cwd }),\n\t\t\t),\n\t\t),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * The controller binds a cwd per mount, so neither filesystem nor shell stores\n * one here. The returned layer owns no provider resource and has no deletion\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Vercel's locator is the sandbox name. See `SandboxResource` for why this is a\n// shared tag rather than a Vercel-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.name })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, () =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"vercel\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: DEFAULT_CWD,\n\t\t\t\t...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Vercel sandbox provides the runtime filesystem service directly plus the\n * sandbox's native remote shell. It intentionally does not provide VFS: remote\n * filesystems have no synchronous filesystem surface.\n */\nexport const layer = (\n\toptions: Options = {},\n): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, VercelError> => {\n\tconst mounted = { ...options, cwd: SandboxIO.resolveMountCwd(DEFAULT_CWD, options.cwd) };\n\treturn Layer.mergeAll(filesystemLayer(mounted), shellLayer(mounted), identityLayer(mounted), resourceLayer).pipe(\n\t\tLayer.provide(remote(mounted)),\n\t);\n};\n\nexport const services = layer;\n\nexport * as EnvVercel from \"./vercel.ts\";\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { makeRedactor, providerError, type SandboxProviderError } from \"../errors.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { EnvVercel } from \"../providers/vercel.ts\";\n\nexport interface ClientOptions {\n\treadonly token?: string | undefined;\n\treadonly teamId?: string | undefined;\n\treadonly projectId?: string | undefined;\n}\n\nexport const Source = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"git\"),\n\t\turl: Schema.String,\n\t\trevision: Schema.optional(Schema.String),\n\t\tdepth: Schema.optional(Schema.Finite),\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"tarball\"),\n\t\turl: Schema.String,\n\t}),\n]);\nexport type Source = typeof Source.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\tsource: Schema.optional(Source),\n\truntime: Schema.optional(Schema.String),\n\tports: Schema.optional(Schema.Array(Schema.Finite)),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tvcpus: Schema.optional(Schema.Finite),\n\ttimeout: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"vercel\");\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\nconst statusFrom = (\n\tstatus: RemoteSandbox[\"status\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => ({\n\tstatus:\n\t\tstatus === \"stopped\"\n\t\t\t? \"offline\"\n\t\t\t: status === \"stopping\" || status === \"snapshotting\"\n\t\t\t\t? \"suspending\"\n\t\t\t\t: status === \"failed\" || status === \"aborted\"\n\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t: \"online\",\n\tproviderStatus: status,\n});\n\nconst isNotFound = (cause: unknown): boolean => {\n\tif (typeof cause !== \"object\" || cause === null) return false;\n\tconst response = \"response\" in cause && cause.response instanceof Response ? cause.response : undefined;\n\tconst code =\n\t\t\"code\" in cause && typeof cause.code === \"string\"\n\t\t\t? cause.code\n\t\t\t: \"json\" in cause &&\n\t\t\t\t typeof cause.json === \"object\" &&\n\t\t\t\t cause.json !== null &&\n\t\t\t\t \"error\" in cause.json &&\n\t\t\t\t typeof cause.json.error === \"object\" &&\n\t\t\t\t cause.json.error !== null &&\n\t\t\t\t \"code\" in cause.json.error &&\n\t\t\t\t typeof cause.json.error.code === \"string\"\n\t\t\t\t? cause.json.error.code\n\t\t\t\t: undefined;\n\treturn response?.status === 404 || code === \"not_found\" || code === \"sandbox_not_found\";\n};\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst credentials = EnvVercel.credentialsFrom(client);\n\tconst redact = makeRedactor([client.token ?? \"\"]);\n\n\tconst attempt = <A>(operation: string, run: () => Promise<A>): Effect.Effect<A, SandboxProviderError> =>\n\t\tEffect.tryPromise({\n\t\t\ttry: run,\n\t\t\tcatch: (cause) =>\n\t\t\t\tproviderError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation,\n\t\t\t\t\tcause,\n\t\t\t\t\tredact,\n\t\t\t\t\tnotFound: isNotFound(cause),\n\t\t\t\t}),\n\t\t});\n\n\tconst get = (providerResourceId: string, resume: boolean, operation: string) =>\n\t\tattempt(operation, () =>\n\t\t\timport(\"@vercel/sandbox\").then(({ Sandbox }) =>\n\t\t\t\tSandbox.get(\n\t\t\t\t\tcredentials === undefined\n\t\t\t\t\t\t? { name: providerResourceId, resume }\n\t\t\t\t\t\t: { ...credentials, name: providerResourceId, resume },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.status),\n\t\tmetadata: {\n\t\t\tcwd: sandbox.cwd,\n\t\t},\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst source =\n\t\t\t\t\tconfig.source?.type === \"git\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\t\t\t\turl: config.source.url,\n\t\t\t\t\t\t\t\t...(config.source.revision === undefined ? {} : { revision: config.source.revision }),\n\t\t\t\t\t\t\t\t...(config.source.depth === undefined ? {} : { depth: config.source.depth }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: config.source;\n\t\t\t\tconst sandbox = yield* attempt(\"create\", () =>\n\t\t\t\t\tEnvVercel.createSandbox(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...client,\n\t\t\t\t\t\t\t...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }),\n\t\t\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t\t\t\t...(config.runtime === undefined ? {} : { runtime: config.runtime }),\n\t\t\t\t\t\t\t...(config.ports === undefined ? {} : { ports: [...config.ports] }),\n\t\t\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t\t\t...(config.vcpus === undefined ? {} : { vcpus: config.vcpus }),\n\t\t\t\t\t\t\t...(config.timeout === undefined ? {} : { timeout: config.timeout }),\n\t\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t\t\ttags: {\n\t\t\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcredentials,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.status);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.name,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tcwd: sandbox.cwd,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.map(get(providerResourceId, false, \"runtimeConfigFor\"), (sandbox) => ({\n\t\t\t\tdefaultCwd: overrides?.defaultCwd ?? SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t})),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.map(\n\t\t\t\t\tget(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t),\n\t\t\t\t\t(sandbox) =>\n\t\t\t\t\t\tEnvVercel.transport(\n\t\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\ttrue,\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nexport * as VercelSandboxDriver from \"./vercel.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { posix as path } from \"../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 \"../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 { EventList } from \"../event/list.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 { SessionMessageSchema } from \"../session/message/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\nexport class ModelNotFoundError extends Schema.TaggedError<ModelNotFoundError>()(\"Runner.ModelNotFoundError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n}) {}\n\nexport class ProviderTurnError extends Schema.TaggedError<ProviderTurnError>()(\"Runner.ProviderTurnError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\nexport class LLMStreamError extends Schema.TaggedError<LLMStreamError>()(\"Runner.LLMStreamError\", {\n\tsessionId: Schema.String,\n\treason: Schema.String,\n}) {}\n\nexport class TurnError extends Schema.TaggedError<TurnError>()(\"Runner.TurnError\", {\n\tsessionId: Schema.String,\n\tmessageId: optional(SessionMessageSchema.ID),\n\tcause: EventList.TurnAbortCause,\n}) {}\n\nexport type RunError =\n\t| ModelNotFoundError\n\t| ProviderTurnError\n\t| LLMStreamError\n\t| TurnError\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/** Drains durable queued input without forcing an otherwise empty provider turn. */\n\treadonly drain: (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/** Interrupt active work owned by this process. Idle interruption is a no-op. */\n\treadonly interrupt: (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\tdrain: () => Effect.void,\n\t\twake: () => Effect.void,\n\t\tinterrupt: () => 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 * as 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 and awaits the drain generation responsible for it. */\n\treadonly run: (\n\t\tinput: PromptInput,\n\t) => Effect.Effect<Admitted, Session.SessionNotFoundError | PromptConflictError | Runner.RunError>;\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* restore(execution.drain(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 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// Uninterruptible because `interrupt` waits for the owner fiber's cleanup:\n\t\t// cancelling the caller partway would abandon a stop it already started.\n\t\tconst interrupt = Effect.fn(\"Control.interrupt\")((sessionId: SessionSchema.ID) =>\n\t\t\tEffect.uninterruptible(execution.interrupt(sessionId)),\n\t\t);\n\n\t\treturn Service.of({ prompt, run, 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> {\n\t/** Snapshots keys with an execution owned by this coordinator. */\n\treadonly active: Effect.Effect<ReadonlySet<Key>>;\n\t/** Starts execution while idle or joins the active execution. */\n\treadonly run: (key: Key) => Effect.Effect<void, E>;\n\t/** Coalesces queued work and awaits the drain generation assigned to it. */\n\treadonly drain: (key: Key) => Effect.Effect<void, E>;\n\t/** Registers one coalesced follow-up after newly recorded work. */\n\treadonly wake: (key: Key) => Effect.Effect<void>;\n\t/** Stops active execution and waits for its cleanup. */\n\treadonly interrupt: (key: Key) => Effect.Effect<void>;\n}\n\ntype Entry<E> = {\n\t// other fiber wants to know when key is finished will await this deferred\n\treadonly done: Deferred.Deferred<void, E>;\n\tcurrentWaiters: Array<Deferred.Deferred<void, E>>;\n\tpendingWaiters: Array<Deferred.Deferred<void, E>>;\n\t// process owner\n\towner?: Fiber.Fiber<void, void>;\n\t// if called wake() while the fiber is running, flips to true\n\t// runs one more time when finished.\n\tpendingWake: boolean;\n\t// set by interrupt()\n\tstopping: boolean;\n};\n\nexport const make = <Key, E>(options: {\n\t// Actual work that is to be run within the coordinator\n\t// key: Execution resource ID e.g: sessionID\n\t// force: A boolean flag passed down by coordinator\n\treadonly drain: (key: Key, force: boolean) => Effect.Effect<void, E>;\n}): Effect.Effect<Coordinator<Key, E>, never, Scope.Scope> =>\n\tEffect.gen(function* () {\n\t\tconst active = new Map<Key, Entry<E>>();\n\t\tconst fork = yield* FiberSet.makeRuntime<never, void, never>();\n\n\t\tconst makeEntry = (waiter?: Deferred.Deferred<void, E>): Entry<E> => ({\n\t\t\tdone: Deferred.makeUnsafe<void, E>(),\n\t\t\tcurrentWaiters: waiter === undefined ? [] : [waiter],\n\t\t\tpendingWaiters: [],\n\t\t\tpendingWake: false,\n\t\t\tstopping: false,\n\t\t});\n\n\t\tconst complete = (waiters: ReadonlyArray<Deferred.Deferred<void, E>>, exit: Exit.Exit<void, E>) => {\n\t\t\tfor (const waiter of waiters) Deferred.doneUnsafe(waiter, exit);\n\t\t};\n\n\t\tconst start = (key: Key, entry: Entry<E>, force: boolean, successor = false) => {\n\t\t\t// The Race Condition:\n\t\t\t// When we spawn new fiber, Effect fork might start immediate execution on same tick of event loop\n\t\t\t// `entry.owner` might not be set i.e `settle` is invoked before setting `entry.owner`, leading to race conditions\n\t\t\t// To prevent this, parent creates Deferred called ready.\n\t\t\t// The child fiber sees: `Deferred.await(ready)` and sleeps giving time for parent to set the `entry.owner = owner`\n\t\t\t// Once assigned, the parent calls `Deferred.doneUnsafe` waking the child up for actual work.\n\t\t\t//\n\t\t\t// In Successor Path:\n\t\t\t// If the fiber was spawned by settle because pendingWake was set true, it doesn't need the ready lock.\n\t\t\t// As the parent of settle, already knows about the entry exists and has set `entry.owner`\n\t\t\tconst ready = Deferred.makeUnsafe<void>();\n\t\t\tconst owner = fork(\n\t\t\t\t(successor ? Effect.yieldNow : Deferred.await(ready)).pipe(\n\t\t\t\t\tEffect.andThen(Effect.suspend(() => options.drain(key, force))),\n\t\t\t\t\tEffect.onExit((exit) => Effect.sync(() => settle(key, entry, 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\tentry.owner = owner;\n\t\t\tif (!successor) Deferred.doneUnsafe(ready, Effect.void);\n\t\t};\n\n\t\tconst settle = (key: Key, entry: Entry<E>, exit: Exit.Exit<void, E>) => {\n\t\t\tif (Exit.isSuccess(exit) && !entry.stopping && entry.pendingWake) {\n\t\t\t\tcomplete(entry.currentWaiters, exit);\n\t\t\t\tentry.currentWaiters = entry.pendingWaiters;\n\t\t\t\tentry.pendingWaiters = [];\n\t\t\t\tentry.pendingWake = false;\n\t\t\t\tstart(key, entry, false, true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcomplete(entry.currentWaiters, exit);\n\t\t\tif (entry.stopping) complete(entry.pendingWaiters, exit);\n\t\t\tconst successor = entry.pendingWake ? makeEntry() : undefined;\n\t\t\tif (successor !== undefined) successor.currentWaiters = entry.pendingWaiters;\n\t\t\tif (successor === undefined) active.delete(key);\n\t\t\telse {\n\t\t\t\tactive.set(key, successor);\n\t\t\t\tstart(key, successor, false, true);\n\t\t\t}\n\t\t\tDeferred.doneUnsafe(entry.done, exit);\n\t\t};\n\n\t\tconst run = (key: Key): Effect.Effect<void, E> =>\n\t\t\tEffect.uninterruptibleMask((restore) => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tif (entry.stopping) return restore(Deferred.await(entry.done).pipe(Effect.andThen(run(key))));\n\t\t\t\t\treturn restore(Deferred.await(entry.done));\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry();\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, true);\n\t\t\t\treturn restore(Deferred.await(next.done));\n\t\t\t});\n\n\t\tconst drain = (key: Key): Effect.Effect<void, E> =>\n\t\t\tEffect.uninterruptibleMask((restore) => {\n\t\t\t\tconst waiter = Deferred.makeUnsafe<void, E>();\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tif (entry.stopping) return restore(Deferred.await(entry.done).pipe(Effect.andThen(drain(key))));\n\t\t\t\t\tentry.pendingWake = true;\n\t\t\t\t\tentry.pendingWaiters.push(waiter);\n\t\t\t\t\treturn restore(Deferred.await(waiter));\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry(waiter);\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, false);\n\t\t\t\treturn restore(Deferred.await(waiter));\n\t\t\t});\n\n\t\tconst wake = (key: Key) =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tentry.pendingWake = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry();\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, false);\n\t\t\t});\n\n\t\tconst interrupt = (key: Key): Effect.Effect<void> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry?.owner === undefined) return Effect.void;\n\t\t\t\tentry.stopping = true;\n\t\t\t\tentry.pendingWake = false;\n\t\t\t\treturn Fiber.interrupt(entry.owner);\n\t\t\t});\n\n\t\treturn { active: Effect.sync(() => new Set(active.keys())), run, drain, wake, interrupt };\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 * as 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.hasInterruptsOnly(cause)\n\t\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t\t: Effect.logError(\"failed to drain session\", cause).pipe(Effect.annotateLogs({ sessionId })),\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\tdrain: coordinator.drain,\n\t\t\twake: coordinator.wake,\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","/*\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 {\n\tstream as aikitStream,\n\tllm,\n\ttype Event as AikitEvent,\n\ttype Message,\n\ttype Model,\n\ttype OpenAIOptions,\n} from \"@codeworksh/aikit\";\nimport { 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 { 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}\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<AsyncIterable<AikitEvent.LLMMessageEvent>, Runner.ModelNotFoundError | Runner.ProviderTurnError>;\n\nexport type Request = (\n\tinput: RequestInput,\n) => Effect.Effect<\n\tLLMEventPublisher.Terminal,\n\tRunner.ModelNotFoundError | Runner.ProviderTurnError | Runner.LLMStreamError\n>;\n\nconst runtimeOptions = (input: Input, signal: AbortSignal): OpenAIOptions =>\n\t({\n\t\tproviderOptions: { openai: { reasoningSummary: \"auto\" } },\n\t\t...input.options,\n\t\t...(input.thinkingLevel === undefined || input.thinkingLevel === \"off\" ? {} : { reasoning: input.thinkingLevel }),\n\t\tsessionId: input.sessionId,\n\t\tsignal,\n\t}) as unknown as OpenAIOptions;\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),\n\t\tcatch: (cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, cause }),\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, signal)),\n\t\tcatch: (cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, 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(\n\t\t\t\t\titerable,\n\t\t\t\t\t(cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, cause }),\n\t\t\t\t).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","/**\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 \"../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 \"../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","import { Context, Effect, Layer, Option, Ref } from \"effect\";\nimport type { SessionSchema } from \"./schema.ts\";\nimport type { State } from \"../state/state.ts\";\n\n/** Process-local values that cannot be reconstructed from the durable session log. */\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 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 { Context as SessionContext } from \"../context/context.ts\";\nimport { Location } from \"../location/location.ts\";\nimport { SandboxIO } from \"../sandbox/io.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 type { ID as SessionId } from \"../session/schema.ts\";\nimport { SessionRuntime } from \"../session/runtime.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 * FIXME(sanchitrk): read from settings config once we set that up;\n *\n * Defaults. `maxTokens` is deliberately absent: aikit's `stream()` already calls\n * `applyDefaultMaxTokens`, which derives it from the model's own `maxTokens` and\n * `contextWindow`. Setting one here would override a model-aware value with a\n * fixed guess.\n */\nexport const defaults = {\n\tprovider: \"openai\",\n\tmodel: \"gpt-5.5\",\n\tthinkingLevel: \"medium\",\n\ttoolExecution: \"sequential\",\n\ttimeoutMs: 60_000,\n\tmaxRetries: 0,\n} as const satisfies {\n\treadonly provider: string;\n\treadonly model: string;\n\treadonly thinkingLevel: Model.ThinkingLevel;\n\treadonly toolExecution: ToolExecutionMode;\n\treadonly timeoutMs: number;\n\treadonly maxRetries: number;\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\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 | SessionContext.ContextReadError, 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 contexts = yield* SessionContext.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 durable = (yield* contexts.assemble(sessionId)).config;\n\t\t\t\t\tconst merged = { ...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: runtimeProvider,\n\t\t\t\t\t\tmodel: runtimeModel,\n\t\t\t\t\t\tthinkingLevel: runtimeThinkingLevel,\n\t\t\t\t\t\ttoolExecution = defaults.toolExecution,\n\t\t\t\t\t\t...rest\n\t\t\t\t\t} = merged;\n\t\t\t\t\tconst provider = runtimeProvider ?? durable.model?.providerId ?? defaults.provider;\n\t\t\t\t\tconst model = runtimeModel ?? durable.model?.modelId ?? defaults.model;\n\t\t\t\t\tconst thinkingLevel = runtimeThinkingLevel ?? durable.thinkingLevel ?? defaults.thinkingLevel;\n\t\t\t\t\tconst request: RequestOptions = {\n\t\t\t\t\t\ttimeoutMs: defaults.timeoutMs,\n\t\t\t\t\t\tmaxRetries: defaults.maxRetries,\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t};\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\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 { Context } from \"../context/context.ts\";\nimport { ContextCodec } from \"../context/codec.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\treturn squashed instanceof Error ? squashed.message : String(squashed);\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\tpublisher,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (terminal.outcome === \"failed\") {\n\t\t\t\t\t\tconst cause: EventList.TurnAbortCause =\n\t\t\t\t\t\t\tterminal.reason === \"aborted\"\n\t\t\t\t\t\t\t\t? { _tag: \"interrupted\" }\n\t\t\t\t\t\t\t\t: { _tag: \"error\", message: terminal.message.errorMessage ?? \"provider turn failed\" };\n\t\t\t\t\t\treturn yield* new Runner.TurnError({\n\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t...(publisher.startedMessageId === undefined ? {} : { messageId: publisher.startedMessageId }),\n\t\t\t\t\t\t\tcause,\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 failure = Cause.findErrorOption(cause);\n\t\t\t\t\t\tif (Option.isSome(failure) && failure.value._tag === \"Runner.TurnError\") {\n\t\t\t\t\t\t\treturn Effect.fail(failure.value);\n\t\t\t\t\t\t}\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\treturn Effect.fail(\n\t\t\t\t\t\t\tnew Runner.TurnError({\n\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\t...(publisher?.startedMessageId === undefined ? {} : { messageId: publisher.startedMessageId }),\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}),\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).pipe(\n\t\t\t\t\tEffect.catchTag(\"Runner.TurnError\", (error) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tif (error.messageId !== undefined) {\n\t\t\t\t\t\t\t\tconst stored = yield* sessions.entry(error.messageId);\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, error.cause);\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: snapshot.sessionId,\n\t\t\t\t\t\t\t\tcause: error.cause,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn yield* error;\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\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","/*\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, Schema } 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\";\nimport { optional } from \"../schema.ts\";\n\nconst ConfigChangeData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tmodel: optional(Schema.Struct({ providerId: Schema.String, modelId: Schema.String })),\n\t\tthinkingLevel: optional(Schema.Literals([\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"])),\n\t}),\n);\nconst encodeConfigChange = Schema.encodeEffect(ConfigChangeData);\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\tyield* events.project(EventList.ConfigChanged, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (event.durable === undefined)\n\t\t\t\t\treturn yield* Effect.die(\"ConfigChanged is missing its aggregate sequence\");\n\t\t\t\tyield* sessions\n\t\t\t\t\t.append({\n\t\t\t\t\t\tid: event.id,\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\ttype: \"configChange\",\n\t\t\t\t\t\tstate: \"committed\",\n\t\t\t\t\t\tdata: yield* encodeConfigChange({\n\t\t\t\t\t\t\t...(event.data.model === undefined ? {} : { model: event.data.model }),\n\t\t\t\t\t\t\t...(event.data.thinkingLevel === undefined ? {} : { thinkingLevel: event.data.thinkingLevel }),\n\t\t\t\t\t\t}).pipe(Effect.orDie),\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\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 { SessionLive } from \"../session/live.ts\";\nimport { SessionRuntime } from \"../session/runtime.ts\";\nimport { State } from \"../state/state.ts\";\nimport type { Driver } from \"./sandbox.ts\";\n\nexport interface Options {\n\treadonly database?: string;\n\treadonly home?: string;\n\treadonly sandboxes?: ReadonlyArray<Driver>;\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.resolveLocation(configuredDatabase, paths.data));\n\t\t\tconst drivers = SandboxDriver.layer(...(options.sandboxes ?? []));\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(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 { DaytonaSandboxDriver } from \"../sandbox/drivers/daytona.ts\";\nimport { MemorySandboxDriver } from \"../sandbox/drivers/memory.ts\";\nimport { SqldbSandboxDriver } from \"../sandbox/drivers/sqldb.ts\";\nimport { VercelSandboxDriver } from \"../sandbox/drivers/vercel.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\n\nexport type Info = SandboxInstance.Info;\nexport type Driver = SandboxDriver.Registration;\n\nexport type CreateInput =\n\t| { readonly driver: \"memory\"; readonly cwd?: string }\n\t| { readonly driver: \"sqldb\"; readonly cwd?: string; readonly location?: string }\n\t| ({ readonly driver: \"vercel\" } & VercelSandboxDriver.CreateConfig)\n\t| ({ readonly driver: \"daytona\" } & DaytonaSandboxDriver.CreateConfig);\n\nexport type RegisterInput = {\n\treadonly driver: \"vercel\" | \"daytona\";\n\treadonly providerResourceId: string;\n};\n\nconst registered = Effect.fn(\"Sandbox.registered\")(function* (name: string) {\n\tconst registry = yield* SandboxDriver.Registry;\n\treturn yield* registry.get(SandboxDriver.Name.make(name));\n});\n\nexport const create = Effect.fn(\"Sandbox.create\")(function* (input: CreateInput) {\n\tconst controller = yield* SandboxController.Controller;\n\tconst driver = yield* registered(input.driver);\n\tif (input.driver === \"memory\") {\n\t\tconst cwd = SandboxDriver.AbsolutePath.make(input.cwd ?? \"/\");\n\t\treturn yield* controller.create({ driver, config: { defaultCwd: cwd, initializeCwd: cwd } });\n\t}\n\tif (input.driver === \"sqldb\") {\n\t\tconst cwd = SandboxDriver.AbsolutePath.make(input.cwd ?? \"/\");\n\t\treturn yield* controller.create({\n\t\t\tdriver,\n\t\t\tconfig: {\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t\tinitializeCwd: cwd,\n\t\t\t\t...(input.location === undefined ? {} : { location: input.location }),\n\t\t\t},\n\t\t});\n\t}\n\tconst { driver: _, ...config } = input;\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\treturn yield* controller.register({ driver, providerResourceId: input.providerResourceId });\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: SandboxDriver.Name.make(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 const Drivers = {\n\tget memory(): Driver {\n\t\treturn MemorySandboxDriver.make().driver;\n\t},\n\tget sqldb(): Driver {\n\t\treturn SqldbSandboxDriver.make().driver;\n\t},\n\tvercel: (options: VercelSandboxDriver.ClientOptions = {}): Driver => VercelSandboxDriver.make(options),\n\tdaytona: (options: DaytonaSandboxDriver.ClientOptions = {}): Driver => DaytonaSandboxDriver.make(options),\n} as const;\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 type { EventSchema } from \"../event/schema.ts\";\nimport * as Event from \"../event/event.ts\";\nimport { EventList } from \"../event/list.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 { State } from \"../state/state.ts\";\nimport type { StatePrompt } from \"../state/prompt.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 Pick<RuntimeInput, \"tools\" | \"systemPrompt\"> {\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 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\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 events = yield* Event.Service;\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\tif (input.model !== undefined || input.thinkingLevel !== undefined) {\n\t\tyield* events.publish(EventList.ConfigChanged, {\n\t\t\ttimestamp: yield* DateTime.now,\n\t\t\tsessionId: id,\n\t\t\t...(input.model === undefined ? {} : { model: { providerId: input.model.provider, modelId: input.model.id } }),\n\t\t\t...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),\n\t\t});\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\tyield* runtime.set(input.sessionId, runtimeBindings(input));\n\treturn found.value;\n});\n\nexport { AbsolutePath, SessionMessageSchema, SessionSchema };\n\nexport * as Session from \"./session.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA,MAAM,kCAAkB,IAAI,QAA2D;AAEvF,MAAM,qBAAwC,WAA2D;CACxG,MAAM,SAAS,gBAAgB,IAAI,MAAM;CACzC,IAAI,WAAW,KAAA,GAAW,OAAO;CACjC,MAAM,WAAW,cAAc,QAAQ,MAAM;CAC7C,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACR;AAEA,MAAM,kBAAkB,UAGV;CACb,IAAI,MAAM,cAAc,OAAO,MAAM,aAAa,UAAU,CAAC;CAC7D,MAAM,WAAW,MAAM,QAAQ;CAC/B,OAAO,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK,IAAI,IAAI;AACxD;AAEA,MAAM,uBAA0C,QAAW,OAAgB,UAA6B;CACvG,MAAM,YAAY,kBAAkB,MAAM;CAC1C,IAAI,UAAU,MAAM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AU,SAAS,MAAM,MAAM;EAAG,EAAE;EAC5G,GAAI,MAAM,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,MAAM,cAAc;CACnF,CAAC;CAEF,OAAO,QAAQ,IAAI,IAAI,gBAAgB,KAAK,CAAC;CAC7C,OAAO,OAAO,WAAW,EAAE;AAC5B,CAAC;AAED,MAAa,MAAM,OAAO,GAAG,aAAa,CAAC,CAAC,WAAW,WAA6B;CAEnF,MAAM,QAAQ,QAAO,OADGT,WAAAA,CACM,IAAI,SAAS;CAC3C,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,OAAO,KAAa;CACrD,OAAO,OAAO,KAAK,OAAO,WAAW,SAAS,CAAC;AAChD,CAAC;AAED,MAAa,SAAS,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAAW,OAAoB;CAChF,MAAM,QAAQ,OAAO,IAAI,MAAM,SAAS;CACxC,IAAI,OAAO,OAAO,KAAK,GACtB,OAAO,OAAO,IAAII,qBAAkC,EAAE,WAAW,MAAM,UAAU,CAAC;CAGnF,QAAO,OADgBI,UAAAA,CACR,IAAI,MAAM,WAAW,gBAAgB,KAAK,CAAC;CAC1D,OAAO,MAAM;AACd,CAAC"}
|
|
1
|
+
{"version":3,"file":"session-CF1B0VEr.mjs","names":["AbsolutePath","ID","Usage","Service","make","build","layer","layer","Str","Global.resolve","defaultLayer","reasonOf","ID","define","ID","Model","EventSchema.ID","SandboxInstance.ID","SandboxInstance.Kind","SandboxInstance.Ownership","SandboxInstance.Status","SandboxInstance.PersistedError","AbsolutePath","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","ConfigChangeData","SessionSchema.CompactionData","Service","layer","Session.Service","Session.SessionNotFoundError","Service","withCwd","path","Shell","FileSystem","SandboxFileSystem.Service","ShellTag","SandboxInstance.ID","SandboxInstance.Status","SandboxInstance.PersistedError","errorMessage","layer","Buffer","make","SandboxFileSystem.isNotFoundError","layer","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","layer","Shell","layer","Local.Vfs","Process.host","make","SandboxInstance.ID","Local.layer","HostExe.layer","EnvNodeJSDefault.layer","SandboxInstance.PersistedError","encodeUnknownJson","make","SandboxDriver.Registry","SandboxStore.make","SandboxIO.resolveMountCwd","SandboxInstance.isMountable","SandboxIO.FileSystem","SandboxIO.Shell","SandboxIO.Current","SandboxFileSystem.withCwd","shellWithCwd","layer","Buffer","make","Seed.initialize","Buffer","Shell","make","transport","Local.Vfs","Local.layer","EnvBash.transport","transport","Local.Vfs","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","SandboxDriver.RuntimeConfigBase","make","SandboxDriver.driver","EnvInMemory.make","transport","make","Seed.initialize","Local.Vfs","layer","Process.host","Process.unsupported","CreateConfig","SandboxDriver.AbsolutePath","RuntimeConfig","make","EnvSqldb.layer","SandboxDriver.driver","EnvSqldb.make","transport","resolvePath","make","Service","DEFAULT_CWD","SandboxIO.resolveMountCwd","SandboxInstance.PersistedError","Remote","statsFrom","providerFrom","Buffer","exec","execArgv","transport","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","resourceLayer","SandboxResource.Service","CreateConfig","RuntimeConfig","SandboxDriver.AbsolutePath","name","statusFrom","make","SandboxDriver.driver","EnvDaytona.mountCwd","EnvDaytona.transport","SandboxInstance.PersistedError","Buffer","SandboxFileSystem.isNotFoundError","stream","SandboxFileSystem.Service","SandboxFileSystem.fromProvider","RemoteFileSystem.make","Shell","SandboxResource.Service","SandboxDriver.AbsolutePath","make","EnvVercel.credentialsFrom","SandboxDriver.driver","EnvVercel.createSandbox","EnvVercel.transport","AbsolutePath","Service","layer","SandboxIO.FileSystem","SandboxIO.Shell","SandboxFs.up","path","AbsolutePath","Service","layer","SandboxIO.FileSystem","SandboxFs.up","SandboxFs.isDirectory","SandboxFs.readFileSafe","AbsolutePath","SandboxInstance.ID","Info","Hash.fast","Service","layer","SandboxIO.FileSystem","Git.Service","ProjectCopy.Service","SandboxIO.Current","SandboxInstance.toColumn","AbsolutePath","SandboxInstance.fromField","path","Model","SandboxInstance.toField","Ref","AbsolutePath","SandboxInstance.ID","ProjectSchema.ID","ProjectSchema.Vcs","Service","layer","SandboxIO.Current","Project.Service","SandboxInstance.ID","SessionMessageSchema.ID","EventList.TurnAbortCause","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","Runner.ProviderTurnError","Runner.ModelNotFoundError","aikitStream","make","make","Shell","make","register","Tool.define","Tool.implement","endTime","make","Executor.make","Service","layer","layer","SessionRuntime.Service","SessionContext.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","Runner.TurnError","EventList.TurnAborted","run","layer","Event.Service","SessionInput.make","Session.Service","EventList.ConfigChanged","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.resolveLocation","SandboxDriver.layer","SandboxController.layer","Loop.layer","LLM.make","State.layer","SessionRuntime.layer","Context.layer","SessionLive.layer","Event.layer","SandboxDriver.Registry","create","SandboxController.Controller","get","MemorySandboxDriver.make","SqldbSandboxDriver.make","VercelSandboxDriver.make","DaytonaSandboxDriver.make","EventList.ConfigChanged","SessionStore.Service","Control.Service","Event.Service","SandboxController.Controller","SessionStore.SessionNotFoundError","SandboxInstanceSchema.fromField","AbsolutePath","create","SessionRuntime.Service"],"sources":["../../src/schema.ts","../../src/session/schema.ts","../../src/host.ts","../../src/posix.ts","../../src/global.ts","../../src/db/migrations.ts","../../src/db/db.ts","../../src/event/schema.ts","../../src/sandbox/instance.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/fs/filesystem.ts","../../src/sandbox/shell/shell.ts","../../src/sandbox/io.ts","../../src/sandbox/errors.ts","../../src/sandbox/driver.ts","../../src/sandbox/fs/vfs.ts","../../src/sandbox/shell/host.ts","../../src/sandbox/utils/process.ts","../../src/sandbox/fs/nodejs.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/fs/remote.ts","../../src/sandbox/resource.ts","../../src/sandbox/providers/daytona.ts","../../src/sandbox/drivers/daytona.ts","../../src/sandbox/providers/vercel.ts","../../src/sandbox/drivers/vercel.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/runner/llm.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/session/runtime.ts","../../src/state/prompt.ts","../../src/state/state.ts","../../src/runner/loop.ts","../../src/session/projector.ts","../../src/session/live.ts","../../src/effect/harness.ts","../../src/effect/sandbox.ts","../../src/effect/session.ts"],"sourcesContent":["import { Message } from \"@codeworksh/aikit\";\nimport { Option, Schema, SchemaGetter, DateTime } from \"effect\";\nimport type { Static, TSchema } from \"typebox\";\nimport TypeBoxSchema from \"typebox/schema\";\n\nconst aikitValidators = new WeakMap<TSchema, ReturnType<typeof TypeBoxSchema.Compile>>();\n\nconst aikitValidatorFor = <T extends TSchema>(schema: T): ReturnType<typeof TypeBoxSchema.Compile<T>> => {\n\tconst cached = aikitValidators.get(schema) as ReturnType<typeof TypeBoxSchema.Compile<T>> | undefined;\n\tif (cached !== undefined) return cached;\n\tconst compiled = TypeBoxSchema.Compile(schema);\n\taikitValidators.set(schema, compiled);\n\treturn compiled;\n};\n\nconst aikitErrorPath = (error: {\n\treadonly instancePath?: string;\n\treadonly params?: Record<string, unknown>;\n}): string => {\n\tif (error.instancePath) return error.instancePath.substring(1);\n\tconst required = error.params?.requiredProperties;\n\treturn Array.isArray(required) ? required.join(\", \") : \"root\";\n};\n\nconst validateAikitSchema = <T extends TSchema>(schema: T, value: unknown, label: string): Static<T> => {\n\tconst validator = aikitValidatorFor(schema);\n\tif (validator.Check(value)) return value;\n\n\tconst [, issues] = validator.Errors(value);\n\tconst details = issues.map((issue) => ` - ${aikitErrorPath(issue)}: ${issue.message}`).join(\"\\n\") || \"unknown error\";\n\tthrow new Error(`validation failed for ${label}\\n${details}`);\n};\n\n/** Validate an aikit message without coercing or rewriting durable data. */\nexport const validateAikitMessage = (value: unknown, label: string): Message.Message =>\n\tvalidateAikitSchema(Message.MessageSchema, value, label);\n\nexport const validateAikitUserMessage = (value: unknown, label: string): Message.UserMessage =>\n\tvalidateAikitSchema(Message.UserMessageSchema, value, label);\n\nexport const validateAikitAssistantMessage = (value: unknown, label: string): Message.AssistantMessage =>\n\tvalidateAikitSchema(Message.AssistantMessageSchema, value, label);\n\nexport const validateAikitToolCallTerminalPart = (value: unknown, label: string): Message.ToolCallTerminalPart =>\n\tvalidateAikitSchema(Message.ToolCallTerminalPartSchema, value, label);\n\nexport const isAikitAssistantMessage = (value: unknown): value is Message.AssistantMessage =>\n\taikitValidatorFor(Message.AssistantMessageSchema).Check(value);\n\nexport const isAikitToolCallTerminalPart = (value: unknown): value is Message.ToolCallTerminalPart =>\n\taikitValidatorFor(Message.ToolCallTerminalPartSchema).Check(value);\n\n/**\n * Integer greater than zero.\n */\nexport const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\n\n/**\n * Integer greater than or equal to zero.\n */\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Cost greater than or equal with finite value\n */\nexport const NonNegativeCost = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0));\n\n/**\n * Relative file path (e.g., `src/components/Button.tsx`).\n */\nexport const RelativePath = Schema.String.pipe(Schema.brand(\"RelativePath\"));\nexport type RelativePath = Schema.Schema.Type<typeof RelativePath>;\n\n/**\n * Absolute file path (e.g., `/home/user/projects/myapp/src/main.ts`).\n */\nexport const AbsolutePath = Schema.String.pipe(Schema.brand(\"AbsolutePath\"));\nexport type AbsolutePath = Schema.Schema.Type<typeof AbsolutePath>;\n\n/**\n * Optional public JSON field that can hold explicit `undefined` on the type\n * side but encodes it as an omitted key, matching legacy `JSON.stringify`.\n */\nexport const optional = <S extends Schema.Top>(schema: S) =>\n\tSchema.optionalKey(schema).pipe(\n\t\tSchema.decodeTo(Schema.optional(schema), {\n\t\t\tdecode: SchemaGetter.passthrough({ strict: false }),\n\t\t\tencode: SchemaGetter.transformOptional(Option.filter((value) => value !== undefined)),\n\t\t}),\n\t);\n\n/**\n * Strip `readonly` from a nested type. Stand-in for `effect`'s `Types.DeepMutable`\n * until `effect:core/x228my` (\"Types.DeepMutable widens unknown to `{}`\") lands.\n *\n * The upstream version falls through `unknown` into `{ -readonly [K in keyof T]: ... }`\n * where `keyof unknown = never`, so `unknown` collapses to `{}`. This local\n * version gates the object branch on `extends object` (which `unknown` does\n * not) so `unknown` passes through untouched.\n *\n * Primitive bailout matches upstream — without it, branded strings like\n * `string & Brand<\"SessionID\">` fall into the object branch and get their\n * prototype methods walked.\n *\n * Tuple branch preserves readonly tuples (e.g. `ConfigPlugin.Spec`'s\n * `readonly [string, Options]`); the general array branch would otherwise\n * widen them to unbounded arrays.\n */\nexport type DeepMutable<T> = T extends string | number | boolean | bigint | symbol | Function\n\t? T\n\t: T extends readonly [unknown, ...unknown[]]\n\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t: T extends readonly (infer U)[]\n\t\t\t? DeepMutable<U>[]\n\t\t\t: T extends object\n\t\t\t\t? { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\t\t\t\t: T;\n\n/**\n * Attach static methods to a schema object. Designed to be used with `.pipe()`:\n *\n * @example\n * export const Foo = fooSchema.pipe(\n * withStatics((schema) => ({\n * zero: schema.make(0),\n * from: Schema.decodeUnknownOption(schema),\n * }))\n * )\n */\nexport const withStatics =\n\t<S extends object, M extends Record<string, unknown>>(methods: (schema: S) => M) =>\n\t(schema: S): S & M =>\n\t\tObject.assign(schema, methods(schema));\n\n/**\n * Nominal wrapper for scalar types. The class itself is a valid schema —\n * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc.\n *\n * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type`\n * of a field using this newtype resolves to `Self` rather than the underlying\n * branded phantom. Without that override, passing a class instance to code\n * typed against `Schema.Schema.Type<FieldSchema>` would require a cast even\n * though the values are structurally equivalent at runtime.\n *\n * @example\n * class QuestionID extends Newtype<QuestionID>()(\"QuestionID\", Schema.String) {\n * static make(id: string): QuestionID {\n * return this.make(id)\n * }\n * }\n *\n * Schema.decodeEffect(QuestionID)(input)\n */\nexport function Newtype<Self>() {\n\treturn <const Tag extends string, S extends Schema.Top>(tag: Tag, schema: S) => {\n\t\tabstract class Base {\n\t\t\tdeclare readonly _newtype: Tag;\n\n\t\t\tstatic make(value: Schema.Schema.Type<S>): Self {\n\t\t\t\treturn value as unknown as Self;\n\t\t\t}\n\t\t}\n\n\t\tObject.setPrototypeOf(Base, schema);\n\n\t\treturn Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & {\n\t\t\treadonly make: (value: Schema.Schema.Type<S>) => Self;\n\t\t} & Omit<Schema.Opaque<Self, S, {}>, \"make\" | \"~type.make\"> & {\n\t\t\t\treadonly \"~type.make\": Self;\n\t\t\t};\n\t};\n}\n\nexport const DateTimeUtcFromMillis = Schema.Finite.pipe(\n\tSchema.decodeTo(Schema.DateTimeUtc, {\n\t\tdecode: SchemaGetter.transform((value) => DateTime.makeUnsafe(value)),\n\t\tencode: SchemaGetter.transform((value) => DateTime.toEpochMillis(value)),\n\t}),\n);\n","import { Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { NonNegativeCost, NonNegativeInt, withStatics } from \"../schema.ts\";\n\n// Session identity. Branded so a session ID is not interchangeable with an\n// entry, part, or workspace ID at the type level — service signatures take\n// `SessionSchema.ID`, never a bare `string`.\n//\n// `create` mints a new one; `ascending` adopts an ID that came from outside\n// (a persisted row, a request payload) and rejects a foreign prefix rather\n// than branding it silently. uuidv7 keeps IDs lexicographically sortable by\n// creation time, so `ORDER BY id` is `ORDER BY created`.\nexport const ID = Schema.String.check(Schema.isStartsWith(\"ses\")).pipe(\n\tSchema.brand(\"Session.ID\"),\n\twithStatics((schema) => ({\n\t\tascending: (id?: string) => {\n\t\t\tif (!id) return schema.make(\"ses_\" + uuidv7());\n\t\t\tif (!id.startsWith(\"ses\")) throw new Error(`ID ${id} does not start with ses`);\n\t\t\treturn schema.make(id);\n\t\t},\n\t\tcreate: () => schema.make(\"ses_\" + uuidv7()),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\nexport const IDFromDb = Schema.String.pipe(Schema.brand(\"Session.ID\"));\n\n// 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 } from \"@effect/platform-node\";\nimport { Effect, FileSystem } 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","import { Effect, Path } from \"effect\";\n\n/** Shared POSIX path implementation for sandbox and remote-runtime paths. */\nexport const posix = Effect.runSync(Path.Path.pipe(Effect.provide(Path.layer)));\n","import { Config, Context, Effect, Layer } from \"effect\";\nimport * as os from \"node:os\";\nimport { fileSystem } from \"./host.ts\";\nimport { posix } from \"./posix.ts\";\n\nexport const configDir = \".codework\";\nexport const app = \"codework\";\n\nconst defaultHome = posix.join(os.homedir(), configDir);\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 agent: 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\tagent: input.agent ?? posix.join(home, \"agent\"),\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.agent, { 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 \"../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 resolveLocation(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 resolveLocation(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 { Option, Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport { withStatics } from \"../schema.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\n\n/**\n * A Sandbox instance is a **durable filesystem namespace** plus whatever compute\n * acts on it — a device in Unix terms, which exists whether or not anything has\n * it mounted. `Sandbox.Controller` is the only thing that creates,\n * stops, or destroys one; this module is just its identity and state model.\n *\n * The application ID is deliberately separate from the driver's own resource\n * locator: callers never parse a Vercel name or a Daytona ID, driver formats may\n * change, and a destroyed resource must stay identifiable in Project/Session\n * history. A missing resource is never recreated under an existing ID — a new\n * resource is a new namespace and therefore a new ID.\n */\n\nexport const ID = Schema.String.pipe(\n\tSchema.brand(\"SandboxInstance.ID\"),\n\twithStatics((schema) => ({\n\t\t/**\n\t\t * The host. Reserved, and never written to a column — see {@link toColumn}.\n\t\t * It exists at runtime so nothing has to branch on \"is this the host\": it is\n\t\t * what identity reads, what logs show, and what the transport cache keys on.\n\t\t */\n\t\tlocal: schema.make(\"local\"),\n\t\t/** A fresh identity for a namespace nothing has named yet. */\n\t\tcreate: () => schema.make(`sbx_${uuidv7()}`),\n\t})),\n);\nexport type ID = typeof ID.Type;\n\n/**\n * The storage boundary for namespace references, in one place.\n *\n * The host filesystem exists whether or not a row describes it, so it gets no\n * row and `NULL` is the only spelling of it — the Unix analogue is exact, since\n * `/` has no entry in the mount table you consult to find other mounts. That\n * makes a session or directory writable before any namespace is registered (the\n * foreign key is skipped on NULL), makes `SET sandbox_instance_id = NULL` a\n * meaningful \"revert to the host\", and leaves the host impossible to tombstone,\n * collect, or destroy, because there is nothing to point at.\n *\n * Two SQLite consequences ride on this and break correctness silently if missed:\n * unique indexes treat NULLs as distinct, so every uniqueness constraint\n * spanning a namespace column coalesces to `'local'`; and `= NULL` never\n * matches, so namespace-scoped reads use `IS`.\n */\nexport const toColumn = (id: ID): string | null => (id === ID.local ? null : id);\nexport const fromColumn = (value: string | null): ID => (value === null ? ID.local : ID.make(value));\n\n/**\n * The same mapping for row models, whose optional columns are `Option` rather\n * than `null`. Kept beside {@link toColumn} so the boundary stays one place:\n * `toColumn`/`fromColumn` for SQL parameters, these for `Model.FieldOption`.\n */\nexport const toField = (id: ID): Option.Option<ID> => (id === ID.local ? Option.none() : Option.some(id));\nexport const fromField = (value: Option.Option<ID>): ID => Option.getOrElse(value, () => ID.local);\n\n/**\n * Filesystem-class taxonomy, mirroring Unix: disk, tmpfs/procfs, NFS/CIFS.\n * Stored on the row rather than derived from the registered driver, so reading\n * an instance never depends on the registry — which matters most when a driver\n * is *not* configured and you need to list or clean up its rows.\n */\nexport const Kind = Schema.Literals([\"local\", \"virtual\", \"remote\"]);\nexport type Kind = typeof Kind.Type;\n\nexport const Ownership = Schema.Literals([\"managed\", \"external\"]);\nexport type Ownership = typeof Ownership.Type;\n\n/**\n * Lifecycle state, in ZFS pool vocabulary. This is the **last observed** value,\n * not live driver truth: Daytona auto-stops and auto-archives, Vercel sandboxes\n * expire on their own timeout, so drift is normal. `stateObservedAt` carries the\n * freshness and `Controller.refresh` updates it without waking anything.\n *\n * `removed` and `unavail` are deliberately distinct. `removed` means we deleted\n * it; `unavail` means the driver claims it is gone. A \"not found\" is frequently a\n * misclassification — wrong region, wrong API url, a revoked key answering 404,\n * eventual consistency right after create — so it must never be recorded as if we\n * had destroyed the resource ourselves.\n */\nexport const Status = Schema.Literals([\n\t\"provisioning\",\n\t\"online\",\n\t\"offline\",\n\t\"suspending\",\n\t\"removing\",\n\t\"removed\",\n\t\"unavail\",\n\t\"faulted\",\n]);\nexport type Status = typeof Status.Type;\n\n/**\n * The statuses a `mount` may proceed from. This is the predicate every\n * conditional write depends on, so it is enumerated once here rather than\n * restated as prose at each call site.\n *\n * `offline` qualifies because mounting wakes.\n * `faulted` qualifies because a fault is a *usability* condition, not an identity one — see {@link Status}.\n *\n * There is no `resuming`: it would exist to be observed by nothing, since\n * mounting wakes, `offline` is already mountable, and waking is not destructive\n * so it needs no claim. `suspending` and `removing` stay because they *are*\n * compare-and-set claims, blocking a concurrent mount mid-destruction.\n */\nexport const mountable: ReadonlySet<Status> = new Set<Status>([\"online\", \"offline\", \"faulted\"]);\n\nexport const isMountable = (status: Status): boolean => mountable.has(status);\n\n/**\n * Reference state, derived — never stored. `busy` carries its `umount` meaning:\n * something holds this and destruction must not proceed unforced.\n *\n * `pinned` is the kernel sense of the word: never reclaimable. It short-circuits\n * counting entirely for instances that cannot be stopped or destroyed (the local\n * host), which is what keeps them out of any future collector by construction\n * rather than by an ownership check happening to catch them.\n */\nexport const Usage = Schema.Literals([\"idle\", \"busy\", \"pinned\"]);\nexport type Usage = typeof Usage.Type;\n\n/** Sanitized driver failure. The only error shape allowed to be persisted or logged. */\nexport const PersistedError = Schema.Struct({\n\tname: Schema.String,\n\tmessage: Schema.String,\n\tcode: Schema.optional(Schema.String),\n});\nexport type PersistedError = typeof PersistedError.Type;\n\n/** Durable metadata, safe to return and persist. Assembled by the control plane. */\nexport interface Info {\n\treadonly id: ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: Kind;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly ownership: Ownership;\n\treadonly status: Status;\n\treadonly usage: Usage;\n\t/** References held by *this* control plane. Process-local; see the transport cache. */\n\treadonly refCount: number;\n\treadonly providerStatus: Option.Option<string>;\n\treadonly metadata: Readonly<Record<string, string>>;\n\treadonly lastError: Option.Option<PersistedError>;\n\treadonly createdAt: Date;\n\treadonly updatedAt: Date;\n\treadonly stateObservedAt: Date;\n\treadonly lastMountedAt: Option.Option<Date>;\n\treadonly lastUnmountedAt: Option.Option<Date>;\n\treadonly lastUsedAt: Option.Option<Date>;\n\treadonly removedAt: Option.Option<Date>;\n}\n\nexport * as SandboxInstance from \"./instance.ts\";\n","import { Schema } from \"effect\";\nimport { withStatics } from \"../../schema.ts\";\n\n// TODO: add support for diff input types\n// as supported by packages/aikit\nexport const Prompt = Schema.Struct({\n\ttext: Schema.String,\n})\n\t.annotate({ identifier: \"Prompt\" })\n\t.pipe(\n\t\twithStatics((schema) => ({\n\t\t\tequivalence: Schema.toEquivalence(schema),\n\t\t\tfromUserMessage: (input: Pick<Prompt, \"text\">) =>\n\t\t\t\tschema.make({\n\t\t\t\t\ttext: input.text,\n\t\t\t\t}),\n\t\t})),\n\t);\nexport type Prompt = typeof Prompt.Type;\n\nexport const Delivery = Schema.Literals([\"steer\", \"followUp\"]);\nexport type Delivery = typeof Delivery.Type;\n\nexport * as PromptSchema from \"./schema.ts\";\n","import { Schema } from \"effect\";\nimport { 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, optional } 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\nexport 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});\nexport 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\tConfigChanged,\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","// API that deals with event\n\nimport { Effect, Context, Layer, Option, PubSub, Cause, 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 { EventSchema } from \"./schema.ts\";\nimport { EventManifest } from \"./manifest.ts\";\nimport type { Data, Definition, ID, Payload } 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\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\tdurable: new Map<string, Set<PubSub.PubSub<void>>>(),\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\tyield* Effect.forEach(\n\t\t\t\t\tpubsub.durable.values(),\n\t\t\t\t\t(wakes) => Effect.forEach(wakes, PubSub.shutdown, { discard: true }),\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\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\t// Durable subscribers carry no payload -- they re-read from their own\n\t\t\t\t// cursor, so one content-free wake per aggregate is enough.\n\t\t\t\tyield* Effect.forEach(pubsub.durable.get(aggregateId) ?? [], (wake) => PubSub.publish(wake, undefined), {\n\t\t\t\t\tdiscard: true,\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 tail = streamAll().pipe(\n\t\t\t\tStream.filter((event) => (event.data as { readonly sessionId?: unknown }).sessionId === input.sessionId),\n\t\t\t);\n\t\t\tif (input.after === undefined) return tail;\n\n\t\t\tconst history = Stream.paginate(\n\t\t\t\tinput.after,\n\t\t\t\tEffect.fn(\"Event.stream.history\")(function* (after) {\n\t\t\t\t\tconst page = yield* readAggregate({\n\t\t\t\t\t\taggregateId: input.sessionId,\n\t\t\t\t\t\tafter,\n\t\t\t\t\t\tlimit: 100,\n\t\t\t\t\t\tmanifest: EventManifest.Manifest,\n\t\t\t\t\t});\n\t\t\t\t\tconst last = page.events.at(-1);\n\t\t\t\t\tconst next =\n\t\t\t\t\t\tpage.hasMore && last?.durable !== undefined ? Option.some(last.durable.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\t\t\treturn history.pipe(\n\t\t\t\tStream.map((event) => event as Payload),\n\t\t\t\tStream.concat(tail),\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 EntryType,\n\tentryStates,\n\tentryTypes,\n\ttype EntryState,\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 EntryType,\n\ttype EntryState,\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\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, Model } 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 EffectiveConfig {\n\treadonly model?: {\n\t\treadonly providerId: string;\n\t\treadonly modelId: string;\n\t};\n\treadonly thinkingLevel?: Model.ThinkingLevel;\n}\n\nexport interface Snapshot {\n\treadonly sessionId: string;\n\treadonly leafEntryId: string | null;\n\treadonly messages: ReadonlyArray<Message.Message>;\n\treadonly config: EffectiveConfig;\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 ConfigChangeData = Schema.fromJsonString(\n\tSchema.Struct({\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\nconst decodeSyntheticData = Schema.decodeUnknownEffect(SyntheticData);\nconst decodeCompactionData = Schema.decodeUnknownEffect(SessionSchema.CompactionData);\nconst decodeBranchSummaryData = Schema.decodeUnknownEffect(BranchSummaryData);\nconst decodeCustomData = Schema.decodeUnknownEffect(CustomData);\nconst decodeConfigChangeData = Schema.decodeUnknownEffect(ConfigChangeData);\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 model: EffectiveConfig[\"model\"];\n\tlet thinkingLevel: Model.ThinkingLevel | undefined;\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\tmodel = { providerId: message.provider.id, modelId: message.model };\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\tcase \"configChange\": {\n\t\t\t\tconst data = yield* decodeConfigChangeData(entry.data).pipe(Effect.mapError(decodeFailure(hydrated)));\n\t\t\t\tif (data.model !== undefined) model = data.model;\n\t\t\t\tif (data.thinkingLevel !== undefined) thinkingLevel = data.thinkingLevel;\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\tconfig: {\n\t\t\t...(model === undefined ? {} : { model }),\n\t\t\t...(thinkingLevel === undefined ? {} : { thinkingLevel }),\n\t\t},\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 \"../../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, Schema } from \"effect\";\nimport { posix } from \"../../posix.ts\";\n\n/**\n * The runtime filesystem contract, independent of any backend.\n *\n * Two surfaces, deliberately:\n * - {@link Provider} is what a backend implements — plain promises that reject,\n * matching every SDK we wrap.\n * - {@link Interface} is what the harness consumes — Effect with a typed error\n * channel and tracing spans. {@link fromProvider} bridges the two exactly\n * once, so no consumer ever writes `Effect.tryPromise` against a filesystem.\n *\n * Implementations:\n * - Local:\n * implement it over a VFS (`./local`);\n * local filesystem use OS primitives; hence have broader filesytem capabilities.\n *\n * - Remote:\n * implement it over a provider (`./remote`).\n * remote filesytems depends on the interface provided by the remote provider; hence can have limited filesytem capabilities.\n *\n * `isFile`/`isDirectory` are required booleans; size, mtime, and isSymbolicLink are omitted when the\n * backend cannot report them — never fabricated.\n *\n * **Paths are POSIX, and the harness is Unix-only (for now!).** Every path uses `/`\n * separators on both the host and inside a sandbox — Windows is not supported,\n * so no translation layer exists. Consumers must use the shared Effect POSIX\n * path implementation, never the platform default, or a host running the harness would\n * impose its own flavour on a remote sandbox's paths. Relative paths resolve\n * against the backend's configured `cwd`.\n */\n\nexport class OperationUnsupportedError extends Schema.TaggedError<OperationUnsupportedError>()(\n\t\"OperationUnsupportedError\",\n\t{\n\t\toperation: Schema.String,\n\t\tmessage: Schema.String,\n\t},\n) {}\n\n/** A backend operation failed. `cause` carries the provider's own rejection. */\nexport class FileSystemError extends Schema.TaggedError<FileSystemError>()(\"SandboxFileSystemError\", {\n\tmethod: Schema.String,\n\tpath: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface FileStat {\n\treadonly isFile: boolean;\n\treadonly isDirectory: boolean;\n\treadonly isSymbolicLink?: boolean;\n\treadonly size?: number;\n\treadonly mtime?: Date;\n}\n\nexport interface RmOptions {\n\treadonly recursive?: boolean;\n\treadonly force?: boolean;\n}\n\n/** Whether a provider failure means the path itself is definitively absent. */\nexport const isNotFoundError = (cause: unknown) => {\n\tconst code = (cause as NodeJS.ErrnoException | undefined)?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n};\n\n/**\n * The backend-facing contract. Backends author plain promises and let them\n * reject; {@link fromProvider} turns rejections into typed failures.\n */\nexport interface Provider {\n\treadonly readFile: (path: string) => Promise<string>;\n\treadonly readFileBuffer: (path: string) => Promise<Uint8Array>;\n\t/**\n\t * Write the file. Parents may be missing — do not create them here;\n\t * {@link fromProvider} owns that guarantee for every backend.\n\t */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Promise<void>;\n\treadonly stat: (path: string) => Promise<FileStat>;\n\treadonly readdir: (path: string) => Promise<string[]>;\n\treadonly exists: (path: string) => Promise<boolean>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n\treadonly rm: (path: string, options?: RmOptions) => Promise<void>;\n\t/**\n\t * Metadata for the directory entry itself rather than a symlink's target.\n\t * Optional: a backend whose `stat` has mixed symlink semantics implements it\n\t * so symlink identity is asked for explicitly, never inferred.\n\t */\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\n/**\n * The consumer-facing contract. `exists` distinguishes \"absent\" from \"could not\n * tell\": a backend failure is a typed failure, not `false`, so a caller acting\n * on absence never acts on a network blip. Use `SandboxFs.existsOrFalse` where\n * a best-effort answer really is wanted.\n */\nexport interface Interface {\n\treadonly readFile: (path: string) => Effect.Effect<string, FileSystemError>;\n\treadonly readFileBuffer: (path: string) => Effect.Effect<Uint8Array, FileSystemError>;\n\t/** Creates missing parent directories, on every backend. */\n\treadonly writeFile: (path: string, content: string | Uint8Array) => Effect.Effect<void, FileSystemError>;\n\treadonly stat: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n\treadonly readdir: (path: string) => Effect.Effect<string[], FileSystemError>;\n\treadonly exists: (path: string) => Effect.Effect<boolean, FileSystemError>;\n\treadonly mkdir: (path: string, options?: { recursive?: boolean }) => Effect.Effect<void, FileSystemError>;\n\treadonly rm: (path: string, options?: RmOptions) => Effect.Effect<void, FileSystemError | OperationUnsupportedError>;\n\t// `lstat` is present only when the backend supports it; check before calling.\n\treadonly lstat?: (path: string) => Effect.Effect<FileStat, FileSystemError>;\n}\n\n/** The runtime filesystem service — the live {@link Interface} for the active sandbox. */\nexport class Service extends Context.Service<Service, Interface>()(\n\t\"@codeworksh/harness/sandbox/fs/filesystem/Service\",\n) {}\n\n/**\n * Reject `rm` options a provider does not implement, before any mutation. Only\n * `recursive` and `force` are part of the contract; anything else is refused\n * loudly rather than silently ignored.\n */\nexport const validateRmOptions = (\n\toptions: RmOptions | undefined,\n\toperation = \"rm\",\n): Effect.Effect<void, OperationUnsupportedError> =>\n\tEffect.suspend(() => {\n\t\tfor (const option of Object.keys((options ?? {}) as Record<string, unknown>)) {\n\t\t\tif (option === \"recursive\" || option === \"force\") continue;\n\t\t\treturn Effect.fail(new OperationUnsupportedError({ operation, message: `Unsupported rm option: ${option}` }));\n\t\t}\n\t\treturn Effect.void;\n\t});\n\n/**\n * Lift a {@link Provider} into the runtime {@link Interface}: one place that\n * converts rejections into {@link FileSystemError}, validates `rm` options,\n * creates missing parents on write, and names a tracing span per operation.\n */\nexport const fromProvider = (provider: Provider): Interface => {\n\tconst attempt = <A>(method: string, path: string, run: () => Promise<A>) =>\n\t\tEffect.tryPromise({ try: run, catch: (cause) => new FileSystemError({ method, path, cause }) });\n\n\t// The parent-creation guarantee, installed once for every backend instead of\n\t// re-implemented per provider: anything that reaches `Interface` reaches it\n\t// through here, so a backend cannot forget it.\n\t//\n\t// Lazy by design — try the write first, so the happy path stays a single call\n\t// and no remote backend pays a round-trip per write. A failure is usually a\n\t// missing parent, so create it and retry once. The mkdir's own error is\n\t// dropped on purpose: when the write failed for some other reason (EACCES,\n\t// EROFS, a dropped connection), the retry reproduces it, and *that* is the\n\t// failure the caller must see rather than a misleading mkdir error standing\n\t// in for it.\n\tconst writeCreatingParents = (path: string, content: string | Uint8Array) => {\n\t\tconst write = attempt(\"writeFile\", path, () => provider.writeFile(path, content));\n\t\tconst parent = posix.dirname(path);\n\t\treturn write.pipe(\n\t\t\tEffect.catch(() =>\n\t\t\t\tattempt(\"mkdir\", parent, () => provider.mkdir(parent, { recursive: true })).pipe(\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.andThen(write),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t};\n\n\treturn {\n\t\treadFile: Effect.fn(\"SandboxFileSystem.readFile\")((path: string) =>\n\t\t\tattempt(\"readFile\", path, () => provider.readFile(path)),\n\t\t),\n\t\treadFileBuffer: Effect.fn(\"SandboxFileSystem.readFileBuffer\")((path: string) =>\n\t\t\tattempt(\"readFileBuffer\", path, () => provider.readFileBuffer(path)),\n\t\t),\n\t\twriteFile: Effect.fn(\"SandboxFileSystem.writeFile\")(writeCreatingParents),\n\t\tstat: Effect.fn(\"SandboxFileSystem.stat\")((path: string) => attempt(\"stat\", path, () => provider.stat(path))),\n\t\t// carried through only when the backend actually implements it\n\t\t...(provider.lstat === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tlstat: Effect.fn(\"SandboxFileSystem.lstat\")((path: string) =>\n\t\t\t\t\t\tattempt(\"lstat\", path, () => provider.lstat!(path)),\n\t\t\t\t\t),\n\t\t\t\t}),\n\t\treaddir: Effect.fn(\"SandboxFileSystem.readdir\")((path: string) =>\n\t\t\tattempt(\"readdir\", path, () => provider.readdir(path)),\n\t\t),\n\t\t// A backend that cannot answer fails; it does not report \"absent\". A\n\t\t// caller acting on absence — deleting a record, say — must not be told\n\t\t// the path is gone because a token expired or a request timed out.\n\t\texists: Effect.fn(\"SandboxFileSystem.exists\")((path: string) =>\n\t\t\tattempt(\"exists\", path, () => provider.exists(path)),\n\t\t),\n\t\tmkdir: Effect.fn(\"SandboxFileSystem.mkdir\")((path: string, options?: { recursive?: boolean }) =>\n\t\t\tattempt(\"mkdir\", path, () => provider.mkdir(path, options)),\n\t\t),\n\t\trm: Effect.fn(\"SandboxFileSystem.rm\")((path: string, options?: RmOptions) =>\n\t\t\tvalidateRmOptions(options).pipe(Effect.andThen(attempt(\"rm\", path, () => provider.rm(path, options)))),\n\t\t),\n\t};\n};\n\n/**\n * Bind a cwd-neutral filesystem to one mount's working directory.\n *\n * The counterpart of `Shell.withCwd`, and the reason relative paths mean the\n * same thing to both: a shared transport stays rooted at the namespace root, so\n * resolution happens here, per mount, rather than inside a VFS whose `chdir` is\n * global state two mounts would fight over.\n */\nexport const withCwd = (fs: Interface, cwd: string): Interface => {\n\tconst at = (path: string) => posix.resolve(cwd, path);\n\treturn {\n\t\treadFile: (path) => fs.readFile(at(path)),\n\t\treadFileBuffer: (path) => fs.readFileBuffer(at(path)),\n\t\twriteFile: (path, content) => fs.writeFile(at(path), content),\n\t\tstat: (path) => fs.stat(at(path)),\n\t\treaddir: (path) => fs.readdir(at(path)),\n\t\texists: (path) => fs.exists(at(path)),\n\t\tmkdir: (path, options) => fs.mkdir(at(path), options),\n\t\trm: (path, options) => fs.rm(at(path), options),\n\t\t// carried through only when the backend implements it, so a caller can\n\t\t// still detect absence by checking the property\n\t\t...(fs.lstat === undefined ? {} : { lstat: (path: string) => fs.lstat!(at(path)) }),\n\t};\n};\n\nexport * as SandboxFileSystem from \"./filesystem.ts\";\n","import { Context, type Effect, Schema, type Stream } from \"effect\";\nimport { posix as path } from \"../../posix.ts\";\n\n/**\n * The pluggable execution contract. Local sandboxes usually get a Shell through\n * just-bash over the local `Local.Vfs`; remote sandboxes provide their own\n * native Shell. Either way the rest of the harness depends only on this service\n * tag.\n */\n\nexport class ShellError extends Schema.TaggedError<ShellError>()(\"ShellError\", {\n\tcommand: Schema.String,\n\tcause: Schema.optional(Schema.Defect()),\n}) {}\n\nexport interface ExecResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number;\n}\n\n/**\n * One options shape for every entry point. `cwd` is the operation-level\n * override: it wins over the mount's working directory, and a relative value\n * resolves against it. Neither mutates shared state, so concurrent commands in\n * one mount can run in different directories.\n */\nexport interface ShellOptions {\n\treadonly env?: Record<string, string>;\n\treadonly cwd?: string;\n}\n\n/**\n * A streamed chunk of command output, terminated by a single `exit` carrying the\n * exit code. (A backend-level mirror of the tool layer's event; kept here so\n * `sandbox/` does not depend on `tools/`.)\n */\nexport type ExecChunk =\n\t| { readonly _tag: \"stdout\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"stderr\"; readonly bytes: Uint8Array }\n\t| { readonly _tag: \"exit\"; readonly exitCode: number };\n\n/**\n * The command-execution capability a sandbox exposes. For an in-process\n * backend this is just-bash; for a remote backend it is the sandbox's own\n * shell. The {@link Shell} service tag carries this interface.\n */\nexport interface ISandboxExe {\n\treadonly exec: (command: string, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Run a program with an explicit argument vector, bypassing shell word\n\t * splitting. Callers that build commands from untrusted values — branch\n\t * names, file paths — must use this instead of interpolating into\n\t * {@link exec}, where a space or `$(…)` would change what runs.\n\t *\n\t * Backends whose transport only accepts a string quote the vector with\n\t * {@link quote}; backends that spawn directly pass it through untouched.\n\t */\n\treadonly execArgv: (argv: ReadonlyArray<string>, options?: ShellOptions) => Effect.Effect<ExecResult, ShellError>;\n\t/**\n\t * Optional streaming output: stdout/stderr chunks then a terminal `exit`.\n\t * Backends that can stream (e.g. Vercel) implement it; `ToolShell.fromSandboxShell`\n\t * bridges it to `ToolShell.stream` so the bash tool streams over them too.\n\t */\n\treadonly stream?: (command: string, options?: ShellOptions) => Stream.Stream<ExecChunk, ShellError>;\n}\n\ntype MountFactory = (cwd: string) => ISandboxExe;\n\n/**\n * Mount-local shell factories are attached out-of-band so the public Shell\n * contract stays about command execution only.\n *\n * Most transports are safely shared and need only the cwd wrapper below.\n * Stateful in-process interpreters use this hook to construct one interpreter\n * per mount while retaining the underlying filesystem transport. This tag must\n * remain on the outermost wrapper consumed by {@link withCwd}; wrapper helpers\n * such as {@link fromExec} must propagate it when they return a new object.\n */\nconst mountFactories = new WeakMap<object, MountFactory>();\n\nexport const perMount = (transport: ISandboxExe, make: MountFactory): ISandboxExe => {\n\tmountFactories.set(transport, make);\n\treturn transport;\n};\n\n/**\n * POSIX single-quote escaping: wrap in `'…'` and rewrite each embedded quote as\n * `'\\''`. Everything inside single quotes is literal to the shell, so this is\n * safe for arbitrary bytes.\n */\nexport const quote = (value: string) => `'${value.replace(/'/g, `'\\\\''`)}'`;\n\n/** Render an argument vector as one shell-safe command string. */\nexport const quoteArgv = (argv: ReadonlyArray<string>) => argv.map(quote).join(\" \");\n\n/**\n * Resolve a per-command cwd against the sandbox cwd. Passing a relative cwd\n * straight to a host or remote process API would otherwise resolve it against\n * that API's own default, which need not be the filesystem's configured cwd.\n */\nexport const resolveCwd = (base: string | undefined, cwd: string | undefined) => {\n\tif (cwd === undefined || path.isAbsolute(cwd) || base === undefined) return cwd ?? base;\n\treturn path.resolve(base, cwd);\n};\n\n/**\n * Complete a string-only backend: `execArgv` quotes the vector and runs it\n * through `exec`. Backends that spawn a real argument vector (Vercel) implement\n * `execArgv` themselves instead, so the args never meet a shell parser at all.\n *\n * `cwd` rides the options rather than a `cd <dir> && …` prefix. Every backend\n * we wrap takes a working directory natively, and the prefix form cannot tell a\n * failed `cd` from a failed command — both arrive as one exit code.\n */\nexport const fromExec = (backend: Omit<ISandboxExe, \"execArgv\">): ISandboxExe => {\n\tconst wrapped: ISandboxExe = {\n\t\t...backend,\n\t\texecArgv: (argv, options) => backend.exec(quoteArgv(argv), options),\n\t};\n\tconst mountFactory = mountFactories.get(backend);\n\treturn mountFactory === undefined ? wrapped : perMount(wrapped, (cwd) => fromExec(mountFactory(cwd)));\n};\n\n/**\n * Bind a cwd-neutral backend to one mount's working directory.\n *\n * The transport is shared between mounts and must stay rooted at the namespace\n * root, so the directory cannot live inside it: two mounts at different\n * directories would otherwise see each other's. This wrapper is per mount, and\n * an operation-level `cwd` still wins — resolved against the mount's, so a\n * relative one means what it reads like.\n */\nexport const withCwd = (backend: ISandboxExe, cwd: string): ISandboxExe => {\n\tconst mounted = mountFactories.get(backend)?.(cwd) ?? backend;\n\tconst at = (options?: ShellOptions): ShellOptions => {\n\t\tconst resolvedCwd = resolveCwd(cwd, options?.cwd);\n\t\treturn { ...options, ...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }) };\n\t};\n\tconst stream = mounted.stream;\n\treturn {\n\t\texec: (command, options) => mounted.exec(command, at(options)),\n\t\texecArgv: (argv, options) => mounted.execArgv(argv, at(options)),\n\t\t...(stream === undefined ? {} : { stream: (command, options) => stream(command, at(options)) }),\n\t};\n};\n\n/** Execution service — the live {@link ISandboxExe} for the active sandbox. */\nexport class Shell extends Context.Service<Shell, ISandboxExe>()(\"@codeworksh/harness/sandbox/shell/shell\") {}\n","import { Context, Effect, Layer as EffectLayer } from \"effect\";\nimport { posix } from \"../posix.ts\";\nimport type { SandboxDriver } from \"./driver.ts\";\nimport { SandboxFileSystem } from \"./fs/filesystem.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { type ISandboxExe, Shell as ShellTag, withCwd as shellWithCwd } from \"./shell/shell.ts\";\n\n/**\n * `SandboxIO` is a **mount**: a filesystem, a shell, and the identity and\n * working directory they act on.\n *\n * It is the whole vocabulary a consumer needs. Project, Git, Copy, Location, and\n * every tool ask for `SandboxIO.FileSystem`, `SandboxIO.Shell`, and\n * `SandboxIO.Current` — never for a driver, an address, or a provider SDK — so\n * a host directory, an in-memory VFS, and a remote microVM are interchangeable\n * behind one contract.\n *\n * The mount neither creates nor destroys infrastructure. `SandboxInstance` is\n * the durable namespace it acts on — a device, which exists whether or not\n * anything has it mounted — and `Sandbox.Controller` is the only path that\n * creates, stops, or destroys one.\n */\n\n/**\n * The filesystem tag. Re-exported here so consumers import one namespace —\n * Project, Git, Copy, and the runner ask for `SandboxIO.FileSystem`, never for\n * the module that happens to define it. Code *inside* `sandbox/` keeps importing\n * the tag directly, since `io.ts` is built on top of it.\n */\nexport const FileSystem = SandboxFileSystem.Service;\nexport type FileSystem = SandboxFileSystem.Service;\n\n/** The shell tag. Re-exported here so consumers import one namespace. */\nexport const Shell = ShellTag;\nexport type Shell = ShellTag;\n\n/**\n * What a mount sees: immutable identity, plus the working directory resolved for\n * *this* mount.\n *\n * Nothing mutable belongs here. `status`, `usage`, and reference counts all\n * change while a mount is open, so a mount-time snapshot of them would be wrong\n * by construction — runtime code that needs live management state asks the\n * control plane. The driver's own resource locator is likewise absent: consumers\n * never parse a Vercel name or a Daytona id.\n */\nexport interface Identity {\n\treadonly id: SandboxInstance.ID;\n\treadonly driver: SandboxDriver.Name;\n\treadonly kind: SandboxInstance.Kind;\n\t/** Absolute, and always a path in *this* namespace. */\n\treadonly cwd: string;\n}\n\n/** Identity and working directory of the current mount. */\nexport class Current extends Context.Service<Current, Identity>()(\"@codeworksh/harness/sandbox/io/Current\") {}\n\n/** Everything a mount provides. */\nexport type Provides = Current | SandboxFileSystem.Service | ShellTag;\n\n/** A built mount. */\nexport type Layer<E = never, RIn = never> = EffectLayer.Layer<Provides, E, RIn>;\n\n/**\n * Resolve a mount's cwd without consulting ambient process state.\n *\n * The default is supplied by the namespace adapter:\n * provider metadata remotely, `/` for a virtual filesystem, and `process.cwd()` for the host adapter.\n * An explicit absolute cwd replaces it; a relative cwd is resolved inside it. The\n * result is therefore always the one concrete absolute path `Current` requires.\n *\n * A non-absolute default throws rather than failing typed. It is the one\n * defect-level guard in this module, and deliberately so:\n * Adapters reading a value from a provider call this inside their own error channel,\n * where the throw becomes their typed failure (see `EnvDaytona.mountCwd`).\n */\nexport const resolveMountCwd = (defaultCwd: string, cwd?: string): string => {\n\tif (!posix.isAbsolute(defaultCwd)) {\n\t\tthrow new TypeError(`Sandbox default cwd must be absolute: ${defaultCwd}`);\n\t}\n\t// `resolve`, not `normalize`: normalize keeps a trailing slash, and `cwd` is\n\t// persisted — `Location.directory` and `project_directory`'s hash would read\n\t// `/workspace/` and `/workspace` as two directories and keep a row for each.\n\t//\n\t// A provider-reported default (`getWorkDir()`) or a config value is free to\n\t// carry one, so it is stripped here rather than at every reader.\n\tif (cwd === undefined) return posix.resolve(defaultCwd);\n\treturn posix.isAbsolute(cwd) ? posix.resolve(cwd) : posix.resolve(defaultCwd, cwd);\n};\n\n/**\n * Bind a cwd-neutral transport to one mount.\n *\n * The transport underneath is shared between\n * mounts and stays rooted at the namespace root, and everything directory-shaped\n * happens here, once per mount. Two mounts of one namespace at different working\n * directories therefore coexist without seeing or moving each other's.\n *\n * It consumes the same two tags it provides — the transport is supplied by the\n * layer this is composed over, not by itself.\n */\nexport const mount = (identity: Identity): EffectLayer.Layer<Provides, never, SandboxFileSystem.Service | ShellTag> =>\n\tEffectLayer.mergeAll(\n\t\tEffectLayer.succeed(Current, identity),\n\t\tEffectLayer.effect(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tEffect.map(SandboxFileSystem.Service, (fs) => SandboxFileSystem.withCwd(fs, identity.cwd)),\n\t\t),\n\t\tEffectLayer.effect(\n\t\t\tShellTag,\n\t\t\tEffect.map(ShellTag, (shell: ISandboxExe) => shellWithCwd(shell, identity.cwd)),\n\t\t),\n\t);\n\n/**\n * Just the identity tag, with no filesystem or shell beneath it. For consumers\n * assembled from stubs — a test that runs `Project` over a fake filesystem still\n * needs to know which namespace it is in.\n */\nexport const identityLayer = (identity: Identity) => EffectLayer.succeed(Current, identity);\n\n/** The host identity alone. See {@link identityLayer}. */\nexport const hostLayer = (cwd?: string) => identityLayer(host(cwd));\n\n/**\n * The host, rooted at `cwd`. Always `SandboxInstance.ID.local`: the working\n * directory selects where relative paths resolve, it does not make a second host\n * namespace — two mounts rooted at different directories still agree on absolute\n * paths.\n *\n * The host adapter defaults to `process.cwd()`, matching the OS process it wraps.\n * This is the one namespace where that coordinate is intrinsically valid; remote\n * and virtual adapters must never inherit it.\n */\nexport const host = (cwd?: string): Identity => ({\n\tid: SandboxInstance.ID.local,\n\tdriver: \"local\" as SandboxDriver.Name,\n\tkind: \"local\",\n\tcwd: resolveMountCwd(process.cwd(), cwd),\n});\n\n/**\n * A VFS-backed namespace. The id is minted per call unless one is named, because\n * building one of these builds a fresh VFS: N unnamed calls are N distinct\n * namespaces, none of which outlives the process. A file-backed store is the\n * exception — its file is the state, so whoever knows the file supplies the id\n * it was registered under.\n */\nexport const virtual = (input: {\n\treadonly driver: string;\n\treadonly id?: SandboxInstance.ID;\n\treadonly defaultCwd?: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id ?? SandboxInstance.ID.create(),\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"virtual\",\n\tcwd: resolveMountCwd(input.defaultCwd ?? \"/\", input.cwd),\n});\n\n/**\n * A provider-hosted namespace. The id is always supplied: a remote resource's\n * durable identity is minted and recorded by whoever provisioned it, never\n * derived here from the provider's own locator.\n */\nexport const remote = (input: {\n\treadonly driver: string;\n\treadonly id: SandboxInstance.ID;\n\t/** Namespace-intrinsic default supplied or discovered by the driver. */\n\treadonly defaultCwd: string;\n\treadonly cwd?: string;\n}): Identity => ({\n\tid: input.id,\n\tdriver: input.driver as SandboxDriver.Name,\n\tkind: \"remote\",\n\tcwd: resolveMountCwd(input.defaultCwd, input.cwd),\n});\n\nexport * as SandboxIO from \"./io.ts\";\n","import { Schema } from \"effect\";\nimport { SandboxInstance } from \"./instance.ts\";\n\n/**\n * Lifecycle errors are confined to the control plane. Once a mount succeeds,\n * consumers continue to see only FileSystemError and ShellError.\n */\nexport class SandboxNotFoundError extends Schema.TaggedError<SandboxNotFoundError>()(\"SandboxNotFoundError\", {\n\tid: SandboxInstance.ID,\n}) {}\n\nexport class SandboxDriverNotRegisteredError extends Schema.TaggedError<SandboxDriverNotRegisteredError>()(\n\t\"SandboxDriverNotRegisteredError\",\n\t{\n\t\tdriver: Schema.String,\n\t},\n) {}\n\nexport class SandboxDriverRegistrationError extends Schema.TaggedError<SandboxDriverRegistrationError>()(\n\t\"SandboxDriverRegistrationError\",\n\t{\n\t\tdriver: Schema.String,\n\t\treason: Schema.String,\n\t},\n) {}\n\nexport class SandboxBusyError extends Schema.TaggedError<SandboxBusyError>()(\"SandboxBusyError\", {\n\tid: SandboxInstance.ID,\n\trefCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nexport class SandboxMustBeStoppedError extends Schema.TaggedError<SandboxMustBeStoppedError>()(\n\t\"SandboxMustBeStoppedError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\tstatus: SandboxInstance.Status,\n\t},\n) {}\n\nexport class SandboxRemovedError extends Schema.TaggedError<SandboxRemovedError>()(\"SandboxRemovedError\", {\n\tid: SandboxInstance.ID,\n\tremovedAt: Schema.optional(Schema.DateTimeUtc),\n}) {}\n\nexport class SandboxUnavailError extends Schema.TaggedError<SandboxUnavailError>()(\"SandboxUnavailError\", {\n\tid: SandboxInstance.ID,\n\treason: Schema.String,\n}) {}\n\nexport class SandboxUnsupportedError extends Schema.TaggedError<SandboxUnsupportedError>()(\"SandboxUnsupportedError\", {\n\tid: SandboxInstance.ID,\n\tdriver: Schema.String,\n\toperation: Schema.String,\n}) {}\n\nexport class SandboxTransitionConflictError extends Schema.TaggedError<SandboxTransitionConflictError>()(\n\t\"SandboxTransitionConflictError\",\n\t{\n\t\tid: SandboxInstance.ID,\n\t\texpected: Schema.Array(SandboxInstance.Status),\n\t\tactual: SandboxInstance.Status,\n\t},\n) {}\n\n/**\n * A lifecycle failure safe to serialize, persist, or log.\n *\n * The raw SDK defect is deliberately absent from the schema. It is retained on\n * a non-enumerable symbol by {@link providerError}, so Effect's default\n * formatting and JSON serialization cannot expose credentials nested in it.\n */\nexport class SandboxProviderError extends Schema.TaggedError<SandboxProviderError>()(\"SandboxProviderError\", {\n\tdriver: Schema.String,\n\toperation: Schema.String,\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nconst rawCause = Symbol(\"@codework/sandbox/provider/error/raw/cause\");\nconst missingResource = Symbol(\"@codework/sandbox/provider/error/missing/resource\");\n\nexport const providerErrorCause = (error: SandboxProviderError): unknown =>\n\t(error as SandboxProviderError & { readonly [rawCause]?: unknown })[rawCause];\n\nexport const providerErrorIsNotFound = (error: SandboxProviderError): boolean =>\n\t(error as SandboxProviderError & { readonly [missingResource]?: boolean })[missingResource] === true;\n\nexport type Redactor = (value: string) => string;\n\nconst REDACTED = \"<redacted>\";\n\n/**\n * Conservative text redaction shared by every driver sanitizer.\n *\n * Disclaimer: This can really leak. Its never safe\n *\n * Configured secrets are removed exactly. Common authorization/header and URL\n * query shapes are masked as a second line of defence for values the caller did\n * not explicitly seed.\n *\n * Note: add support for diff regex as needed.\n */\nexport const makeRedactor = (secrets: Iterable<string> = []): Redactor => {\n\tconst configured = [...secrets].filter((secret) => secret.length > 0).sort((a, b) => b.length - a.length);\n\treturn (value) => {\n\t\tlet redacted = value;\n\t\tfor (const secret of configured) redacted = redacted.replaceAll(secret, REDACTED);\n\t\treturn redacted\n\t\t\t.replace(/\\b(authorization\\s*:\\s*(?:bearer|basic)\\s+)[^\\s,;]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b((?:api[-_]?key|token|secret|password)\\s*[=:]\\s*)[^\\s,;&]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/([?&](?:access_token|api_key|token|secret|password)=)[^&#\\s]+/gi, `$1${REDACTED}`)\n\t\t\t.replace(/\\b(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\\b/g, REDACTED);\n\t};\n};\n\nconst errorCode = (cause: unknown): string | undefined => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"code\" in cause)) return undefined;\n\tconst code = cause.code;\n\treturn typeof code === \"string\" || typeof code === \"number\" ? String(code) : undefined;\n};\n\nconst errorName = (cause: unknown): string => {\n\tif (typeof cause !== \"object\" || cause === null || !(\"name\" in cause) || typeof cause.name !== \"string\")\n\t\treturn \"Error\";\n\treturn cause.name;\n};\n\nconst errorMessage = (cause: unknown): string => {\n\tif (typeof cause === \"object\" && cause !== null && \"message\" in cause && typeof cause.message === \"string\")\n\t\treturn cause.message;\n\treturn String(cause);\n};\n\nexport const sanitizeError = (cause: unknown, redact: Redactor = makeRedactor()): SandboxInstance.PersistedError => {\n\tconst code = errorCode(cause);\n\treturn {\n\t\tname: redact(errorName(cause)),\n\t\tmessage: redact(errorMessage(cause)),\n\t\t...(code === undefined ? {} : { code: redact(code) }),\n\t};\n};\n\nexport const providerError = (input: {\n\treadonly driver: string;\n\treadonly operation: string;\n\treadonly cause: unknown;\n\treadonly redact?: Redactor;\n\treadonly notFound?: boolean;\n}): SandboxProviderError => {\n\tconst error = new SandboxProviderError({\n\t\tdriver: input.driver,\n\t\toperation: input.operation,\n\t\tsanitized: sanitizeError(input.cause, input.redact),\n\t});\n\tObject.defineProperty(error, rawCause, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.cause,\n\t\twritable: false,\n\t});\n\tObject.defineProperty(error, missingResource, {\n\t\tconfigurable: false,\n\t\tenumerable: false,\n\t\tvalue: input.notFound === true,\n\t\twritable: false,\n\t});\n\treturn error;\n};\n\nexport type SandboxMountError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxRemovedError\n\t| SandboxProviderError;\n\nexport type SandboxCreateError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxProviderError;\n\nexport type SandboxRegisterError =\n\t| SandboxDriverNotRegisteredError\n\t| SandboxDriverRegistrationError\n\t| SandboxProviderError;\n\nexport type SandboxReadError = never;\n\nexport type SandboxRefreshError =\n\t| SandboxNotFoundError\n\t| SandboxDriverNotRegisteredError\n\t| SandboxUnavailError\n\t| SandboxUnsupportedError\n\t| SandboxProviderError;\n\nexport type SandboxWakeError = SandboxRefreshError | SandboxRemovedError;\n\nexport type SandboxStopError = SandboxWakeError | SandboxBusyError | SandboxTransitionConflictError;\n\nexport type SandboxDestroyError = SandboxStopError | SandboxMustBeStoppedError;\n\nexport * as SandboxError from \"./errors.ts\";\n","import { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport {\n\tSandboxDriverNotRegisteredError,\n\tSandboxDriverRegistrationError,\n\ttype SandboxProviderError,\n} from \"./errors.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\n\n/** Open driver identity. Adding a driver never extends a union in core. */\nexport const Name = Schema.String.check(Schema.isNonEmpty()).pipe(Schema.brand(\"SandboxDriver.Name\"));\nexport type Name = typeof Name.Type;\n\n/** A path whose coordinate system is the mounted namespace. */\nexport const AbsolutePath = Schema.String.check(Schema.isStartsWith(\"/\")).pipe(\n\tSchema.brand(\"SandboxDriver.AbsolutePath\"),\n);\nexport type AbsolutePath = typeof AbsolutePath.Type;\n\nexport const RuntimeConfigBase = Schema.Struct({\n\tdefaultCwd: AbsolutePath,\n});\nexport interface RuntimeConfigBase extends Schema.Schema.Type<typeof RuntimeConfigBase> {}\n\nexport interface Capabilities {\n\treadonly reattach: boolean;\n\treadonly wake: boolean;\n\treadonly stop: boolean;\n\treadonly destroy: boolean;\n\treadonly cancels: boolean;\n}\n\nexport interface Observed {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus?: string | undefined;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface Provisioned<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly providerResourceId?: string | undefined;\n\treadonly providerStatus?: string | undefined;\n\treadonly runtimeConfig: RuntimeConfig;\n\treadonly metadata?: Readonly<Record<string, string>> | undefined;\n}\n\nexport interface RuntimeInput<RuntimeConfig extends RuntimeConfigBase> {\n\treadonly id: SandboxInstance.ID;\n\treadonly providerResourceId: Option.Option<string>;\n\treadonly runtimeConfig: RuntimeConfig;\n}\n\nexport interface Driver<CreateConfig, RuntimeConfig extends RuntimeConfigBase> {\n\treadonly name: Name;\n\treadonly kind: SandboxInstance.Kind;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<CreateConfig, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfig, unknown>;\n\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: CreateConfig;\n\t}) => Effect.Effect<Provisioned<RuntimeConfig>, SandboxProviderError>;\n\n\treadonly runtimeConfigFor: (input: {\n\t\treadonly providerResourceId: string;\n\t\treadonly overrides?: Partial<RuntimeConfig> | undefined;\n\t}) => Effect.Effect<RuntimeConfig, SandboxProviderError>;\n\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfig>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfig>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nexport type Definition<CreateConfig, RuntimeConfig extends RuntimeConfigBase> = Pick<\n\tDriver<CreateConfig, RuntimeConfig>,\n\t\"name\" | \"createConfigCodec\" | \"runtimeConfigCodec\"\n>;\n\n/**\n * The registry's type-erased shape. Erasure happens once at registration;\n * untrusted values still cross the registered driver's codecs before reaching\n * its typed implementation.\n */\nexport interface Registered {\n\treadonly name: Name;\n\treadonly kind: SandboxInstance.Kind;\n\treadonly capabilities: Capabilities;\n\treadonly createConfigCodec: Schema.Codec<unknown, unknown>;\n\treadonly runtimeConfigCodec: Schema.Codec<RuntimeConfigBase, unknown>;\n\treadonly create: (input: {\n\t\treadonly instanceId: SandboxInstance.ID;\n\t\treadonly config: unknown;\n\t}) => Effect.Effect<Provisioned<RuntimeConfigBase>, SandboxProviderError>;\n\treadonly runtimeConfigFor: (input: {\n\t\treadonly providerResourceId: string;\n\t\treadonly overrides?: Readonly<Record<string, unknown>> | undefined;\n\t}) => Effect.Effect<RuntimeConfigBase, SandboxProviderError>;\n\treadonly attach: (\n\t\tinput: RuntimeInput<RuntimeConfigBase>,\n\t) => Layer.Layer<SandboxIO.FileSystem | SandboxIO.Shell, SandboxProviderError>;\n\treadonly inspect?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly wake?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly stop?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<Observed, SandboxProviderError>;\n\treadonly destroy?: (input: RuntimeInput<RuntimeConfigBase>) => Effect.Effect<void, SandboxProviderError>;\n}\n\nconst erase = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tdriver: Driver<CreateConfig, RuntimeConfig>,\n): Registered => ({\n\tname: driver.name,\n\tkind: driver.kind,\n\tcapabilities: driver.capabilities,\n\tcreateConfigCodec: driver.createConfigCodec as Schema.Codec<unknown, unknown>,\n\truntimeConfigCodec: driver.runtimeConfigCodec as Schema.Codec<RuntimeConfigBase, unknown>,\n\tcreate: (input) => driver.create({ instanceId: input.instanceId, config: input.config as CreateConfig }),\n\truntimeConfigFor: (input) =>\n\t\tdriver.runtimeConfigFor({\n\t\t\tproviderResourceId: input.providerResourceId,\n\t\t\t...(input.overrides === undefined ? {} : { overrides: input.overrides as Partial<RuntimeConfig> }),\n\t\t}),\n\tattach: (input) => driver.attach(input as RuntimeInput<RuntimeConfig>),\n\t...(driver.inspect === undefined\n\t\t? {}\n\t\t: { inspect: (input: RuntimeInput<RuntimeConfigBase>) => driver.inspect!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.wake === undefined\n\t\t? {}\n\t\t: { wake: (input: RuntimeInput<RuntimeConfigBase>) => driver.wake!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.stop === undefined\n\t\t? {}\n\t\t: { stop: (input: RuntimeInput<RuntimeConfigBase>) => driver.stop!(input as RuntimeInput<RuntimeConfig>) }),\n\t...(driver.destroy === undefined\n\t\t? {}\n\t\t: { destroy: (input: RuntimeInput<RuntimeConfigBase>) => driver.destroy!(input as RuntimeInput<RuntimeConfig>) }),\n});\n\nexport interface RegistryService {\n\treadonly names: ReadonlySet<Name>;\n\treadonly find: (name: Name) => Option.Option<Registered>;\n\treadonly get: (name: Name) => Effect.Effect<Registered, SandboxDriverNotRegisteredError>;\n\treadonly decodeCreateConfig: (\n\t\tname: Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n\treadonly decodeRuntimeConfig: (\n\t\tname: Name,\n\t\tinput: unknown,\n\t) => Effect.Effect<RuntimeConfigBase, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n\treadonly encodeRuntimeConfig: (\n\t\tname: Name,\n\t\tinput: RuntimeConfigBase,\n\t) => Effect.Effect<unknown, SandboxDriverNotRegisteredError | SandboxDriverRegistrationError>;\n}\n\nexport class Registry extends Context.Service<Registry, RegistryService>()(\n\t\"@codeworksh/harness/sandbox/driver/Registry\",\n) {}\n\nconst codecFailure = (driver: Name, reason: unknown) =>\n\tnew SandboxDriverRegistrationError({ driver, reason: String(reason) });\n\nexport interface Registration {\n\treadonly registered: Registered;\n}\n\n/**\n * Creates in-memory driver registry map and throws for invalid state operations.\n * Exposes registry services methods to work with.\n */\nexport const makeRegistry = (\n\tdrivers: ReadonlyArray<Registration>,\n): Effect.Effect<RegistryService, SandboxDriverRegistrationError> =>\n\tEffect.gen(function* () {\n\t\tconst entries = new Map<Name, Registered>();\n\t\tfor (const registration of drivers) {\n\t\t\tconst driver = registration.registered;\n\t\t\tif (entries.has(driver.name)) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.name,\n\t\t\t\t\treason: \"duplicate driver registration\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (driver.capabilities.destroy && !driver.capabilities.stop) {\n\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\tdriver: driver.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 [\"wake\", \"stop\", \"destroy\"] as const) {\n\t\t\t\tif (driver.capabilities[operation] !== (driver[operation] !== undefined)) {\n\t\t\t\t\treturn yield* new SandboxDriverRegistrationError({\n\t\t\t\t\t\tdriver: driver.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\tentries.set(driver.name, erase(driver));\n\t\t}\n\n\t\t// `find` safely returns undefined if nothing\n\t\t// `get` throws\n\t\tconst find = (name: Name) => Option.fromUndefinedOr(entries.get(name));\n\t\tconst get = (name: Name) =>\n\t\t\tEffect.fromOption(find(name)).pipe(\n\t\t\t\tEffect.mapError(() => new SandboxDriverNotRegisteredError({ driver: name })),\n\t\t\t);\n\n\t\tconst decodeCreateConfig = Effect.fn(\"SandboxDriver.Registry.decodeCreateConfig\")(function* (\n\t\t\tname: Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(driver.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: Name,\n\t\t\tinput: unknown,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.decodeUnknownEffect(driver.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: Name,\n\t\t\tinput: RuntimeConfigBase,\n\t\t) {\n\t\t\tconst driver = yield* get(name);\n\t\t\treturn yield* Schema.encodeUnknownEffect(driver.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\tfind,\n\t\t\tget,\n\t\t\tdecodeCreateConfig,\n\t\t\tdecodeRuntimeConfig,\n\t\t\tencodeRuntimeConfig,\n\t\t});\n\t});\n\n/**\n * Register a static set of drivers for one process-lifetime control plane.\n *\n * `driver()` preserves the concrete driver at its definition site; this layer\n * is the only erasure boundary.\n */\nexport const layer = (...drivers: ReadonlyArray<Registration>) => Layer.effect(Registry, makeRegistry(drivers));\n\nexport const driver = <CreateConfig, RuntimeConfig extends RuntimeConfigBase>(\n\tvalue: Driver<CreateConfig, RuntimeConfig>,\n): Driver<CreateConfig, RuntimeConfig> & Registration =>\n\tObject.assign(value, {\n\t\tregistered: erase(value),\n\t});\n\nexport * as SandboxDriver from \"./driver.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 \"../../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 { 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 { 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","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, 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 {\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 { Local } from \"./fs/vfs.ts\";\nimport { HostExe } from \"./shell/host.ts\";\nimport { SandboxInstance } from \"./instance.ts\";\nimport { SandboxIO } from \"./io.ts\";\nimport { EnvNodeJSDefault } from \"./fs/nodejs.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* SandboxDriver.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\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 \"../../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 \"../../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 CreateConfig {\n\treadonly defaultCwd: SandboxDriver.AbsolutePath;\n\treadonly initializeCwd?: SandboxDriver.AbsolutePath | undefined;\n}\n\nexport interface RuntimeConfig extends SandboxDriver.RuntimeConfigBase {}\n\nexport const CreateConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n});\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\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\tEnvInMemory.make({ cwd: config.initializeCwd ?? config.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: config.defaultCwd },\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t),\n\t\truntimeConfigFor: ({ providerResourceId }) =>\n\t\t\tEffect.fail(\n\t\t\t\tproviderError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation: \"runtimeConfigFor\",\n\t\t\t\t\tcause: new Error(`memory resources cannot be reattached: ${providerResourceId}`),\n\t\t\t\t\tnotFound: true,\n\t\t\t\t}),\n\t\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 \"../../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 CreateConfig {\n\treadonly defaultCwd: SandboxDriver.AbsolutePath;\n\treadonly initializeCwd?: SandboxDriver.AbsolutePath | undefined;\n\treadonly location?: string | undefined;\n}\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: SandboxDriver.AbsolutePath,\n\tinitializeCwd: Schema.optional(SandboxDriver.AbsolutePath),\n\tlocation: Schema.optional(Schema.String),\n});\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\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 location = config.location === undefined ? undefined : posix.resolve(config.location);\n\t\t\treturn EnvSqldb.make(location, { cwd: config.initializeCwd ?? config.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: config.defaultCwd,\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 { posix } from \"../../posix.ts\";\nimport { SandboxFileSystem } from \"./filesystem.ts\";\n\n// The provider contract and FileStat live in `filesystem.ts` (the single source of truth, VFS-free).\n// A remote provider implements this Interface; `make` wraps\n// it into the same runtime surface the local vfs backend exposes.\nexport type FileStat = SandboxFileSystem.FileStat;\n\n// Remote-aware callers can opt into metadata that is not part of the generic\n// SandboxFileSystem surface. In particular, `stat` keeps the familiar\n// provider-level meaning, while `lstat` explicitly asks for the directory entry\n// itself so symlink identity is not inferred from a method with mixed provider\n// semantics.\nexport interface Interface extends SandboxFileSystem.Provider {\n\treadonly lstat?: (path: string) => Promise<FileStat>;\n}\n\nexport interface Options {\n\t/**\n\t * Optional remote working directory for relative paths. When omitted, relative\n\t * paths are passed through so the remote provider can use its own default cwd.\n\t */\n\treadonly cwd?: string;\n}\n\nconst resolvePath = (path: string, options?: Options) => {\n\tconst normalized = posix.normalize(path);\n\tif (options?.cwd === undefined || posix.isAbsolute(normalized)) return normalized;\n\treturn posix.normalize(posix.join(options.cwd, normalized));\n};\n\n/**\n * Wrap a remote provider into the runtime filesystem surface: resolve relative\n * paths against `cwd`, and nothing else. Parent creation and `rm` option\n * validation are the runtime's job and live in `SandboxFileSystem.fromProvider`,\n * which every backend passes through — putting them here would cover only the\n * backends that happen to use this wrapper.\n */\nexport const make = (provider: Interface, options?: Options): Interface => {\n\tconst resolve = (path: string) => resolvePath(path, options);\n\n\treturn {\n\t\treadFile: (path) => provider.readFile(resolve(path)),\n\t\treadFileBuffer: (path) => provider.readFileBuffer(resolve(path)),\n\t\twriteFile: (path, content) => provider.writeFile(resolve(path), content),\n\t\tstat: (path) => provider.stat(resolve(path)),\n\t\t...(provider.lstat === undefined ? {} : { lstat: (path: string) => provider.lstat!(resolve(path)) }),\n\t\treaddir: (path) => provider.readdir(resolve(path)),\n\t\texists: (path) => provider.exists(resolve(path)),\n\t\tmkdir: (path, mkdirOptions) => provider.mkdir(resolve(path), mkdirOptions),\n\t\t// option validation happens in `fromProvider`, before any mutation\n\t\trm: (path, rmOptions) => provider.rm(resolve(path), rmOptions),\n\t};\n};\n\nexport const withProvider = make;\n\nexport * as RemoteFileSystem from \"./remote.ts\";\n","import { Context } from \"effect\";\n\n/**\n * The driver's own locator for the attached resource — a Vercel sandbox name, a\n * Daytona sandbox id.\n *\n * Deliberately *not* on `SandboxIO.Current`: consumers never parse one,\n * and keeps it separate from the application id precisely so a driver's format can\n * change without touching identity.\n *\n * It exists for the control plane, which records it as `provider_resource_id`,\n * and for tests that reattach to the same resource.\n *\n * One tag for every driver rather than one per driver. A mount has exactly one\n * driver, so there is nothing to disambiguate, and the control plane has to read\n * the locator without knowing which driver produced it — keeps the\n * driver name open, so anything keyed on a closed `\"vercel\" | \"daytona\"` set is\n * a bug waiting for the third driver.\n */\nexport class Service extends Context.Service<Service, { readonly providerResourceId: string }>()(\n\t\"@codeworksh/harness/sandbox/resource/Service\",\n) {}\n\nexport * as SandboxResource from \"./resource.ts\";\n","/* oxlint-disable effecttsgo/async-function -- Daytona's SDK boundary is Promise-based. */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { posix } from \"../../posix.ts\";\nimport { sanitizeError } from \"../errors.ts\";\nimport { SandboxFileSystem } from \"../fs/filesystem.ts\";\nimport { RemoteFileSystem } from \"../fs/remote.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { SandboxIO } from \"../io.ts\";\nimport { SandboxResource } from \"../resource.ts\";\nimport { type ISandboxExe, quote, quoteArgv, resolveCwd, Shell, ShellError } from \"../shell/shell.ts\";\n\ntype CodeLanguage = import(\"@daytona/sdk\").CodeLanguage;\ntype Daytona = import(\"@daytona/sdk\").Daytona;\ntype FileInfo = import(\"@daytona/sdk\").FileInfo;\ntype Image = import(\"@daytona/sdk\").Image;\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\n/** Fallback when Daytona cannot report a snapshot/image-specific work directory. */\nexport const DEFAULT_CWD = \"/home/daytona\";\n\n/**\n * The mount cwd for a Daytona namespace.\n *\n * An absolute override replaces the namespace default outright, so the\n * `getWorkDir()` round-trip is skipped: it would discover a value we then throw\n * away. Otherwise the sandbox's own work directory is the default, and\n * {@link DEFAULT_CWD} covers a snapshot or image that reports none.\n *\n * Taken as a thunk rather than read off the sandbox so all three branches are\n * testable without provisioning one — this decides where every Daytona mount\n * roots, and §8.1 makes a wrong answer here resolve silently rather than fail.\n */\nexport const mountCwd = async (\n\tcwd: string | undefined,\n\tgetWorkDir: () => Promise<string | undefined>,\n): Promise<string> => {\n\tconst defaultCwd = posix.isAbsolute(cwd ?? \"\") ? DEFAULT_CWD : ((await getWorkDir()) ?? DEFAULT_CWD);\n\treturn SandboxIO.resolveMountCwd(defaultCwd, cwd);\n};\n\nexport class DaytonaError extends Schema.TaggedError<DaytonaError>()(\"DaytonaError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\nexport interface Options {\n\t/** API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n\treadonly apiKey?: string | undefined;\n\t/** API URL. Falls back to `DAYTONA_API_URL` / the SDK default. */\n\treadonly apiUrl?: string | undefined;\n\t/** Target region. Falls back to `DAYTONA_TARGET` / the SDK default. */\n\treadonly target?: string | undefined;\n\t/** Reuse an existing sandbox by id or name instead of creating one. */\n\treadonly sandboxId?: string | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Image (registry reference or declarative `Image`) to create the sandbox from. */\n\treadonly image?: string | Image | undefined;\n\t/** Runtime used for code execution. Defaults to `\"typescript\"`. */\n\treadonly language?: CodeLanguage | string | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** Resource allocation (cpu / memory / disk). */\n\treadonly resources?: Resources | undefined;\n\t/** OS user to run as inside the sandbox. */\n\treadonly user?: string | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `getWorkDir()`;\n\t * omitted values use it, with `/home/daytona` as the provider fallback.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Idle minutes before the sandbox auto-stops. */\n\treadonly autoStopInterval?: number | undefined;\n\t/** Per-command timeout in seconds. 0 means no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n\treadonly cwd: string;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandbox/providers/daytona/Remote\") {}\n\nconst assertCommandSucceeded = (command: string, result: { exitCode: number; result?: string }) => {\n\tif (result.exitCode !== 0) throw new Error(result.result || `command failed (${result.exitCode}): ${command}`);\n};\n\nconst dateFrom = (value: string | undefined) => {\n\tif (value === undefined) return undefined;\n\treturn Option.getOrUndefined(DateTime.make(value).pipe(Option.map(DateTime.toDateUtc)));\n};\n\nexport const createSandbox = (daytona: Daytona, options: Options) => {\n\tconst base = {\n\t\tlanguage: options.language ?? \"typescript\",\n\t\t...(options.envVars === undefined ? {} : { envVars: options.envVars }),\n\t\t...(options.user === undefined ? {} : { user: options.user }),\n\t\t...(options.autoStopInterval === undefined ? {} : { autoStopInterval: options.autoStopInterval }),\n\t\tautoDeleteInterval: -1,\n\t};\n\treturn options.image !== undefined\n\t\t? daytona.create({\n\t\t\t\t...base,\n\t\t\t\timage: options.image,\n\t\t\t\t...(options.resources === undefined ? {} : { resources: options.resources }),\n\t\t\t})\n\t\t: daytona.create({ ...base, ...(options.snapshot === undefined ? {} : { snapshot: options.snapshot }) });\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Daytona } = await import(\"@daytona/sdk\");\n\t\t\t\tconst daytona = new Daytona({\n\t\t\t\t\t...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),\n\t\t\t\t\t...(options.apiUrl === undefined ? {} : { apiUrl: options.apiUrl }),\n\t\t\t\t\t...(options.target === undefined ? {} : { target: options.target }),\n\t\t\t\t});\n\t\t\t\tconst sandbox = options.sandboxId\n\t\t\t\t\t? await daytona.get(options.sandboxId)\n\t\t\t\t\t: await createSandbox(daytona, options);\n\t\t\t\treturn {\n\t\t\t\t\tsandbox,\n\t\t\t\t\tcwd: await mountCwd(options.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t};\n\t\t\t},\n\t\t\tcatch: (cause) => new DaytonaError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\nexport const statsFrom = (info: FileInfo): RemoteFileSystem.FileStat => {\n\tconst symlink = info.mode === undefined ? undefined : info.mode.startsWith(\"l\");\n\tconst mtime = dateFrom(info.modifiedAt ?? info.modTime);\n\n\t// omit size/mtime/isSymbolicLink the toolbox did not report — never fabricate\n\treturn {\n\t\tisFile: !info.isDir && symlink !== true,\n\t\tisDirectory: info.isDir,\n\t\t...(symlink === undefined ? {} : { isSymbolicLink: symlink }),\n\t\t...(info.size === undefined ? {} : { size: info.size }),\n\t\t...(mtime === undefined ? {} : { mtime }),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\"\n>;\n\nconst providerFrom = (sandbox: RemoteSandbox, options: Options) => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: async (path: string) => (await sandbox.fs.downloadFile(path)).toString(\"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.downloadFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.uploadFile(typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content), path),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.getFileDetails(path)),\n\t\t// The toolbox file-details endpoint follows symlinks. Detect the entry\n\t\t// with the sandbox shell first so lstat never reports target metadata as\n\t\t// if it described the link itself.\n\t\tlstat: async (path: string) => {\n\t\t\tconst command = `test -L ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tif (result.exitCode === 0) {\n\t\t\t\treturn { isFile: false, isDirectory: false, isSymbolicLink: true };\n\t\t\t}\n\t\t\tif (result.exitCode === 1) return statsFrom(await sandbox.fs.getFileDetails(path));\n\t\t\tassertCommandSucceeded(command, result);\n\t\t\tthrow new Error(`unreachable lstat result for ${path}`);\n\t\t},\n\t\treaddir: async (path: string) => (await sandbox.fs.listFiles(path)).map((entry) => entry.name),\n\t\t// Only a genuine 404 means \"absent\". Auth, rate-limit, and transport\n\t\t// failures propagate: a caller that deletes records on absence must not\n\t\t// be told a path is gone because the API was briefly unreachable.\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.getFileDetails(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tconst { DaytonaNotFoundError } = await import(\"@daytona/sdk\");\n\t\t\t\tif (cause instanceof DaytonaNotFoundError) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tif (!mkdirOptions?.recursive) {\n\t\t\t\tawait sandbox.fs.createFolder(path, \"755\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst command = `mkdir -p ${quote(path)}`;\n\t\t\tconst result = await sandbox.process.executeCommand(command, options.cwd, undefined, options.execTimeout);\n\t\t\tassertCommandSucceeded(command, result);\n\t\t},\n\t\trm: async (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) => {\n\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.deleteFile(path, rmOptions?.recursive);\n\t\t\t} catch (cause) {\n\t\t\t\tif (rmOptions?.force && !(await filesystem.exists(path))) return;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t};\n\n\treturn filesystem;\n};\n\n// Daytona's execute API folds stderr into `result` and reports a single exit\n// code, so the shell surfaces the combined output as stdout and leaves stderr\n// empty rather than inventing a split.\nconst runCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\topts?: { env?: Record<string, string>; cwd?: string },\n) =>\n\tEffect.tryPromise({\n\t\ttry: () =>\n\t\t\tsandbox.process.executeCommand(command, resolveCwd(options.cwd, opts?.cwd), opts?.env, options.execTimeout),\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t}).pipe(Effect.map((response) => ({ stdout: response.result ?? \"\", stderr: \"\", exitCode: response.exitCode })));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\trunCommand(sandbox, options, command, opts);\n\n// `executeCommand` takes a single string, so the vector is quoted here rather\n// than spawned; the per-call cwd rides the toolbox's own cwd argument instead\n// of a `cd` prefix.\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) =>\n\t\trunCommand(sandbox, options, quoteArgv(argv), opts);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn SandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, mounted), { cwd }));\n\t\t}),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox, cwd }) => {\n\t\t\tconst mounted = { ...options, cwd };\n\t\t\treturn Shell.of({ exec: exec(sandbox, mounted), execArgv: execArgv(sandbox, mounted) });\n\t\t}),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * Mount wrappers supply an absolute cwd to every public operation. Internal\n * filesystem helper commands already receive absolute paths, so the transport\n * itself keeps no mutable working-directory state and owns no resource\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox, options))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Daytona's locator is the sandbox id. See `SandboxResource` for why this is a\n// shared tag rather than a Daytona-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.id })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, ({ cwd }) =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"daytona\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Daytona sandbox provides the runtime filesystem service directly plus\n * the sandbox's native remote shell. It intentionally does not provide VFS:\n * remote filesystems have no synchronous filesystem surface.\n */\nexport const layer = (options: Options = {}): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, DaytonaError> =>\n\tLayer.mergeAll(filesystemLayer(options), shellLayer(options), identityLayer(options), resourceLayer).pipe(\n\t\tLayer.provide(remote(options)),\n\t);\n\nexport const services = layer;\n\nexport * as EnvDaytona from \"./daytona.ts\";\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { makeRedactor, providerError, type SandboxProviderError } from \"../errors.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { EnvDaytona } from \"../providers/daytona.ts\";\n\nexport interface ClientOptions {\n\treadonly apiKey?: string | undefined;\n\treadonly apiUrl?: string | undefined;\n\treadonly target?: string | undefined;\n}\n\nexport const ResourcesConfig = Schema.Struct({\n\tcpu: Schema.optional(Schema.Finite),\n\tgpu: Schema.optional(Schema.Finite),\n\tmemory: Schema.optional(Schema.Finite),\n\tdisk: Schema.optional(Schema.Finite),\n});\nexport type ResourcesConfig = typeof ResourcesConfig.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\timage: Schema.optional(Schema.String),\n\tlanguage: Schema.optional(Schema.String),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tresources: Schema.optional(ResourcesConfig),\n\tuser: Schema.optional(Schema.String),\n\tcwd: Schema.optional(Schema.String),\n\tautoStopInterval: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\tuser: Schema.optional(Schema.String),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"daytona\");\ntype DaytonaSdk = typeof import(\"@daytona/sdk\");\ntype RemoteSandbox = import(\"@daytona/sdk\").Sandbox;\ntype Resources = import(\"@daytona/sdk\").Resources;\n\nconst statusFrom = (\n\tstate: RemoteSandbox[\"state\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => {\n\tconst providerStatus = state ?? \"unknown\";\n\treturn {\n\t\tstatus:\n\t\t\tstate === \"stopped\" || state === \"archived\"\n\t\t\t\t? \"offline\"\n\t\t\t\t: state === \"stopping\" || state === \"archiving\" || state === \"snapshotting\" || state === \"destroying\"\n\t\t\t\t\t? \"suspending\"\n\t\t\t\t\t: state === \"destroyed\"\n\t\t\t\t\t\t? \"unavail\"\n\t\t\t\t\t\t: state === \"error\" || state === \"build_failed\" || state === \"unknown\"\n\t\t\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t\t\t: \"online\",\n\t\tproviderStatus,\n\t};\n};\n\nconst shouldWake = (sandbox: RemoteSandbox): boolean => sandbox.state === \"stopped\" || sandbox.state === \"archived\";\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst redact = makeRedactor([client.apiKey ?? \"\"]);\n\tconst daytona = (sdk: DaytonaSdk) =>\n\t\tnew sdk.Daytona({\n\t\t\t...(client.apiKey === undefined ? {} : { apiKey: client.apiKey }),\n\t\t\t...(client.apiUrl === undefined ? {} : { apiUrl: client.apiUrl }),\n\t\t\t...(client.target === undefined ? {} : { target: client.target }),\n\t\t});\n\n\tconst attempt = <A>(\n\t\toperation: string,\n\t\trun: (sdk: DaytonaSdk) => Promise<A>,\n\t): Effect.Effect<A, SandboxProviderError> =>\n\t\tEffect.suspend(() => {\n\t\t\tlet sdk: DaytonaSdk | undefined;\n\t\t\treturn Effect.tryPromise({\n\t\t\t\ttry: () =>\n\t\t\t\t\timport(\"@daytona/sdk\").then((loaded) => {\n\t\t\t\t\t\tsdk = loaded;\n\t\t\t\t\t\treturn run(loaded);\n\t\t\t\t\t}),\n\t\t\t\tcatch: (cause) =>\n\t\t\t\t\tproviderError({\n\t\t\t\t\t\tdriver: name,\n\t\t\t\t\t\toperation,\n\t\t\t\t\t\tcause,\n\t\t\t\t\t\tredact,\n\t\t\t\t\t\tnotFound: sdk !== undefined && cause instanceof sdk.DaytonaNotFoundError,\n\t\t\t\t\t}),\n\t\t\t});\n\t\t});\n\n\tconst get = (providerResourceId: string, operation: string) =>\n\t\tattempt(operation, (sdk) => daytona(sdk).get(providerResourceId));\n\n\tconst refresh = (sandbox: RemoteSandbox, operation: string) =>\n\t\tattempt(operation, () => sandbox.refreshData()).pipe(Effect.as(sandbox));\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.state),\n\t\tmetadata: {\n\t\t\ttarget: sandbox.target,\n\t\t},\n\t});\n\n\tconst wake = (sandbox: RemoteSandbox, operation: string) =>\n\t\tshouldWake(sandbox)\n\t\t\t? attempt(operation, () => sandbox.start()).pipe(Effect.map(() => sandbox))\n\t\t\t: Effect.succeed(sandbox);\n\n\tconst runtime = (\n\t\tdefaultCwd: string,\n\t\tinput: { readonly user?: string | undefined; readonly execTimeout?: number | undefined },\n\t) => ({\n\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(defaultCwd),\n\t\t...(input.user === undefined ? {} : { user: input.user }),\n\t\t...(input.execTimeout === undefined ? {} : { execTimeout: input.execTimeout }),\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\t// Installed SDK 0.187.0 has no cancellation signal on\n\t\t\t// executeCommand; session execution cannot carry cwd/env safely.\n\t\t\tcancels: false,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst base = {\n\t\t\t\t\tlanguage: config.language ?? \"typescript\",\n\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t...(config.user === undefined ? {} : { user: config.user }),\n\t\t\t\t\t...(config.autoStopInterval === undefined ? {} : { autoStopInterval: config.autoStopInterval }),\n\t\t\t\t\tautoDeleteInterval: -1,\n\t\t\t\t\tlabels: {\n\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst sandbox = yield* attempt(\"create\", (loaded) => {\n\t\t\t\t\tconst sdk = daytona(loaded);\n\t\t\t\t\treturn config.image === undefined\n\t\t\t\t\t\t? sdk.create({ ...base, ...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }) })\n\t\t\t\t\t\t: sdk.create({\n\t\t\t\t\t\t\t\t...base,\n\t\t\t\t\t\t\t\timage: config.image,\n\t\t\t\t\t\t\t\t...(config.resources === undefined ? {} : { resources: config.resources as Resources }),\n\t\t\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tconst defaultCwd = yield* attempt(\"create.cwd\", () =>\n\t\t\t\t\tEnvDaytona.mountCwd(config.cwd, () => sandbox.getWorkDir()),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.state);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.id,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: runtime(defaultCwd, config),\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\ttarget: sandbox.target,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst sandbox = yield* get(providerResourceId, \"runtimeConfigFor\");\n\t\t\t\tconst defaultCwd =\n\t\t\t\t\toverrides?.defaultCwd ??\n\t\t\t\t\tSandboxDriver.AbsolutePath.make(\n\t\t\t\t\t\tyield* attempt(\"runtimeConfigFor.cwd\", () =>\n\t\t\t\t\t\t\tEnvDaytona.mountCwd(undefined, () => sandbox.getWorkDir()),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tdefaultCwd,\n\t\t\t\t\t...(overrides?.user === undefined ? { user: sandbox.user } : { user: overrides.user }),\n\t\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t\t};\n\t\t\t}),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tconst sandbox = yield* get(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t);\n\t\t\t\t\tyield* wake(sandbox, \"attach.wake\");\n\t\t\t\t\treturn EnvDaytona.transport(\n\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(refresh(sandbox, \"inspect.refresh\"), observed),\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => Effect.map(wake(sandbox, \"wake.start\"), observed),\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nexport * as DaytonaSandboxDriver from \"./daytona.ts\";\n","/* oxlint-disable effecttsgo/async-function -- Vercel's sandbox SDK boundary is Promise-based. */\nimport { Context, Effect, Layer, Schema, Stream } from \"effect\";\nimport { Buffer } from \"node:buffer\";\nimport { sanitizeError } from \"../errors.ts\";\nimport { SandboxFileSystem } from \"../fs/filesystem.ts\";\nimport { RemoteFileSystem } from \"../fs/remote.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { SandboxIO } from \"../io.ts\";\nimport { SandboxResource } from \"../resource.ts\";\nimport {\n\ttype ExecChunk,\n\ttype ExecResult,\n\ttype ISandboxExe,\n\tquoteArgv,\n\tresolveCwd,\n\tShell,\n\tShellError,\n} from \"../shell/shell.ts\";\n\nconst utf8 = new TextEncoder();\ntype Command = import(\"@vercel/sandbox\").Command;\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\n/** Vercel's namespace-intrinsic working directory. */\nexport const DEFAULT_CWD = \"/vercel/sandbox\";\n\nexport class VercelError extends Schema.TaggedError<VercelError>()(\"VercelError\", {\n\tsanitized: SandboxInstance.PersistedError,\n}) {}\n\n/**\n * Vercel API credentials. Either all three are provided together or none are:\n * when omitted, the SDK resolves them from the `VERCEL_OIDC_TOKEN` env var\n * (the token's payload carries the project and team ids).\n */\nexport interface Credentials {\n\treadonly token: string;\n\treadonly teamId: string;\n\treadonly projectId: string;\n}\n\nexport interface Options {\n\t/** Auth token (OIDC or access token). Falls back to `VERCEL_OIDC_TOKEN`. */\n\treadonly token?: string | undefined;\n\t/** Team id. Derived from the OIDC token when omitted. */\n\treadonly teamId?: string | undefined;\n\t/** Project id. Derived from the OIDC token when omitted. */\n\treadonly projectId?: string | undefined;\n\t/** Reuse an existing sandbox by name instead of creating one. */\n\treadonly sandboxName?: string | undefined;\n\t/** Explicit name for a newly created sandbox. */\n\treadonly name?: string | undefined;\n\t/** Provider-side diagnostic labels (maximum five). */\n\treadonly tags?: Record<string, string> | undefined;\n\t/** Durable instance identity for this namespace. Supplied by the Controller. */\n\treadonly instanceId?: SandboxInstance.ID | undefined;\n\t/** Snapshot id to create the sandbox from. */\n\treadonly snapshot?: string | undefined;\n\t/** Source to seed the sandbox filesystem from (git or tarball). */\n\treadonly source?:\n\t\t| {\n\t\t\t\treadonly type: \"git\";\n\t\t\t\treadonly url: string;\n\t\t\t\treadonly revision?: string | undefined;\n\t\t\t\treadonly depth?: number | undefined;\n\t\t }\n\t\t| { readonly type: \"tarball\"; readonly url: string };\n\t/** Runtime used by the sandbox. Defaults to the SDK default (`node24`). */\n\treadonly runtime?: string | undefined;\n\t/** Ports to expose from the sandbox (max 4). */\n\treadonly ports?: number[] | undefined;\n\t/** Environment variables baked into the sandbox. */\n\treadonly envVars?: Record<string, string> | undefined;\n\t/** vCPU allocation (memory scales at 2048 MB per vCPU). */\n\treadonly vcpus?: number | undefined;\n\t/**\n\t * Mount working directory. Relative values resolve against `/vercel/sandbox`;\n\t * omitted values use that namespace default.\n\t */\n\treadonly cwd?: string | undefined;\n\t/** Milliseconds before the sandbox auto-terminates. */\n\treadonly timeout?: number | undefined;\n\t/** Per-command timeout in milliseconds. Omit for no timeout. */\n\treadonly execTimeout?: number | undefined;\n}\n\ninterface RemoteState {\n\treadonly sandbox: RemoteSandbox;\n}\n\nclass Remote extends Context.Service<Remote, RemoteState>()(\"@codeworksh/harness/sandbox/providers/vercel/Remote\") {}\n\n// Vercel requires all three credential fields together or none — partial\n// credentials are rejected by the SDK — so only forward them when complete.\nexport const credentialsFrom = (options: Options): Credentials | undefined =>\n\toptions.token !== undefined && options.teamId !== undefined && options.projectId !== undefined\n\t\t? { token: options.token, teamId: options.teamId, projectId: options.projectId }\n\t\t: undefined;\n\nexport const createSandbox = async (options: Options, creds: Credentials | undefined = credentialsFrom(options)) => {\n\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\tconst withCreds = <T extends object>(params: T) => (creds ? { ...params, ...creds } : params);\n\tconst source =\n\t\toptions.source?.type === \"git\"\n\t\t\t? {\n\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\turl: options.source.url,\n\t\t\t\t\t...(options.source.revision === undefined ? {} : { revision: options.source.revision }),\n\t\t\t\t\t...(options.source.depth === undefined ? {} : { depth: options.source.depth }),\n\t\t\t\t}\n\t\t\t: options.source;\n\tconst base = {\n\t\t...(options.name === undefined ? {} : { name: options.name }),\n\t\t...(options.tags === undefined ? {} : { tags: options.tags }),\n\t\t...(options.envVars === undefined ? {} : { env: options.envVars }),\n\t\t...(options.ports === undefined ? {} : { ports: options.ports }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.vcpus === undefined ? {} : { resources: { vcpus: options.vcpus } }),\n\t};\n\treturn options.snapshot !== undefined\n\t\t? Sandbox.create(withCreds({ ...base, source: { type: \"snapshot\" as const, snapshotId: options.snapshot } }))\n\t\t: Sandbox.create(\n\t\t\t\twithCreds({\n\t\t\t\t\t...base,\n\t\t\t\t\t...(options.runtime === undefined ? {} : { runtime: options.runtime }),\n\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t}),\n\t\t\t);\n};\n\nconst remote = (options: Options) =>\n\tLayer.effect(\n\t\tRemote,\n\t\tEffect.tryPromise({\n\t\t\ttry: async (): Promise<RemoteState> => {\n\t\t\t\tconst { Sandbox } = await import(\"@vercel/sandbox\");\n\t\t\t\tconst creds = credentialsFrom(options);\n\t\t\t\tconst sandbox = options.sandboxName\n\t\t\t\t\t? await Sandbox.get(creds ? { ...creds, name: options.sandboxName } : { name: options.sandboxName })\n\t\t\t\t\t: await createSandbox(options, creds);\n\t\t\t\treturn { sandbox };\n\t\t\t},\n\t\t\tcatch: (cause) => new VercelError({ sanitized: sanitizeError(cause) }),\n\t\t}),\n\t);\n\ninterface Stats {\n\treadonly size: number;\n\treadonly mtime: Date;\n\treadonly isFile: () => boolean;\n\treadonly isDirectory: () => boolean;\n\treadonly isSymbolicLink: () => boolean;\n}\n\nexport const statsFrom = (stats: Stats): RemoteFileSystem.FileStat => {\n\tconst mtime = stats.mtime;\n\n\t// omit size/mtime the stat could not report — never fabricate\n\treturn {\n\t\tisFile: stats.isFile(),\n\t\tisDirectory: stats.isDirectory(),\n\t\tisSymbolicLink: stats.isSymbolicLink(),\n\t\t...(Number.isFinite(stats.size) ? { size: stats.size } : {}),\n\t\t...(mtime instanceof Date && !Number.isNaN(mtime.getTime()) ? { mtime } : {}),\n\t};\n};\n\ntype RemoteFilesystemProvider = Pick<\n\tRemoteFileSystem.Interface,\n\t\"readFile\" | \"readFileBuffer\" | \"writeFile\" | \"stat\" | \"lstat\" | \"readdir\" | \"exists\" | \"mkdir\" | \"rm\"\n>;\n\n// The Vercel `fs` surface is `node:fs/promises`-compatible, so the provider\n// maps almost directly. The `RemoteFileSystem.make` wrapper resolves relative\n// paths against `cwd` and guarantees parent creation on `writeFile`.\nconst providerFrom = (sandbox: RemoteSandbox): RemoteFilesystemProvider => {\n\tconst filesystem: RemoteFilesystemProvider = {\n\t\treadFile: (path: string) => sandbox.fs.readFile(path, \"utf8\"),\n\t\treadFileBuffer: async (path: string) => new Uint8Array(await sandbox.fs.readFile(path)),\n\t\twriteFile: (path: string, content: string | Uint8Array) =>\n\t\t\tsandbox.fs.writeFile(path, typeof content === \"string\" ? Buffer.from(content, \"utf8\") : Buffer.from(content)),\n\t\tstat: async (path: string) => statsFrom(await sandbox.fs.stat(path)),\n\t\t// Keep symlink identity explicit: Vercel's `stat` follows symlinks\n\t\t// (`stat -L`), so remote-aware callers must ask for `lstat` when they\n\t\t// need the entry itself instead of the target's metadata.\n\t\tlstat: async (path: string) => statsFrom(await sandbox.fs.lstat(path)),\n\t\t// `withFileTypes` lists via `find`, which includes dotfiles (`.git` …);\n\t\t// the bare `readdir` shells out to `ls -1` and would drop them.\n\t\treaddir: async (path: string) => (await sandbox.fs.readdir(path, { withFileTypes: true })).map((e) => e.name),\n\t\texists: async (path: string) => {\n\t\t\ttry {\n\t\t\t\tawait sandbox.fs.stat(path);\n\t\t\t\treturn true;\n\t\t\t} catch (cause) {\n\t\t\t\tif (SandboxFileSystem.isNotFoundError(cause)) return false;\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t},\n\t\tmkdir: async (path: string, mkdirOptions?: { recursive?: boolean }) => {\n\t\t\tawait sandbox.fs.mkdir(\n\t\t\t\tpath,\n\t\t\t\tmkdirOptions?.recursive === undefined ? {} : { recursive: mkdirOptions.recursive },\n\t\t\t);\n\t\t},\n\t\t// `rm -f` is native, so force/recursive delegate straight through; the\n\t\t// wrapper has already rejected any unsupported option before we get here.\n\t\trm: (path: string, rmOptions?: { recursive?: boolean; force?: boolean }) =>\n\t\t\tsandbox.fs.rm(path, {\n\t\t\t\t...(rmOptions?.recursive === undefined ? {} : { recursive: rmOptions.recursive }),\n\t\t\t\t...(rmOptions?.force === undefined ? {} : { force: rmOptions.force }),\n\t\t\t}),\n\t};\n\n\treturn filesystem;\n};\n\n// Arbitrary command strings run through `sh -c` to match the single-string\n// contract the rest of the harness expects. Commands run **detached** so the\n// returned `Command` exposes `kill`/`logs`/`wait`: a `cwd`/`env` is threaded in,\n// and the per-command `execTimeout` is a server-side SIGKILL deadline.\nconst spawn = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => spawnArgv(sandbox, options, [\"sh\", \"-c\", command], env, cwd);\n\n// Vercel spawns a program with a real argument vector, so `execArgv` needs no\n// quoting at all — the args never pass through a shell.\nconst spawnArgv = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\targv: ReadonlyArray<string>,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n): Promise<Command> => {\n\tconst resolvedCwd = resolveCwd(options.cwd, cwd);\n\treturn sandbox.runCommand({\n\t\tcmd: argv[0]!,\n\t\targs: argv.slice(1),\n\t\t...(resolvedCwd === undefined ? {} : { cwd: resolvedCwd }),\n\t\t...(env === undefined ? {} : { env }),\n\t\tdetached: true,\n\t\t...(options.execTimeout === undefined ? {} : { timeoutMs: options.execTimeout }),\n\t});\n};\n\n// Acquire a detached command and register its kill as a scope finalizer, so an\n// interrupt / timeout from the consumer actually terminates the remote process\n// (best-effort SIGKILL) instead of leaving it running server-side.\n// `command` labels failures only; the spawn itself is supplied by the caller so\n// string and argv execution share one kill finalizer.\nconst acquireWith = (command: string, run: () => Promise<Command>) =>\n\tEffect.acquireRelease(Effect.tryPromise({ try: run, catch: (cause) => new ShellError({ command, cause }) }), (cmd) =>\n\t\tEffect.promise(() => cmd.kill(\"SIGKILL\").catch(() => {})),\n\t);\n\n// Vercel reports stdout and stderr separately with a distinct exit code, so the\n// shell surfaces both streams faithfully.\nconst collect = (command: string) => (cmd: Command) =>\n\tEffect.tryPromise({\n\t\ttry: async (): Promise<ExecResult> => {\n\t\t\tconst result = await cmd.wait();\n\t\t\tconst [stdout, stderr] = await Promise.all([result.stdout(), result.stderr()]);\n\t\t\treturn { stdout, stderr, exitCode: result.exitCode };\n\t\t},\n\t\tcatch: (cause) => new ShellError({ command, cause }),\n\t});\n\nconst acquireCommand = (\n\tsandbox: RemoteSandbox,\n\toptions: Options,\n\tcommand: string,\n\tenv?: Record<string, string>,\n\tcwd?: string,\n) => acquireWith(command, () => spawn(sandbox, options, command, env, cwd));\n\nconst exec =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"exec\"] =>\n\t(command, opts) =>\n\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\nconst execArgv =\n\t(sandbox: RemoteSandbox, options: Options): ISandboxExe[\"execArgv\"] =>\n\t(argv, opts) => {\n\t\t// quoted for the error label only — the spawn passes argv through untouched\n\t\tconst command = quoteArgv(argv);\n\t\treturn acquireWith(command, () => spawnArgv(sandbox, options, argv, opts?.env, opts?.cwd)).pipe(\n\t\t\tEffect.flatMap(collect(command)),\n\t\t\tEffect.scoped,\n\t\t);\n\t};\n\n// Streaming output via `Command.logs` (an async generator of stdout/stderr\n// entries), followed by the exit code from `wait`. The kill finalizer fires when\n// the consuming scope closes (interrupt / timeout).\nconst stream =\n\t(sandbox: RemoteSandbox, options: Options): NonNullable<ISandboxExe[\"stream\"]> =>\n\t(command, opts) =>\n\t\tStream.unwrap(\n\t\t\tacquireCommand(sandbox, options, command, opts?.env, opts?.cwd).pipe(\n\t\t\t\tEffect.map((cmd) => {\n\t\t\t\t\tconst logs = Stream.fromAsyncIterable(cmd.logs(), (cause) => new ShellError({ command, cause })).pipe(\n\t\t\t\t\t\tStream.map((log): ExecChunk => ({ _tag: log.stream, bytes: utf8.encode(log.data) })),\n\t\t\t\t\t);\n\t\t\t\t\tconst exit = Stream.fromEffect(\n\t\t\t\t\t\tEffect.tryPromise({ try: () => cmd.wait(), catch: (cause) => new ShellError({ command, cause }) }),\n\t\t\t\t\t).pipe(Stream.map((finished): ExecChunk => ({ _tag: \"exit\", exitCode: finished.exitCode })));\n\t\t\t\t\treturn Stream.concat(logs, exit);\n\t\t\t\t}),\n\t\t\t),\n\t\t);\n\nconst filesystemLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxFileSystem.Service,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tSandboxFileSystem.fromProvider(\n\t\t\t\tRemoteFileSystem.make(providerFrom(sandbox), options.cwd === undefined ? undefined : { cwd: options.cwd }),\n\t\t\t),\n\t\t),\n\t);\n\nconst shellLayer = (options: Options) =>\n\tLayer.effect(\n\t\tShell,\n\t\tEffect.map(Remote, ({ sandbox }) =>\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * Cwd-neutral IO attachment for a lifecycle driver.\n *\n * The controller binds a cwd per mount, so neither filesystem nor shell stores\n * one here. The returned layer owns no provider resource and has no deletion\n * finalizer.\n */\nexport const transport = (\n\tsandbox: RemoteSandbox,\n\toptions: Pick<Options, \"execTimeout\"> = {},\n): Layer.Layer<SandboxFileSystem.Service | Shell> =>\n\tLayer.merge(\n\t\tLayer.succeed(\n\t\t\tSandboxFileSystem.Service,\n\t\t\tSandboxFileSystem.fromProvider(RemoteFileSystem.make(providerFrom(sandbox))),\n\t\t),\n\t\tLayer.succeed(\n\t\t\tShell,\n\t\t\tShell.of({\n\t\t\t\texec: exec(sandbox, options),\n\t\t\t\texecArgv: execArgv(sandbox, options),\n\t\t\t\tstream: stream(sandbox, options),\n\t\t\t}),\n\t\t),\n\t);\n\n// Vercel's locator is the sandbox name. See `SandboxResource` for why this is a\n// shared tag rather than a Vercel-specific one.\nconst resourceLayer = Layer.effect(\n\tSandboxResource.Service,\n\tEffect.map(Remote, ({ sandbox }) => ({ providerResourceId: sandbox.name })),\n);\n\n// Identity is per remote sandbox, not per provider: two sandboxes both rooted at\n// the same directory must not share persisted directory records.\n//\n// The id is minted here only when the caller names none. A durable id is the\n// control plane's to mint and record — deriving one from the provider's own\n// locator is what §6.1 forbids — so a caller that needs the namespace to survive\n// a restart passes `instanceId` rather than relying on this.\nconst identityLayer = (options: Options) =>\n\tLayer.effect(\n\t\tSandboxIO.Current,\n\t\tEffect.map(Remote, () =>\n\t\t\tSandboxIO.remote({\n\t\t\t\tdriver: \"vercel\",\n\t\t\t\tid: options.instanceId ?? SandboxInstance.ID.create(),\n\t\t\t\tdefaultCwd: DEFAULT_CWD,\n\t\t\t\t...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n\t\t\t}),\n\t\t),\n\t);\n\n/**\n * A Vercel sandbox provides the runtime filesystem service directly plus the\n * sandbox's native remote shell. It intentionally does not provide VFS: remote\n * filesystems have no synchronous filesystem surface.\n */\nexport const layer = (\n\toptions: Options = {},\n): Layer.Layer<SandboxIO.Provides | SandboxResource.Service, VercelError> => {\n\tconst mounted = { ...options, cwd: SandboxIO.resolveMountCwd(DEFAULT_CWD, options.cwd) };\n\treturn Layer.mergeAll(filesystemLayer(mounted), shellLayer(mounted), identityLayer(mounted), resourceLayer).pipe(\n\t\tLayer.provide(remote(mounted)),\n\t);\n};\n\nexport const services = layer;\n\nexport * as EnvVercel from \"./vercel.ts\";\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport { SandboxDriver } from \"../driver.ts\";\nimport { makeRedactor, providerError, type SandboxProviderError } from \"../errors.ts\";\nimport { SandboxInstance } from \"../instance.ts\";\nimport { EnvVercel } from \"../providers/vercel.ts\";\n\nexport interface ClientOptions {\n\treadonly token?: string | undefined;\n\treadonly teamId?: string | undefined;\n\treadonly projectId?: string | undefined;\n}\n\nexport const Source = Schema.Union([\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"git\"),\n\t\turl: Schema.String,\n\t\trevision: Schema.optional(Schema.String),\n\t\tdepth: Schema.optional(Schema.Finite),\n\t}),\n\tSchema.Struct({\n\t\ttype: Schema.Literal(\"tarball\"),\n\t\turl: Schema.String,\n\t}),\n]);\nexport type Source = typeof Source.Type;\n\nexport const CreateConfig = Schema.Struct({\n\tsnapshot: Schema.optional(Schema.String),\n\tsource: Schema.optional(Source),\n\truntime: Schema.optional(Schema.String),\n\tports: Schema.optional(Schema.Array(Schema.Finite)),\n\tenvVars: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n\tvcpus: Schema.optional(Schema.Finite),\n\ttimeout: Schema.optional(Schema.Finite),\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type CreateConfig = typeof CreateConfig.Type;\n\nexport const RuntimeConfig = Schema.Struct({\n\tdefaultCwd: SandboxDriver.AbsolutePath,\n\texecTimeout: Schema.optional(Schema.Finite),\n});\nexport type RuntimeConfig = typeof RuntimeConfig.Type;\n\nconst name = SandboxDriver.Name.make(\"vercel\");\ntype RemoteSandbox = import(\"@vercel/sandbox\").Sandbox;\n\nconst statusFrom = (\n\tstatus: RemoteSandbox[\"status\"],\n): {\n\treadonly status: SandboxInstance.Status;\n\treadonly providerStatus: string;\n} => ({\n\tstatus:\n\t\tstatus === \"stopped\"\n\t\t\t? \"offline\"\n\t\t\t: status === \"stopping\" || status === \"snapshotting\"\n\t\t\t\t? \"suspending\"\n\t\t\t\t: status === \"failed\" || status === \"aborted\"\n\t\t\t\t\t? \"faulted\"\n\t\t\t\t\t: \"online\",\n\tproviderStatus: status,\n});\n\nconst isNotFound = (cause: unknown): boolean => {\n\tif (typeof cause !== \"object\" || cause === null) return false;\n\tconst response = \"response\" in cause && cause.response instanceof Response ? cause.response : undefined;\n\tconst code =\n\t\t\"code\" in cause && typeof cause.code === \"string\"\n\t\t\t? cause.code\n\t\t\t: \"json\" in cause &&\n\t\t\t\t typeof cause.json === \"object\" &&\n\t\t\t\t cause.json !== null &&\n\t\t\t\t \"error\" in cause.json &&\n\t\t\t\t typeof cause.json.error === \"object\" &&\n\t\t\t\t cause.json.error !== null &&\n\t\t\t\t \"code\" in cause.json.error &&\n\t\t\t\t typeof cause.json.error.code === \"string\"\n\t\t\t\t? cause.json.error.code\n\t\t\t\t: undefined;\n\treturn response?.status === 404 || code === \"not_found\" || code === \"sandbox_not_found\";\n};\n\nexport const make = (\n\tclient: ClientOptions = {},\n): SandboxDriver.Driver<CreateConfig, RuntimeConfig> & SandboxDriver.Registration => {\n\tconst credentials = EnvVercel.credentialsFrom(client);\n\tconst redact = makeRedactor([client.token ?? \"\"]);\n\n\tconst attempt = <A>(operation: string, run: () => Promise<A>): Effect.Effect<A, SandboxProviderError> =>\n\t\tEffect.tryPromise({\n\t\t\ttry: run,\n\t\t\tcatch: (cause) =>\n\t\t\t\tproviderError({\n\t\t\t\t\tdriver: name,\n\t\t\t\t\toperation,\n\t\t\t\t\tcause,\n\t\t\t\t\tredact,\n\t\t\t\t\tnotFound: isNotFound(cause),\n\t\t\t\t}),\n\t\t});\n\n\tconst get = (providerResourceId: string, resume: boolean, operation: string) =>\n\t\tattempt(operation, () =>\n\t\t\timport(\"@vercel/sandbox\").then(({ Sandbox }) =>\n\t\t\t\tSandbox.get(\n\t\t\t\t\tcredentials === undefined\n\t\t\t\t\t\t? { name: providerResourceId, resume }\n\t\t\t\t\t\t: { ...credentials, name: providerResourceId, resume },\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\tconst observed = (sandbox: RemoteSandbox): SandboxDriver.Observed => ({\n\t\t...statusFrom(sandbox.status),\n\t\tmetadata: {\n\t\t\tcwd: sandbox.cwd,\n\t\t},\n\t});\n\n\treturn SandboxDriver.driver({\n\t\tname,\n\t\tkind: \"remote\",\n\t\tcapabilities: {\n\t\t\treattach: true,\n\t\t\twake: true,\n\t\t\tstop: true,\n\t\t\tdestroy: true,\n\t\t\tcancels: true,\n\t\t},\n\t\tcreateConfigCodec: CreateConfig,\n\t\truntimeConfigCodec: RuntimeConfig,\n\t\tcreate: ({ instanceId, config }) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tconst source =\n\t\t\t\t\tconfig.source?.type === \"git\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttype: \"git\" as const,\n\t\t\t\t\t\t\t\turl: config.source.url,\n\t\t\t\t\t\t\t\t...(config.source.revision === undefined ? {} : { revision: config.source.revision }),\n\t\t\t\t\t\t\t\t...(config.source.depth === undefined ? {} : { depth: config.source.depth }),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: config.source;\n\t\t\t\tconst sandbox = yield* attempt(\"create\", () =>\n\t\t\t\t\tEnvVercel.createSandbox(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...client,\n\t\t\t\t\t\t\t...(config.snapshot === undefined ? {} : { snapshot: config.snapshot }),\n\t\t\t\t\t\t\t...(source === undefined ? {} : { source }),\n\t\t\t\t\t\t\t...(config.runtime === undefined ? {} : { runtime: config.runtime }),\n\t\t\t\t\t\t\t...(config.ports === undefined ? {} : { ports: [...config.ports] }),\n\t\t\t\t\t\t\t...(config.envVars === undefined ? {} : { envVars: config.envVars }),\n\t\t\t\t\t\t\t...(config.vcpus === undefined ? {} : { vcpus: config.vcpus }),\n\t\t\t\t\t\t\t...(config.timeout === undefined ? {} : { timeout: config.timeout }),\n\t\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t\t\ttags: {\n\t\t\t\t\t\t\t\t\"codework-instance\": instanceId,\n\t\t\t\t\t\t\t\t\"codework-managed\": \"true\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcredentials,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst state = statusFrom(sandbox.status);\n\t\t\t\treturn {\n\t\t\t\t\tproviderResourceId: sandbox.name,\n\t\t\t\t\tproviderStatus: state.providerStatus,\n\t\t\t\t\truntimeConfig: {\n\t\t\t\t\t\tdefaultCwd: SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t\t\t...(config.execTimeout === undefined ? {} : { execTimeout: config.execTimeout }),\n\t\t\t\t\t},\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tcwd: sandbox.cwd,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\truntimeConfigFor: ({ providerResourceId, overrides }) =>\n\t\t\tEffect.map(get(providerResourceId, false, \"runtimeConfigFor\"), (sandbox) => ({\n\t\t\t\tdefaultCwd: overrides?.defaultCwd ?? SandboxDriver.AbsolutePath.make(sandbox.cwd || EnvVercel.DEFAULT_CWD),\n\t\t\t\t...(overrides?.execTimeout === undefined ? {} : { execTimeout: overrides.execTimeout }),\n\t\t\t})),\n\t\tattach: (input) =>\n\t\t\tLayer.unwrap(\n\t\t\t\tEffect.map(\n\t\t\t\t\tget(\n\t\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\"attach\",\n\t\t\t\t\t),\n\t\t\t\t\t(sandbox) =>\n\t\t\t\t\t\tEnvVercel.transport(\n\t\t\t\t\t\t\tsandbox,\n\t\t\t\t\t\t\tinput.runtimeConfig.execTimeout === undefined\n\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t: { execTimeout: input.runtimeConfig.execTimeout },\n\t\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\tinspect: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"inspect\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\twake: (input) =>\n\t\t\tEffect.map(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\ttrue,\n\t\t\t\t\t\"wake\",\n\t\t\t\t),\n\t\t\t\tobserved,\n\t\t\t),\n\t\tstop: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"stop\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"stop\", () => sandbox.stop()).pipe(Effect.map(() => observed(sandbox))),\n\t\t\t),\n\t\tdestroy: (input) =>\n\t\t\tEffect.flatMap(\n\t\t\t\tget(\n\t\t\t\t\tOption.getOrElse(input.providerResourceId, () => input.id),\n\t\t\t\t\tfalse,\n\t\t\t\t\t\"destroy\",\n\t\t\t\t),\n\t\t\t\t(sandbox) => attempt(\"destroy\", () => sandbox.delete()),\n\t\t\t),\n\t});\n};\n\nexport * as VercelSandboxDriver from \"./vercel.ts\";\n","import { Context, Effect, Layer, Schema } from \"effect\";\nimport { posix as path } from \"../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 \"../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 { EventList } from \"../event/list.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 { SessionMessageSchema } from \"../session/message/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\nexport class ModelNotFoundError extends Schema.TaggedError<ModelNotFoundError>()(\"Runner.ModelNotFoundError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n}) {}\n\nexport class ProviderTurnError extends Schema.TaggedError<ProviderTurnError>()(\"Runner.ProviderTurnError\", {\n\tprovider: Schema.String,\n\tmodel: Schema.String,\n\tcause: Schema.Defect(),\n}) {}\n\nexport class LLMStreamError extends Schema.TaggedError<LLMStreamError>()(\"Runner.LLMStreamError\", {\n\tsessionId: Schema.String,\n\treason: Schema.String,\n}) {}\n\nexport class TurnError extends Schema.TaggedError<TurnError>()(\"Runner.TurnError\", {\n\tsessionId: Schema.String,\n\tmessageId: optional(SessionMessageSchema.ID),\n\tcause: EventList.TurnAbortCause,\n}) {}\n\nexport type RunError =\n\t| ModelNotFoundError\n\t| ProviderTurnError\n\t| LLMStreamError\n\t| TurnError\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/** Drains durable queued input without forcing an otherwise empty provider turn. */\n\treadonly drain: (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/** Interrupt active work owned by this process. Idle interruption is a no-op. */\n\treadonly interrupt: (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\tdrain: () => Effect.void,\n\t\twake: () => Effect.void,\n\t\tinterrupt: () => 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 * as 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 and awaits the drain generation responsible for it. */\n\treadonly run: (\n\t\tinput: PromptInput,\n\t) => Effect.Effect<Admitted, Session.SessionNotFoundError | PromptConflictError | Runner.RunError>;\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* restore(execution.drain(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 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// Uninterruptible because `interrupt` waits for the owner fiber's cleanup:\n\t\t// cancelling the caller partway would abandon a stop it already started.\n\t\tconst interrupt = Effect.fn(\"Control.interrupt\")((sessionId: SessionSchema.ID) =>\n\t\t\tEffect.uninterruptible(execution.interrupt(sessionId)),\n\t\t);\n\n\t\treturn Service.of({ prompt, run, 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> {\n\t/** Snapshots keys with an execution owned by this coordinator. */\n\treadonly active: Effect.Effect<ReadonlySet<Key>>;\n\t/** Starts execution while idle or joins the active execution. */\n\treadonly run: (key: Key) => Effect.Effect<void, E>;\n\t/** Coalesces queued work and awaits the drain generation assigned to it. */\n\treadonly drain: (key: Key) => Effect.Effect<void, E>;\n\t/** Registers one coalesced follow-up after newly recorded work. */\n\treadonly wake: (key: Key) => Effect.Effect<void>;\n\t/** Stops active execution and waits for its cleanup. */\n\treadonly interrupt: (key: Key) => Effect.Effect<void>;\n}\n\ntype Entry<E> = {\n\t// other fiber wants to know when key is finished will await this deferred\n\treadonly done: Deferred.Deferred<void, E>;\n\tcurrentWaiters: Array<Deferred.Deferred<void, E>>;\n\tpendingWaiters: Array<Deferred.Deferred<void, E>>;\n\t// process owner\n\towner?: Fiber.Fiber<void, void>;\n\t// if called wake() while the fiber is running, flips to true\n\t// runs one more time when finished.\n\tpendingWake: boolean;\n\t// set by interrupt()\n\tstopping: boolean;\n};\n\nexport const make = <Key, E>(options: {\n\t// Actual work that is to be run within the coordinator\n\t// key: Execution resource ID e.g: sessionID\n\t// force: A boolean flag passed down by coordinator\n\treadonly drain: (key: Key, force: boolean) => Effect.Effect<void, E>;\n}): Effect.Effect<Coordinator<Key, E>, never, Scope.Scope> =>\n\tEffect.gen(function* () {\n\t\tconst active = new Map<Key, Entry<E>>();\n\t\tconst fork = yield* FiberSet.makeRuntime<never, void, never>();\n\n\t\tconst makeEntry = (waiter?: Deferred.Deferred<void, E>): Entry<E> => ({\n\t\t\tdone: Deferred.makeUnsafe<void, E>(),\n\t\t\tcurrentWaiters: waiter === undefined ? [] : [waiter],\n\t\t\tpendingWaiters: [],\n\t\t\tpendingWake: false,\n\t\t\tstopping: false,\n\t\t});\n\n\t\tconst complete = (waiters: ReadonlyArray<Deferred.Deferred<void, E>>, exit: Exit.Exit<void, E>) => {\n\t\t\tfor (const waiter of waiters) Deferred.doneUnsafe(waiter, exit);\n\t\t};\n\n\t\tconst start = (key: Key, entry: Entry<E>, force: boolean, successor = false) => {\n\t\t\t// The Race Condition:\n\t\t\t// When we spawn new fiber, Effect fork might start immediate execution on same tick of event loop\n\t\t\t// `entry.owner` might not be set i.e `settle` is invoked before setting `entry.owner`, leading to race conditions\n\t\t\t// To prevent this, parent creates Deferred called ready.\n\t\t\t// The child fiber sees: `Deferred.await(ready)` and sleeps giving time for parent to set the `entry.owner = owner`\n\t\t\t// Once assigned, the parent calls `Deferred.doneUnsafe` waking the child up for actual work.\n\t\t\t//\n\t\t\t// In Successor Path:\n\t\t\t// If the fiber was spawned by settle because pendingWake was set true, it doesn't need the ready lock.\n\t\t\t// As the parent of settle, already knows about the entry exists and has set `entry.owner`\n\t\t\tconst ready = Deferred.makeUnsafe<void>();\n\t\t\tconst owner = fork(\n\t\t\t\t(successor ? Effect.yieldNow : Deferred.await(ready)).pipe(\n\t\t\t\t\tEffect.andThen(Effect.suspend(() => options.drain(key, force))),\n\t\t\t\t\tEffect.onExit((exit) => Effect.sync(() => settle(key, entry, 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\tentry.owner = owner;\n\t\t\tif (!successor) Deferred.doneUnsafe(ready, Effect.void);\n\t\t};\n\n\t\tconst settle = (key: Key, entry: Entry<E>, exit: Exit.Exit<void, E>) => {\n\t\t\tif (Exit.isSuccess(exit) && !entry.stopping && entry.pendingWake) {\n\t\t\t\tcomplete(entry.currentWaiters, exit);\n\t\t\t\tentry.currentWaiters = entry.pendingWaiters;\n\t\t\t\tentry.pendingWaiters = [];\n\t\t\t\tentry.pendingWake = false;\n\t\t\t\tstart(key, entry, false, true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tcomplete(entry.currentWaiters, exit);\n\t\t\tif (entry.stopping) complete(entry.pendingWaiters, exit);\n\t\t\tconst successor = entry.pendingWake ? makeEntry() : undefined;\n\t\t\tif (successor !== undefined) successor.currentWaiters = entry.pendingWaiters;\n\t\t\tif (successor === undefined) active.delete(key);\n\t\t\telse {\n\t\t\t\tactive.set(key, successor);\n\t\t\t\tstart(key, successor, false, true);\n\t\t\t}\n\t\t\tDeferred.doneUnsafe(entry.done, exit);\n\t\t};\n\n\t\tconst run = (key: Key): Effect.Effect<void, E> =>\n\t\t\tEffect.uninterruptibleMask((restore) => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tif (entry.stopping) return restore(Deferred.await(entry.done).pipe(Effect.andThen(run(key))));\n\t\t\t\t\treturn restore(Deferred.await(entry.done));\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry();\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, true);\n\t\t\t\treturn restore(Deferred.await(next.done));\n\t\t\t});\n\n\t\tconst drain = (key: Key): Effect.Effect<void, E> =>\n\t\t\tEffect.uninterruptibleMask((restore) => {\n\t\t\t\tconst waiter = Deferred.makeUnsafe<void, E>();\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tif (entry.stopping) return restore(Deferred.await(entry.done).pipe(Effect.andThen(drain(key))));\n\t\t\t\t\tentry.pendingWake = true;\n\t\t\t\t\tentry.pendingWaiters.push(waiter);\n\t\t\t\t\treturn restore(Deferred.await(waiter));\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry(waiter);\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, false);\n\t\t\t\treturn restore(Deferred.await(waiter));\n\t\t\t});\n\n\t\tconst wake = (key: Key) =>\n\t\t\tEffect.sync(() => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry !== undefined) {\n\t\t\t\t\tentry.pendingWake = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst next = makeEntry();\n\t\t\t\tactive.set(key, next);\n\t\t\t\tstart(key, next, false);\n\t\t\t});\n\n\t\tconst interrupt = (key: Key): Effect.Effect<void> =>\n\t\t\tEffect.suspend(() => {\n\t\t\t\tconst entry = active.get(key);\n\t\t\t\tif (entry?.owner === undefined) return Effect.void;\n\t\t\t\tentry.stopping = true;\n\t\t\t\tentry.pendingWake = false;\n\t\t\t\treturn Fiber.interrupt(entry.owner);\n\t\t\t});\n\n\t\treturn { active: Effect.sync(() => new Set(active.keys())), run, drain, wake, interrupt };\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 * as 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.hasInterruptsOnly(cause)\n\t\t\t\t\t\t\t? Effect.void\n\t\t\t\t\t\t\t: Effect.logError(\"failed to drain session\", cause).pipe(Effect.annotateLogs({ sessionId })),\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\tdrain: coordinator.drain,\n\t\t\twake: coordinator.wake,\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","/*\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 {\n\tstream as aikitStream,\n\tllm,\n\ttype Event as AikitEvent,\n\ttype Message,\n\ttype Model,\n\ttype OpenAIOptions,\n} from \"@codeworksh/aikit\";\nimport { 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 { 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}\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<AsyncIterable<AikitEvent.LLMMessageEvent>, Runner.ModelNotFoundError | Runner.ProviderTurnError>;\n\nexport type Request = (\n\tinput: RequestInput,\n) => Effect.Effect<\n\tLLMEventPublisher.Terminal,\n\tRunner.ModelNotFoundError | Runner.ProviderTurnError | Runner.LLMStreamError\n>;\n\nconst runtimeOptions = (input: Input, signal: AbortSignal): OpenAIOptions =>\n\t({\n\t\tproviderOptions: { openai: { reasoningSummary: \"auto\" } },\n\t\t...input.options,\n\t\t...(input.thinkingLevel === undefined || input.thinkingLevel === \"off\" ? {} : { reasoning: input.thinkingLevel }),\n\t\tsessionId: input.sessionId,\n\t\tsignal,\n\t}) as unknown as OpenAIOptions;\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),\n\t\tcatch: (cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, cause }),\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, signal)),\n\t\tcatch: (cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, 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(\n\t\t\t\t\titerable,\n\t\t\t\t\t(cause) => new Runner.ProviderTurnError({ provider: input.provider, model: input.model, cause }),\n\t\t\t\t).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","/**\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 \"../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 \"../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","import { Context, Effect, Layer, Option, Ref } from \"effect\";\nimport type { SessionSchema } from \"./schema.ts\";\nimport type { State } from \"../state/state.ts\";\n\n/** Process-local values that cannot be reconstructed from the durable session log. */\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 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 { Context as SessionContext } from \"../context/context.ts\";\nimport { Location } from \"../location/location.ts\";\nimport { SandboxIO } from \"../sandbox/io.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 type { ID as SessionId } from \"../session/schema.ts\";\nimport { SessionRuntime } from \"../session/runtime.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 * FIXME(sanchitrk): read from settings config once we set that up;\n *\n * Defaults. `maxTokens` is deliberately absent: aikit's `stream()` already calls\n * `applyDefaultMaxTokens`, which derives it from the model's own `maxTokens` and\n * `contextWindow`. Setting one here would override a model-aware value with a\n * fixed guess.\n */\nexport const defaults = {\n\tprovider: \"openai\",\n\tmodel: \"gpt-5.5\",\n\tthinkingLevel: \"medium\",\n\ttoolExecution: \"sequential\",\n\ttimeoutMs: 60_000,\n\tmaxRetries: 0,\n} as const satisfies {\n\treadonly provider: string;\n\treadonly model: string;\n\treadonly thinkingLevel: Model.ThinkingLevel;\n\treadonly toolExecution: ToolExecutionMode;\n\treadonly timeoutMs: number;\n\treadonly maxRetries: number;\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\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 | SessionContext.ContextReadError, 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 contexts = yield* SessionContext.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 durable = (yield* contexts.assemble(sessionId)).config;\n\t\t\t\t\tconst merged = { ...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: runtimeProvider,\n\t\t\t\t\t\tmodel: runtimeModel,\n\t\t\t\t\t\tthinkingLevel: runtimeThinkingLevel,\n\t\t\t\t\t\ttoolExecution = defaults.toolExecution,\n\t\t\t\t\t\t...rest\n\t\t\t\t\t} = merged;\n\t\t\t\t\tconst provider = runtimeProvider ?? durable.model?.providerId ?? defaults.provider;\n\t\t\t\t\tconst model = runtimeModel ?? durable.model?.modelId ?? defaults.model;\n\t\t\t\t\tconst thinkingLevel = runtimeThinkingLevel ?? durable.thinkingLevel ?? defaults.thinkingLevel;\n\t\t\t\t\tconst request: RequestOptions = {\n\t\t\t\t\t\ttimeoutMs: defaults.timeoutMs,\n\t\t\t\t\t\tmaxRetries: defaults.maxRetries,\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t};\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\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 { Context } from \"../context/context.ts\";\nimport { ContextCodec } from \"../context/codec.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\treturn squashed instanceof Error ? squashed.message : String(squashed);\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\tpublisher,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (terminal.outcome === \"failed\") {\n\t\t\t\t\t\tconst cause: EventList.TurnAbortCause =\n\t\t\t\t\t\t\tterminal.reason === \"aborted\"\n\t\t\t\t\t\t\t\t? { _tag: \"interrupted\" }\n\t\t\t\t\t\t\t\t: { _tag: \"error\", message: terminal.message.errorMessage ?? \"provider turn failed\" };\n\t\t\t\t\t\treturn yield* new Runner.TurnError({\n\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t...(publisher.startedMessageId === undefined ? {} : { messageId: publisher.startedMessageId }),\n\t\t\t\t\t\t\tcause,\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 failure = Cause.findErrorOption(cause);\n\t\t\t\t\t\tif (Option.isSome(failure) && failure.value._tag === \"Runner.TurnError\") {\n\t\t\t\t\t\t\treturn Effect.fail(failure.value);\n\t\t\t\t\t\t}\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\treturn Effect.fail(\n\t\t\t\t\t\t\tnew Runner.TurnError({\n\t\t\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\t\t\t...(publisher?.startedMessageId === undefined ? {} : { messageId: publisher.startedMessageId }),\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}),\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).pipe(\n\t\t\t\t\tEffect.catchTag(\"Runner.TurnError\", (error) =>\n\t\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\t\tif (error.messageId !== undefined) {\n\t\t\t\t\t\t\t\tconst stored = yield* sessions.entry(error.messageId);\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, error.cause);\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: snapshot.sessionId,\n\t\t\t\t\t\t\t\tcause: error.cause,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn yield* error;\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\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","/*\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, Schema } 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\";\nimport { optional } from \"../schema.ts\";\n\nconst ConfigChangeData = Schema.fromJsonString(\n\tSchema.Struct({\n\t\tmodel: optional(Schema.Struct({ providerId: Schema.String, modelId: Schema.String })),\n\t\tthinkingLevel: optional(Schema.Literals([\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"])),\n\t}),\n);\nconst encodeConfigChange = Schema.encodeEffect(ConfigChangeData);\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\tyield* events.project(EventList.ConfigChanged, (event) =>\n\t\t\tEffect.gen(function* () {\n\t\t\t\tif (event.durable === undefined)\n\t\t\t\t\treturn yield* Effect.die(\"ConfigChanged is missing its aggregate sequence\");\n\t\t\t\tyield* sessions\n\t\t\t\t\t.append({\n\t\t\t\t\t\tid: event.id,\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\ttype: \"configChange\",\n\t\t\t\t\t\tstate: \"committed\",\n\t\t\t\t\t\tdata: yield* encodeConfigChange({\n\t\t\t\t\t\t\t...(event.data.model === undefined ? {} : { model: event.data.model }),\n\t\t\t\t\t\t\t...(event.data.thinkingLevel === undefined ? {} : { thinkingLevel: event.data.thinkingLevel }),\n\t\t\t\t\t\t}).pipe(Effect.orDie),\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\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 { SessionLive } from \"../session/live.ts\";\nimport { SessionRuntime } from \"../session/runtime.ts\";\nimport { State } from \"../state/state.ts\";\nimport type { Driver } from \"./sandbox.ts\";\n\nexport interface Options {\n\treadonly database?: string;\n\treadonly home?: string;\n\treadonly sandboxes?: ReadonlyArray<Driver>;\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.resolveLocation(configuredDatabase, paths.data));\n\t\t\tconst drivers = SandboxDriver.layer(...(options.sandboxes ?? []));\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(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 { DaytonaSandboxDriver } from \"../sandbox/drivers/daytona.ts\";\nimport { MemorySandboxDriver } from \"../sandbox/drivers/memory.ts\";\nimport { SqldbSandboxDriver } from \"../sandbox/drivers/sqldb.ts\";\nimport { VercelSandboxDriver } from \"../sandbox/drivers/vercel.ts\";\nimport { SandboxInstance } from \"../sandbox/instance.ts\";\n\nexport type Info = SandboxInstance.Info;\nexport type Driver = SandboxDriver.Registration;\n\nexport type CreateInput =\n\t| { readonly driver: \"memory\"; readonly cwd?: string }\n\t| { readonly driver: \"sqldb\"; readonly cwd?: string; readonly location?: string }\n\t| ({ readonly driver: \"vercel\" } & VercelSandboxDriver.CreateConfig)\n\t| ({ readonly driver: \"daytona\" } & DaytonaSandboxDriver.CreateConfig);\n\nexport type RegisterInput = {\n\treadonly driver: \"vercel\" | \"daytona\";\n\treadonly providerResourceId: string;\n};\n\nconst registered = Effect.fn(\"Sandbox.registered\")(function* (name: string) {\n\tconst registry = yield* SandboxDriver.Registry;\n\treturn yield* registry.get(SandboxDriver.Name.make(name));\n});\n\nexport const create = Effect.fn(\"Sandbox.create\")(function* (input: CreateInput) {\n\tconst controller = yield* SandboxController.Controller;\n\tconst driver = yield* registered(input.driver);\n\tif (input.driver === \"memory\") {\n\t\tconst cwd = SandboxDriver.AbsolutePath.make(input.cwd ?? \"/\");\n\t\treturn yield* controller.create({ driver, config: { defaultCwd: cwd, initializeCwd: cwd } });\n\t}\n\tif (input.driver === \"sqldb\") {\n\t\tconst cwd = SandboxDriver.AbsolutePath.make(input.cwd ?? \"/\");\n\t\treturn yield* controller.create({\n\t\t\tdriver,\n\t\t\tconfig: {\n\t\t\t\tdefaultCwd: cwd,\n\t\t\t\tinitializeCwd: cwd,\n\t\t\t\t...(input.location === undefined ? {} : { location: input.location }),\n\t\t\t},\n\t\t});\n\t}\n\tconst { driver: _, ...config } = input;\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\treturn yield* controller.register({ driver, providerResourceId: input.providerResourceId });\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: SandboxDriver.Name.make(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 const Drivers = {\n\tget memory(): Driver {\n\t\treturn MemorySandboxDriver.make().driver;\n\t},\n\tget sqldb(): Driver {\n\t\treturn SqldbSandboxDriver.make().driver;\n\t},\n\tvercel: (options: VercelSandboxDriver.ClientOptions = {}): Driver => VercelSandboxDriver.make(options),\n\tdaytona: (options: DaytonaSandboxDriver.ClientOptions = {}): Driver => DaytonaSandboxDriver.make(options),\n} as const;\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 type { EventSchema } from \"../event/schema.ts\";\nimport * as Event from \"../event/event.ts\";\nimport { EventList } from \"../event/list.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 { State } from \"../state/state.ts\";\nimport type { StatePrompt } from \"../state/prompt.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 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 publishConfig = Effect.fn(\"Session.publishConfig\")(function* (\n\tevents: Event.Interface,\n\tsessionId: SessionSchema.ID,\n\tinput: Pick<RuntimeInput, \"model\" | \"thinkingLevel\">,\n) {\n\tif (input.model === undefined && input.thinkingLevel === undefined) return;\n\tyield* events.publish(EventList.ConfigChanged, {\n\t\ttimestamp: yield* DateTime.now,\n\t\tsessionId,\n\t\t...(input.model === undefined ? {} : { model: { providerId: input.model.provider, modelId: input.model.id } }),\n\t\t...(input.thinkingLevel === undefined ? {} : { thinkingLevel: input.thinkingLevel }),\n\t});\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\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 events = yield* Event.Service;\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* publishConfig(events, id, input);\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\tconst events = yield* Event.Service;\n\tyield* publishConfig(events, input.sessionId, input);\n\tyield* runtime.set(input.sessionId, runtimeBindings(input));\n\treturn found.value;\n});\n\nexport { AbsolutePath, SessionMessageSchema, SessionSchema };\n\nexport * as Session from \"./session.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