@codeworksh/cli 0.9.0-canary.161.1.gdb3b1409 → 0.9.0-canary.163.1.g9e8c1408

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.
Files changed (30) hide show
  1. package/{acp-NKndM0y4.mjs → acp-CrNOJRGe.mjs} +2 -2
  2. package/{acp-NKndM0y4.mjs.map → acp-CrNOJRGe.mjs.map} +1 -1
  3. package/{connect-Cwz4fwcc.mjs → connect-Bg3kHbrx.mjs} +3 -3
  4. package/{connect-Cwz4fwcc.mjs.map → connect-Bg3kHbrx.mjs.map} +1 -1
  5. package/{disconnect-D4g8ISX9.mjs → disconnect-hDfEVmWt.mjs} +2 -2
  6. package/{disconnect-D4g8ISX9.mjs.map → disconnect-hDfEVmWt.mjs.map} +1 -1
  7. package/{discovery-CULIX-ah.mjs → discovery-B9UpJs9z.mjs} +2 -2
  8. package/{discovery-CULIX-ah.mjs.map → discovery-B9UpJs9z.mjs.map} +1 -1
  9. package/{identity--j8hMb07.mjs → identity-DQYgsuek.mjs} +2 -2
  10. package/{identity--j8hMb07.mjs.map → identity-DQYgsuek.mjs.map} +1 -1
  11. package/index.mjs +9 -9
  12. package/package-CssYvr3o.mjs +6 -0
  13. package/package-CssYvr3o.mjs.map +1 -0
  14. package/package.json +3 -3
  15. package/{relay-Ccwzl2lc.mjs → relay-Bp4GqpdD.mjs} +8 -4
  16. package/relay-Bp4GqpdD.mjs.map +1 -0
  17. package/{restart-9yoKrlmo.mjs → restart-De6ylFk3.mjs} +2 -2
  18. package/{restart-9yoKrlmo.mjs.map → restart-De6ylFk3.mjs.map} +1 -1
  19. package/{serve-CkGkCgTL.mjs → serve-DfixsOeg.mjs} +10 -4
  20. package/serve-DfixsOeg.mjs.map +1 -0
  21. package/{start-t0FCZvYw.mjs → start-BNhwppz_.mjs} +2 -2
  22. package/{start-t0FCZvYw.mjs.map → start-BNhwppz_.mjs.map} +1 -1
  23. package/{status-2NsYhn1K.mjs → status-B5-Cuqpo.mjs} +2 -2
  24. package/{status-2NsYhn1K.mjs.map → status-B5-Cuqpo.mjs.map} +1 -1
  25. package/{stop-CDk0lO6x.mjs → stop-MCLYgwMu.mjs} +2 -2
  26. package/{stop-CDk0lO6x.mjs.map → stop-MCLYgwMu.mjs.map} +1 -1
  27. package/package-B5dVwZ1g.mjs +0 -6
  28. package/package-B5dVwZ1g.mjs.map +0 -1
  29. package/relay-Ccwzl2lc.mjs.map +0 -1
  30. package/serve-CkGkCgTL.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { a as reportFailure } from "./error-qctchbYS.mjs";
2
- import { t as version } from "./package-B5dVwZ1g.mjs";
2
+ import { t as version } from "./package-CssYvr3o.mjs";
3
3
  import { i as Cmd, t as handler } from "./runtime-BC3hAvn_.mjs";
4
4
  import { t as harnessOptions } from "./harness-6d8TlAVk.mjs";
5
5
  import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Logger, Option, Schema, Stdio, Stream } from "effect";
@@ -546,4 +546,4 @@ var acp_default = handler(Cmd.commands.acp, Effect.fn("CLI.acp", { level: "Info"
546
546
  //#endregion
547
547
  export { acp_default as default };
548
548
 
549
- //# sourceMappingURL=acp-NKndM0y4.mjs.map
549
+ //# sourceMappingURL=acp-CrNOJRGe.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"acp-NKndM0y4.mjs","names":["serve","Agent.RequestError","pkg.version","Config.options","Feed.replay","Config.parseModel","Config.known","Config.isThinkingLevel","update","Feed.update","notice","Feed.notice","Feed.noticeUpdate","Handlers.make","Agent.serve","Runtime.handler","Server.serve"],"sources":["../../src/acp/agent.ts","../../src/acp/config.ts","../../src/acp/feed.ts","../../src/acp/handlers.ts","../../src/acp/server.ts","../../src/cli/cmd/handlers/acp.ts"],"sourcesContent":["import * as Acp from \"@agentclientprotocol/sdk\";\nimport { Cause, Deferred, Effect, Exit, Option, Schema, type Scope, type Stdio, Stream } from \"effect\";\n\n/** A JSON-RPC error a handler answers a request with. */\nexport class RequestError extends Schema.TaggedError<RequestError>()(\"AcpRequestError\", {\n\tcode: Schema.Int,\n\tmessage: Schema.String,\n\tdata: Schema.optionalKey(Schema.Json),\n}) {\n\tstatic invalidRequest = (message: string) => new RequestError({ code: -32600, message });\n\tstatic invalidParams = (message: string) => new RequestError({ code: -32602, message });\n\tstatic internalError = (message: string, data?: Schema.Json) =>\n\t\tnew RequestError({ code: -32603, message, ...(data === undefined ? {} : { data }) });\n\tstatic resourceNotFound = (message: string) => new RequestError({ code: -32002, message });\n}\n\ntype Handler<Request, Response> = (request: Request) => Effect.Effect<Response, RequestError>;\n\n/** Calls the agent makes to the connected client. */\nexport interface Client {\n\treadonly sessionUpdate: (notification: Acp.SessionNotification) => Effect.Effect<void, RequestError>;\n}\n\nexport interface Handlers {\n\treadonly initialize: Handler<Acp.InitializeRequest, Acp.InitializeResponse>;\n\treadonly newSession: Handler<Acp.NewSessionRequest, Acp.NewSessionResponse>;\n\t/** Must replay the session's history through `Client.sessionUpdate` before it returns. */\n\treadonly loadSession: Handler<Acp.LoadSessionRequest, Acp.LoadSessionResponse>;\n\treadonly listSessions: Handler<Acp.ListSessionsRequest, Acp.ListSessionsResponse>;\n\treadonly forkSession: Handler<Acp.ForkSessionRequest, Acp.ForkSessionResponse>;\n\treadonly setConfigOption: Handler<Acp.SetSessionConfigOptionRequest, Acp.SetSessionConfigOptionResponse>;\n\treadonly prompt: Handler<Acp.PromptRequest, Acp.PromptResponse>;\n\treadonly cancel: (notification: Acp.CancelNotification) => Effect.Effect<void>;\n}\n\n/**\n * Serves an ACP agent over `stdio` until the client closes its end.\n *\n * Handlers run as fibers on this effect's services; a request the client cancels, or the\n * connection closing, interrupts its fiber.\n */\nexport const serve = Effect.fn(\"ACP.serve\")(function* (\n\tstdio: Stdio.Stdio,\n\tmakeHandlers: (client: Client) => Handlers,\n): Effect.fn.Return<void, never, Scope.Scope> {\n\tconst context = yield* Effect.context<never>();\n\tconst runExit = Effect.runPromiseExitWith(context);\n\tconst opened = yield* Deferred.make<Acp.AgentConnection>();\n\n\tconst handlers = makeHandlers({\n\t\tsessionUpdate: (notification) =>\n\t\t\tDeferred.await(opened).pipe(\n\t\t\t\tEffect.flatMap((connection) =>\n\t\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t\ttry: () => connection.client.notify(Acp.methods.client.session.update, notification),\n\t\t\t\t\t\tcatch: (error) => RequestError.internalError(`Failed to send session/update: ${String(error)}`),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t});\n\n\t// A JSON-RPC answer for a handler that didn't succeed; the SDK sends what `handle` throws.\n\tconst toWire = (cause: Cause.Cause<RequestError>): Acp.RequestError => {\n\t\tconst error = Cause.findErrorOption(cause);\n\t\tif (Option.isSome(error)) return new Acp.RequestError(error.value.code, error.value.message, error.value.data);\n\t\tif (Cause.hasInterruptsOnly(cause)) return Acp.RequestError.requestCancelled();\n\t\treturn Acp.RequestError.internalError(undefined, String(Cause.squash(cause)));\n\t};\n\tconst handle =\n\t\t<Params, A>(handler: (params: Params) => Effect.Effect<A, RequestError>) =>\n\t\t({ params, signal }: { readonly params: Params; readonly signal: AbortSignal }): Promise<A> =>\n\t\t\trunExit(handler(params), { signal }).then((exit) => {\n\t\t\t\tif (Exit.isSuccess(exit)) return exit.value;\n\t\t\t\tthrow toWire(exit.cause);\n\t\t\t});\n\n\tconst input = yield* Stream.toReadableStreamEffect(stdio.stdin);\n\tconst output = new WritableStream<Uint8Array>({\n\t\twrite: (chunk) => Effect.runPromiseWith(context)(Stream.run(Stream.make(chunk), stdio.stdout())),\n\t});\n\n\tconst connection = Acp.agent({ name: \"codework\" })\n\t\t.onRequest(\"initialize\", handle(handlers.initialize))\n\t\t.onRequest(\"session/new\", handle(handlers.newSession))\n\t\t.onRequest(\"session/load\", handle(handlers.loadSession))\n\t\t.onRequest(\"session/list\", handle(handlers.listSessions))\n\t\t.onRequest(\"session/fork\", handle(handlers.forkSession))\n\t\t.onRequest(\"session/set_config_option\", handle(handlers.setConfigOption))\n\t\t.onRequest(\"session/prompt\", handle(handlers.prompt))\n\t\t.onNotification(\"session/cancel\", handle(handlers.cancel))\n\t\t.connect(Acp.ndJsonStream(output, input));\n\tyield* Deferred.succeed(opened, connection);\n\tyield* Effect.addFinalizer(() => Effect.sync(() => connection.close()));\n\tyield* Effect.promise(() => connection.closed);\n});\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport { Model } from \"@codeworksh/aikit\";\nimport { ModelCatalog, Settings, type State } from \"@codeworksh/harness/effect\";\nimport { Effect, Option } from \"effect\";\n\nexport const MODEL = \"model\";\nexport const THOUGHT_LEVEL = \"thought_level\";\n\nconst thinkingLabels: Record<Model.ThinkingLevel, string> = {\n\toff: \"Off\",\n\tminimal: \"Minimal\",\n\tlow: \"Low\",\n\tmedium: \"Medium\",\n\thigh: \"High\",\n\txhigh: \"Extra High\",\n\tmax: \"Max\",\n};\n\nexport const isThinkingLevel = (value: string): value is Model.ThinkingLevel => Object.hasOwn(thinkingLabels, value);\n\n/** Splits a `provider/model` option value on its first slash; model ids may contain more. */\nexport const parseModel = (value: string): Option.Option<{ readonly provider: string; readonly id: string }> => {\n\tconst slash = value.indexOf(\"/\");\n\tif (slash <= 0 || slash === value.length - 1) return Option.none();\n\treturn Option.some({ provider: value.slice(0, slash), id: value.slice(slash + 1) });\n};\n\n/** The catalog a session in `hostDir` sees: generated entries plus its settings' `models`. */\nconst catalogFor = (hostDir: string | undefined) =>\n\tEffect.gen(function* () {\n\t\tconst settings = yield* Settings.Service;\n\t\treturn yield* ModelCatalog.effective((yield* settings.load(hostDir)).models);\n\t}).pipe(Effect.orElseSucceed((): Model.BuiltInModels => ({})));\n\n/** The `model` and `thought_level` selectors for a session's current configuration. */\nexport const options = Effect.fn(\"ACP.config.options\")(function* (\n\tselection: State.Configuration,\n\thostDir: string | undefined,\n) {\n\tconst catalog = yield* catalogFor(hostDir);\n\t// Providers the harness has credentials for; the current model stays selectable even if not.\n\tconst providers = yield* ModelCatalog.available(hostDir === undefined ? {} : { hostDir }).pipe(\n\t\tEffect.orElseSucceed(() => []),\n\t);\n\n\tconst current = `${selection.provider}/${selection.model}`;\n\tconst models = providers.flatMap((provider) =>\n\t\tObject.entries(provider.models).map(([id, info]) => ({\n\t\t\tvalue: `${provider.id}/${id}`,\n\t\t\tname: `${info.provider.name}: ${info.name}`,\n\t\t})),\n\t);\n\tif (!models.some((option) => option.value === current)) models.unshift({ value: current, name: current });\n\n\tconst result: Array<Acp.SessionConfigOption> = [\n\t\t{ id: MODEL, name: \"Model\", category: \"model\", type: \"select\", currentValue: current, options: models },\n\t];\n\n\tconst info = catalog[selection.provider]?.[selection.model];\n\tconst levels = info === undefined ? [] : Model.getSupportedThinkingLevels(info);\n\tif (levels.some((level) => level !== \"off\")) {\n\t\tresult.push({\n\t\t\tid: THOUGHT_LEVEL,\n\t\t\tname: \"Thinking Effort\",\n\t\t\tcategory: \"thought_level\",\n\t\t\ttype: \"select\",\n\t\t\tcurrentValue: selection.thinkingLevel,\n\t\t\toptions: levels.map((level) => ({ value: level, name: thinkingLabels[level] })),\n\t\t});\n\t}\n\treturn result;\n});\n\n/** Whether a model is in the catalog a session in `hostDir` sees. */\nexport const known = Effect.fn(\"ACP.config.known\")(function* (\n\tmodel: { readonly provider: string; readonly id: string },\n\thostDir: string | undefined,\n) {\n\tconst catalog = yield* catalogFor(hostDir);\n\treturn catalog[model.provider]?.[model.id] !== undefined;\n});\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport { EventList, type EventSchema, type ThreadStore } from \"@codeworksh/harness/effect\";\nimport { Option, Schema } from \"effect\";\n\nconst isTextDelta = Schema.is(EventList.LLMTextDelta);\nconst isThinkingDelta = Schema.is(EventList.LLMThinkingDelta);\nconst isToolStarted = Schema.is(EventList.ToolStarted);\nconst isToolSettled = Schema.is(EventList.ToolSettled);\nconst isPluginUpdated = Schema.is(EventList.PluginUpdated);\n\nconst TextContent = Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String });\nconst ImageContent = Schema.Struct({ type: Schema.Literal(\"image\"), data: Schema.String, mimeType: Schema.String });\nconst ToolResult = Schema.Struct({\n\tcontent: Schema.Array(Schema.Union([TextContent, Schema.Struct({ type: Schema.Literal(\"image\") })])),\n\tisError: Schema.Boolean,\n});\nconst ToolCall = Schema.Struct({\n\ttype: Schema.Literal(\"toolCall\"),\n\tcallID: Schema.String,\n\tname: Schema.String,\n\targuments: Schema.Record(Schema.String, Schema.Json),\n\tstatus: Schema.String,\n\tresult: Schema.optional(ToolResult),\n});\nconst StoredPart = Schema.Union([\n\tTextContent,\n\tImageContent,\n\tSchema.Struct({ type: Schema.Literal(\"thinking\"), thinking: Schema.String }),\n\tToolCall,\n]);\nconst decodePart = Schema.decodeUnknownOption(Schema.fromJsonString(StoredPart));\n\ntype ToolCall = typeof ToolCall.Type;\n\nconst text = (value: string): Acp.ContentBlock => ({ type: \"text\", text: value });\n\n// The kind comes from the tool's name. Only `bash` ships built in; plugin tools report `other`.\nconst kind = (name: string): Acp.ToolKind => (name === \"bash\" ? \"execute\" : \"other\");\n\n/** The command for `bash`, otherwise the tool's label or name. */\nconst title = (name: string, args: Readonly<Record<string, unknown>>, label?: string): string =>\n\tname === \"bash\" && typeof args.command === \"string\" ? args.command : (label ?? name);\n\nconst settled = (call: Pick<ToolCall, \"callID\" | \"name\" | \"arguments\" | \"status\" | \"result\">): Acp.SessionUpdate => {\n\tconst output = call.result?.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n\treturn {\n\t\tsessionUpdate: \"tool_call_update\",\n\t\ttoolCallId: call.callID,\n\t\tkind: kind(call.name),\n\t\tstatus: call.status === \"completed\" ? \"completed\" : \"failed\",\n\t\trawInput: call.arguments,\n\t\t...(call.result === undefined ? {} : { rawOutput: call.result }),\n\t\t...(output ? { content: [{ type: \"content\", content: text(output) }] } : {}),\n\t};\n};\n\n/** The live `session/update` for a harness event, if the client should see one. */\nexport const update = (event: EventSchema.Payload): Option.Option<Acp.SessionUpdate> => {\n\tif (isTextDelta(event)) {\n\t\treturn Option.some({ sessionUpdate: \"agent_message_chunk\", content: text(event.data.delta) });\n\t}\n\tif (isThinkingDelta(event)) {\n\t\treturn Option.some({ sessionUpdate: \"agent_thought_chunk\", content: text(event.data.delta) });\n\t}\n\tif (isToolStarted(event)) {\n\t\treturn Option.some({\n\t\t\tsessionUpdate: \"tool_call\",\n\t\t\ttoolCallId: event.data.callID,\n\t\t\ttitle: title(event.data.name, event.data.arguments, event.data.label),\n\t\t\tkind: kind(event.data.name),\n\t\t\tstatus: \"in_progress\",\n\t\t\trawInput: event.data.arguments,\n\t\t});\n\t}\n\tif (isToolSettled(event)) return Option.some(settled(event.data.part));\n\treturn Option.none();\n};\n\n/**\n * Text for the user about a plugin that failed to load, such as one configured but not installed.\n * It belongs in the conversation because the user may never see this process's logs.\n */\nexport const notice = (event: EventSchema.Payload): Option.Option<string> =>\n\tisPluginUpdated(event) && event.data.status === \"failed\" && event.data.error !== undefined\n\t\t? Option.some(event.data.error)\n\t\t: Option.none();\n\n/** A notice shown to the user in the agent's message. */\nexport const noticeUpdate = (notice: string): Acp.SessionUpdate => ({\n\tsessionUpdate: \"agent_message_chunk\",\n\tcontent: text(`> ⚠ ${notice}\\n\\n`),\n});\n\n/** The `session/update`s that replay one stored entry during `session/load`. */\nexport const replay = ({ entry, parts }: ThreadStore.HydratedEntry): ReadonlyArray<Acp.SessionUpdate> => {\n\tif (entry.type !== \"user\" && entry.type !== \"assistant\") return [];\n\treturn parts.flatMap((row): ReadonlyArray<Acp.SessionUpdate> => {\n\t\tconst part = decodePart(row.data);\n\t\tif (Option.isNone(part)) return [];\n\t\tswitch (part.value.type) {\n\t\t\tcase \"text\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: entry.type === \"user\" ? \"user_message_chunk\" : \"agent_message_chunk\",\n\t\t\t\t\t\tcontent: text(part.value.text),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\tcase \"image\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: entry.type === \"user\" ? \"user_message_chunk\" : \"agent_message_chunk\",\n\t\t\t\t\t\tcontent: { type: \"image\", data: part.value.data, mimeType: part.value.mimeType },\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\tcase \"thinking\":\n\t\t\t\treturn [{ sessionUpdate: \"agent_thought_chunk\", content: text(part.value.thinking) }];\n\t\t\tcase \"toolCall\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: \"tool_call\",\n\t\t\t\t\t\ttoolCallId: part.value.callID,\n\t\t\t\t\t\ttitle: title(part.value.name, part.value.arguments),\n\t\t\t\t\t\tkind: kind(part.value.name),\n\t\t\t\t\t\tstatus: \"in_progress\",\n\t\t\t\t\t\trawInput: part.value.arguments,\n\t\t\t\t\t},\n\t\t\t\t\tsettled(part.value),\n\t\t\t\t];\n\t\t}\n\t});\n};\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport {\n\tControl,\n\tEventList,\n\ttype Harness,\n\tPromptSchema,\n\tSession,\n\tSessionStore,\n\tThreadStore,\n} from \"@codeworksh/harness/effect\";\nimport { DateTime, Effect, Fiber, type Layer, Option, Schema, Stream } from \"effect\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\nimport * as Agent from \"./agent.ts\";\nimport * as Config from \"./config.ts\";\nimport * as Feed from \"./feed.ts\";\n\nconst PAGE_SIZE = 50;\n\nconst isRequestError = Schema.is(Agent.RequestError);\nconst isNotFound = Schema.is(SessionStore.SessionNotFoundError);\nconst isConflict = Schema.is(Control.PromptConflictError);\nconst isInvalidPrompt = Schema.is(PromptSchema.InvalidPromptError);\nconst isLLMEnded = Schema.is(EventList.LLMEnded);\nconst isFailed = Schema.is(EventList.ExecutionFailed);\nconst isInterrupted = Schema.is(EventList.ExecutionInterrupted);\nconst isRunFailed = Schema.is(EventList.RunFailed);\n\n/** Harness failures as JSON-RPC errors; handlers raise protocol-level ones directly. */\nconst toRequestError = (error: { readonly message: string }): Agent.RequestError => {\n\tif (isRequestError(error)) return error;\n\tif (isNotFound(error)) return Agent.RequestError.resourceNotFound(`Session not found: ${error.sessionId}`);\n\tif (isConflict(error)) return Agent.RequestError.invalidRequest(error.message);\n\tif (isInvalidPrompt(error)) return Agent.RequestError.invalidParams(error.message);\n\treturn Agent.RequestError.internalError(error.message);\n};\n\n/**\n * Prompt content as harness prompt parts, in order. Text, embedded context and images are\n * advertised; anything else is rejected. Adjacent text joins into one part. The harness checks\n * the images.\n */\nconst promptParts = Effect.fnUntraced(function* (blocks: ReadonlyArray<Acp.ContentBlock>) {\n\tconst parts: Array<PromptSchema.Part> = [];\n\tconst add = (part: PromptSchema.Part) => {\n\t\tconst last = parts.at(-1);\n\t\tif (part.type === \"text\" && last?.type === \"text\")\n\t\t\tparts[parts.length - 1] = { ...last, text: `${last.text}\\n\\n${part.text}` };\n\t\telse parts.push(part);\n\t};\n\tfor (const block of blocks) {\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\tadd({ type: \"text\", text: block.text });\n\t\t\t\tbreak;\n\t\t\tcase \"resource_link\":\n\t\t\t\tadd({ type: \"text\", text: `[${block.name}](${block.uri})` });\n\t\t\t\tbreak;\n\t\t\tcase \"image\":\n\t\t\t\tadd({ type: \"image\", data: block.data, mimeType: block.mimeType });\n\t\t\t\tbreak;\n\t\t\tcase \"resource\":\n\t\t\t\tif (\"text\" in block.resource) {\n\t\t\t\t\tadd({ type: \"text\", text: `\\`\\`\\`${block.resource.uri}\\n${block.resource.text}\\n\\`\\`\\`` });\n\t\t\t\t} else if (block.resource.mimeType?.startsWith(\"image/\")) {\n\t\t\t\t\tadd({ type: \"image\", data: block.resource.blob, mimeType: block.resource.mimeType });\n\t\t\t\t} else {\n\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unsupported binary resource: ${block.resource.uri}`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unsupported prompt content: ${block.type}`);\n\t\t}\n\t}\n\treturn parts;\n});\n\nconst threadId = (id: string) => Session.ThreadSchema.ID.make(id);\n\ntype Services = Layer.Success<ReturnType<typeof Harness.layer>>;\n\nexport const make = Effect.gen(function* () {\n\tconst control = yield* Control.Service;\n\tconst sessions = yield* SessionStore.Service;\n\tconst threads = yield* ThreadStore.Service;\n\t// Handlers run on the agent's fibers, outside this layer; they carry the harness with them.\n\tconst context = yield* Effect.context<Services>();\n\n\tconst running = new Set<string>();\n\n\t// Every thread is an ACP session of its own. The main thread keeps the CodeWork session's id,\n\t// so a session an editor knew before it had forks still loads; any other thread goes by its id.\n\tconst acpId = (thread: { readonly originKind: string; readonly sessionId: string; readonly id: string }) =>\n\t\tthread.originKind === \"main\" ? thread.sessionId : thread.id;\n\n\t/** The CodeWork session and thread an ACP session id names. */\n\tconst resolve = Effect.fn(\"ACP.resolve\")(function* (id: string) {\n\t\tconst session = yield* sessions.get(id);\n\t\tif (Option.isSome(session)) {\n\t\t\tconst main = yield* threads.main(session.value.id);\n\t\t\tif (Option.isSome(main)) return { session: session.value, threadId: threadId(main.value.id) };\n\t\t}\n\t\tconst thread = yield* threads.get(id);\n\t\tif (Option.isSome(thread)) {\n\t\t\tconst owner = yield* sessions.get(thread.value.sessionId);\n\t\t\tif (Option.isSome(owner)) return { session: owner.value, threadId: threadId(thread.value.id) };\n\t\t}\n\t\treturn yield* new SessionStore.SessionNotFoundError({ sessionId: id });\n\t});\n\n\tconst attach = Effect.fn(\"ACP.attach\")(function* (id: string) {\n\t\tconst { session, threadId } = yield* resolve(id);\n\t\tconst thread = yield* Session.attach({ sessionId: session.id, threadId });\n\t\treturn { thread, hostDir: Option.getOrUndefined(session.hostDir) };\n\t});\n\n\treturn (client: Agent.Client): Agent.Handlers => {\n\t\tconst run = <A, E extends { readonly message: string }>(effect: Effect.Effect<A, E, Services>) =>\n\t\t\teffect.pipe(Effect.provide(context), Effect.mapError(toRequestError));\n\n\t\treturn {\n\t\t\tinitialize: () =>\n\t\t\t\tEffect.succeed({\n\t\t\t\t\tprotocolVersion: 1,\n\t\t\t\t\tagentInfo: { name: \"codework\", version: pkg.version },\n\t\t\t\t\tagentCapabilities: {\n\t\t\t\t\t\tloadSession: true,\n\t\t\t\t\t\tpromptCapabilities: { embeddedContext: true, image: true },\n\t\t\t\t\t\tsessionCapabilities: { list: {}, fork: {} },\n\t\t\t\t\t},\n\t\t\t\t}),\n\n\t\t\tnewSession: ({ cwd }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst handle = yield* Session.create({ directory: cwd, hostDir: cwd });\n\t\t\t\t\t\tconst current = yield* Session.configuration(handle.main.id);\n\t\t\t\t\t\treturn { sessionId: handle.id, configOptions: yield* Config.options(current, cwd) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tloadSession: ({ sessionId: id }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { thread, hostDir } = yield* attach(id);\n\t\t\t\t\t\tconst current = yield* Session.configuration(thread.id);\n\t\t\t\t\t\t// A fork replays its whole line, the part it inherits included.\n\t\t\t\t\t\tfor (const entry of yield* thread.history()) {\n\t\t\t\t\t\t\tfor (const update of Feed.replay(entry)) {\n\t\t\t\t\t\t\t\tyield* client.sessionUpdate({ sessionId: id, update });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { configOptions: yield* Config.options(current, hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tlistSessions: ({ cwd, cursor }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst owners = new Map((yield* sessions.list()).map((row) => [row.id, row]));\n\t\t\t\t\t\tconst all = yield* threads.list();\n\t\t\t\t\t\tconst titles = new Map(all.map((thread) => [thread.id, Option.getOrUndefined(thread.title)]));\n\t\t\t\t\t\tconst rows = all\n\t\t\t\t\t\t\t.flatMap((thread) => {\n\t\t\t\t\t\t\t\tconst session = owners.get(thread.sessionId);\n\t\t\t\t\t\t\t\treturn session === undefined ? [] : [{ thread, session }];\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.filter(({ session }) => cwd == null || Option.getOrUndefined(session.hostDir) === cwd)\n\t\t\t\t\t\t\t.sort((a, b) =>\n\t\t\t\t\t\t\t\tDateTime.Order(\n\t\t\t\t\t\t\t\t\tb.thread.updatedAt ?? b.thread.createdAt,\n\t\t\t\t\t\t\t\t\ta.thread.updatedAt ?? a.thread.createdAt,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst offset = cursor == null ? 0 : Number(cursor);\n\t\t\t\t\t\tif (!Number.isSafeInteger(offset) || offset < 0) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Invalid cursor: ${cursor}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst next = offset + PAGE_SIZE;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsessions: rows.slice(offset, next).map(({ thread, session }) => ({\n\t\t\t\t\t\t\t\tsessionId: acpId(thread),\n\t\t\t\t\t\t\t\tcwd: Option.getOrElse(session.hostDir, () => session.directory),\n\t\t\t\t\t\t\t\t// A fork is untitled until its own first prompt; it reads as its source until then.\n\t\t\t\t\t\t\t\ttitle:\n\t\t\t\t\t\t\t\t\ttitles.get(thread.id) ??\n\t\t\t\t\t\t\t\t\tOption.match(thread.originThreadId, {\n\t\t\t\t\t\t\t\t\t\tonNone: () => undefined,\n\t\t\t\t\t\t\t\t\t\tonSome: (origin) => titles.get(origin),\n\t\t\t\t\t\t\t\t\t}) ??\n\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\tupdatedAt: DateTime.formatIso(thread.updatedAt ?? thread.createdAt),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t...(next < rows.length ? { nextCursor: String(next) } : {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tforkSession: ({ sessionId: id }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { thread, hostDir } = yield* attach(id);\n\t\t\t\t\t\t// ACP forks the conversation as it stands: at its last committed entry, of any type, so\n\t\t\t\t\t\t// a trailing tool result or compaction comes along.\n\t\t\t\t\t\tconst last = (yield* thread.history()).findLast(({ entry }) => entry.state === \"committed\");\n\t\t\t\t\t\tif (last === undefined) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidRequest(\n\t\t\t\t\t\t\t\t\"Nothing to fork yet: the session has no messages\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst forked = yield* thread.fork({ entryId: last.entry.id });\n\t\t\t\t\t\tconst current = yield* Session.configuration(forked.thread.id);\n\t\t\t\t\t\treturn { sessionId: forked.thread.id, configOptions: yield* Config.options(current, hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tsetConfigOption: (request) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { session, threadId } = yield* resolve(request.sessionId);\n\t\t\t\t\t\tconst hostDir = Option.getOrUndefined(session.hostDir);\n\t\t\t\t\t\tconst value = String(request.value);\n\t\t\t\t\t\tlet runtime: Session.RuntimeInput;\n\t\t\t\t\t\tif (request.configId === Config.MODEL) {\n\t\t\t\t\t\t\tconst model = Option.getOrUndefined(Config.parseModel(value));\n\t\t\t\t\t\t\tif (model === undefined || !(yield* Config.known(model, hostDir))) {\n\t\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown model: ${value}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\truntime = { model };\n\t\t\t\t\t\t} else if (request.configId === Config.THOUGHT_LEVEL) {\n\t\t\t\t\t\t\tif (!Config.isThinkingLevel(value)) {\n\t\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown thinking level: ${value}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\truntime = { thinkingLevel: value };\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown config option: ${request.configId}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst thread = yield* Session.attach({ sessionId: session.id, threadId, ...runtime });\n\t\t\t\t\t\treturn { configOptions: yield* Config.options(yield* Session.configuration(thread.id), hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tprompt: ({ sessionId: id, prompt }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst parts = yield* promptParts(prompt);\n\t\t\t\t\t\tconst { thread: handle } = yield* attach(id);\n\t\t\t\t\t\t// Keyed by thread: main answers to its session id and its own thread id alike.\n\t\t\t\t\t\tif (running.has(handle.id)) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidRequest(\"A prompt is already running for this session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\trunning.add(handle.id);\n\t\t\t\t\t\tyield* Effect.addFinalizer(() => Effect.sync(() => running.delete(handle.id)));\n\n\t\t\t\t\t\t// Forward this execution's updates until it settles; the settling event decides the answer.\n\t\t\t\t\t\tlet reason: EventList.LLMEnded[\"data\"][\"reason\"] | undefined;\n\t\t\t\t\t\t// Plugins are checked every exchange; tell the user about each failure once per prompt.\n\t\t\t\t\t\tconst notices = new Set<string>();\n\t\t\t\t\t\tconst settled = yield* handle.events().pipe(\n\t\t\t\t\t\t\tStream.tap((event) => {\n\t\t\t\t\t\t\t\tif (isLLMEnded(event)) reason = event.data.reason;\n\t\t\t\t\t\t\t\tlet update = Feed.update(event);\n\t\t\t\t\t\t\t\tconst notice = Feed.notice(event);\n\t\t\t\t\t\t\t\tif (Option.isSome(notice) && !notices.has(notice.value)) {\n\t\t\t\t\t\t\t\t\tnotices.add(notice.value);\n\t\t\t\t\t\t\t\t\tupdate = Option.some(Feed.noticeUpdate(notice.value));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn Option.match(update, {\n\t\t\t\t\t\t\t\t\tonNone: () => Effect.void,\n\t\t\t\t\t\t\t\t\tonSome: (update) => client.sessionUpdate({ sessionId: id, update }).pipe(Effect.ignore),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tStream.filter(EventList.isRunEnded),\n\t\t\t\t\t\t\tStream.runHead,\n\t\t\t\t\t\t\tEffect.forkScoped({ startImmediately: true }),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst before = (yield* handle.info).title;\n\t\t\t\t\t\tyield* handle.run({ parts });\n\t\t\t\t\t\tconst end = yield* Fiber.join(settled);\n\n\t\t\t\t\t\t// The harness titles a thread from its first prompt; tell the editor.\n\t\t\t\t\t\tconst { title } = yield* handle.info;\n\t\t\t\t\t\tif (title !== undefined && title !== before) {\n\t\t\t\t\t\t\tyield* client\n\t\t\t\t\t\t\t\t.sessionUpdate({ sessionId: id, update: { sessionUpdate: \"session_info_update\", title } })\n\t\t\t\t\t\t\t\t.pipe(Effect.ignore);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (Option.isNone(end) || isInterrupted(end.value)) return { stopReason: \"cancelled\" as const };\n\t\t\t\t\t\tif (isFailed(end.value)) return yield* Agent.RequestError.internalError(end.value.data.error.message);\n\t\t\t\t\t\tif (isRunFailed(end.value)) {\n\t\t\t\t\t\t\tconst { reason, message } = end.value.data;\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.internalError(message, { reason });\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { stopReason: reason === \"length\" ? (\"max_tokens\" as const) : (\"end_turn\" as const) };\n\t\t\t\t\t}).pipe(Effect.scoped),\n\t\t\t\t),\n\n\t\t\tcancel: ({ sessionId: id }) =>\n\t\t\t\tresolve(id).pipe(\n\t\t\t\t\tEffect.flatMap((found) => control.interrupt(found.threadId, { reason: \"user\" })),\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.provide(context),\n\t\t\t\t),\n\t\t};\n\t};\n});\n","import { Control, Harness, Sandbox } from \"@codeworksh/harness/effect\";\nimport { Effect, Logger, Stdio } from \"effect\";\nimport * as Agent from \"./agent.ts\";\nimport * as Handlers from \"./handlers.ts\";\n\n// Sessions and managed sandboxes outlive any single request; the connection's end is what stops them.\nconst shutdown = Effect.gen(function* () {\n\tconst control = yield* Control.Service;\n\tyield* Effect.forEach(\n\t\tyield* control.active,\n\t\t(id) =>\n\t\t\tcontrol\n\t\t\t\t.interrupt(id, { reason: \"shutdown\", awaitSettlement: true })\n\t\t\t\t.pipe(Effect.timeout(\"10 seconds\"), Effect.ignore),\n\t\t{ concurrency: \"unbounded\", discard: true },\n\t);\n\tconst managed = (yield* Sandbox.list()).filter((info) => info.ownership === \"managed\");\n\tyield* Effect.forEach(\n\t\tmanaged,\n\t\t(info) =>\n\t\t\tSandbox.stop(info.id).pipe(\n\t\t\t\tEffect.timeout(\"10 seconds\"),\n\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\tEffect.logError(\"Failed to stop managed sandbox during ACP shutdown\", cause).pipe(\n\t\t\t\t\t\tEffect.annotateLogs({ sandboxInstanceId: info.id }),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t{ concurrency: \"unbounded\", discard: true },\n\t);\n});\n\n/**\n * Serves ACP v1 on stdio until the client disconnects.\n *\n * stdout carries the protocol, so logs go to stderr. The reference is set outside the harness layer\n * so the fibers it forks (turns, plugin loads) inherit it too.\n */\nexport const serve = (options: Harness.Options) =>\n\tEffect.gen(function* () {\n\t\tyield* Effect.addFinalizer(() => shutdown.pipe(Effect.ignore));\n\t\tconst handlers = yield* Handlers.make;\n\t\tyield* Agent.serve(yield* Stdio.Stdio, handlers);\n\t}).pipe(Effect.scoped, Effect.provide(Harness.layer(options)), Effect.provideService(Logger.LogToStderr, true));\n","import { Effect } from \"effect\";\nimport * as Server from \"../../../acp/server.ts\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport { reportFailure } from \"../../error.ts\";\nimport { harnessOptions } from \"../../harness.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.acp,\n\tEffect.fn(\"CLI.acp\", { level: \"Info\" })(function* () {\n\t\tconst shared = yield* Cmd.spec;\n\t\treturn yield* Server.serve(harnessOptions(shared)).pipe(Effect.catch(reportFailure));\n\t}),\n);\n"],"mappings":";;;;;;;;;;AAIA,IAAa,eAAb,MAAa,qBAAqB,OAAO,YAA0B,CAAC,CAAC,mBAAmB;CACvF,MAAM,OAAO;CACb,SAAS,OAAO;CAChB,MAAM,OAAO,YAAY,OAAO,IAAI;AACrC,CAAC,CAAC,CAAC;CACF,OAAO,kBAAkB,YAAoB,IAAI,aAAa;EAAE,MAAM;EAAQ;CAAQ,CAAC;CACvF,OAAO,iBAAiB,YAAoB,IAAI,aAAa;EAAE,MAAM;EAAQ;CAAQ,CAAC;CACtF,OAAO,iBAAiB,SAAiB,SACxC,IAAI,aAAa;EAAE,MAAM;EAAQ;EAAS,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;CAAG,CAAC;CACpF,OAAO,oBAAoB,YAAoB,IAAI,aAAa;EAAE,MAAM;EAAQ;CAAQ,CAAC;AAC1F;;;;;;;AA2BA,MAAaA,UAAQ,OAAO,GAAG,WAAW,CAAC,CAAC,WAC3C,OACA,cAC6C;CAC7C,MAAM,UAAU,OAAO,OAAO,QAAe;CAC7C,MAAM,UAAU,OAAO,mBAAmB,OAAO;CACjD,MAAM,SAAS,OAAO,SAAS,KAA0B;CAEzD,MAAM,WAAW,aAAa,EAC7B,gBAAgB,iBACf,SAAS,MAAM,MAAM,CAAC,CAAC,KACtB,OAAO,SAAS,eACf,OAAO,WAAW;EACjB,WAAW,WAAW,OAAO,OAAO,IAAI,QAAQ,OAA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G,OAAO,eAAe,OAAO,aAAa,IAAI,CAAC;;;ACpC/G,IAAA,cAAeC,QACd,IAAI,SAAS,KACb,OAAO,GAAG,WAAW,EAAE,OAAO,OAAO,CAAC,CAAC,CAAC,aAAa;CACpD,MAAM,SAAS,OAAO,IAAI;CAC1B,OAAO,OAAOC,MAAa,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,aAAa,CAAC;AACpF,CAAC,CACF"}
1
+ {"version":3,"file":"acp-CrNOJRGe.mjs","names":["serve","Agent.RequestError","pkg.version","Config.options","Feed.replay","Config.parseModel","Config.known","Config.isThinkingLevel","update","Feed.update","notice","Feed.notice","Feed.noticeUpdate","Handlers.make","Agent.serve","Runtime.handler","Server.serve"],"sources":["../../src/acp/agent.ts","../../src/acp/config.ts","../../src/acp/feed.ts","../../src/acp/handlers.ts","../../src/acp/server.ts","../../src/cli/cmd/handlers/acp.ts"],"sourcesContent":["import * as Acp from \"@agentclientprotocol/sdk\";\nimport { Cause, Deferred, Effect, Exit, Option, Schema, type Scope, type Stdio, Stream } from \"effect\";\n\n/** A JSON-RPC error a handler answers a request with. */\nexport class RequestError extends Schema.TaggedError<RequestError>()(\"AcpRequestError\", {\n\tcode: Schema.Int,\n\tmessage: Schema.String,\n\tdata: Schema.optionalKey(Schema.Json),\n}) {\n\tstatic invalidRequest = (message: string) => new RequestError({ code: -32600, message });\n\tstatic invalidParams = (message: string) => new RequestError({ code: -32602, message });\n\tstatic internalError = (message: string, data?: Schema.Json) =>\n\t\tnew RequestError({ code: -32603, message, ...(data === undefined ? {} : { data }) });\n\tstatic resourceNotFound = (message: string) => new RequestError({ code: -32002, message });\n}\n\ntype Handler<Request, Response> = (request: Request) => Effect.Effect<Response, RequestError>;\n\n/** Calls the agent makes to the connected client. */\nexport interface Client {\n\treadonly sessionUpdate: (notification: Acp.SessionNotification) => Effect.Effect<void, RequestError>;\n}\n\nexport interface Handlers {\n\treadonly initialize: Handler<Acp.InitializeRequest, Acp.InitializeResponse>;\n\treadonly newSession: Handler<Acp.NewSessionRequest, Acp.NewSessionResponse>;\n\t/** Must replay the session's history through `Client.sessionUpdate` before it returns. */\n\treadonly loadSession: Handler<Acp.LoadSessionRequest, Acp.LoadSessionResponse>;\n\treadonly listSessions: Handler<Acp.ListSessionsRequest, Acp.ListSessionsResponse>;\n\treadonly forkSession: Handler<Acp.ForkSessionRequest, Acp.ForkSessionResponse>;\n\treadonly setConfigOption: Handler<Acp.SetSessionConfigOptionRequest, Acp.SetSessionConfigOptionResponse>;\n\treadonly prompt: Handler<Acp.PromptRequest, Acp.PromptResponse>;\n\treadonly cancel: (notification: Acp.CancelNotification) => Effect.Effect<void>;\n}\n\n/**\n * Serves an ACP agent over `stdio` until the client closes its end.\n *\n * Handlers run as fibers on this effect's services; a request the client cancels, or the\n * connection closing, interrupts its fiber.\n */\nexport const serve = Effect.fn(\"ACP.serve\")(function* (\n\tstdio: Stdio.Stdio,\n\tmakeHandlers: (client: Client) => Handlers,\n): Effect.fn.Return<void, never, Scope.Scope> {\n\tconst context = yield* Effect.context<never>();\n\tconst runExit = Effect.runPromiseExitWith(context);\n\tconst opened = yield* Deferred.make<Acp.AgentConnection>();\n\n\tconst handlers = makeHandlers({\n\t\tsessionUpdate: (notification) =>\n\t\t\tDeferred.await(opened).pipe(\n\t\t\t\tEffect.flatMap((connection) =>\n\t\t\t\t\tEffect.tryPromise({\n\t\t\t\t\t\ttry: () => connection.client.notify(Acp.methods.client.session.update, notification),\n\t\t\t\t\t\tcatch: (error) => RequestError.internalError(`Failed to send session/update: ${String(error)}`),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t),\n\t});\n\n\t// A JSON-RPC answer for a handler that didn't succeed; the SDK sends what `handle` throws.\n\tconst toWire = (cause: Cause.Cause<RequestError>): Acp.RequestError => {\n\t\tconst error = Cause.findErrorOption(cause);\n\t\tif (Option.isSome(error)) return new Acp.RequestError(error.value.code, error.value.message, error.value.data);\n\t\tif (Cause.hasInterruptsOnly(cause)) return Acp.RequestError.requestCancelled();\n\t\treturn Acp.RequestError.internalError(undefined, String(Cause.squash(cause)));\n\t};\n\tconst handle =\n\t\t<Params, A>(handler: (params: Params) => Effect.Effect<A, RequestError>) =>\n\t\t({ params, signal }: { readonly params: Params; readonly signal: AbortSignal }): Promise<A> =>\n\t\t\trunExit(handler(params), { signal }).then((exit) => {\n\t\t\t\tif (Exit.isSuccess(exit)) return exit.value;\n\t\t\t\tthrow toWire(exit.cause);\n\t\t\t});\n\n\tconst input = yield* Stream.toReadableStreamEffect(stdio.stdin);\n\tconst output = new WritableStream<Uint8Array>({\n\t\twrite: (chunk) => Effect.runPromiseWith(context)(Stream.run(Stream.make(chunk), stdio.stdout())),\n\t});\n\n\tconst connection = Acp.agent({ name: \"codework\" })\n\t\t.onRequest(\"initialize\", handle(handlers.initialize))\n\t\t.onRequest(\"session/new\", handle(handlers.newSession))\n\t\t.onRequest(\"session/load\", handle(handlers.loadSession))\n\t\t.onRequest(\"session/list\", handle(handlers.listSessions))\n\t\t.onRequest(\"session/fork\", handle(handlers.forkSession))\n\t\t.onRequest(\"session/set_config_option\", handle(handlers.setConfigOption))\n\t\t.onRequest(\"session/prompt\", handle(handlers.prompt))\n\t\t.onNotification(\"session/cancel\", handle(handlers.cancel))\n\t\t.connect(Acp.ndJsonStream(output, input));\n\tyield* Deferred.succeed(opened, connection);\n\tyield* Effect.addFinalizer(() => Effect.sync(() => connection.close()));\n\tyield* Effect.promise(() => connection.closed);\n});\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport { Model } from \"@codeworksh/aikit\";\nimport { ModelCatalog, Settings, type State } from \"@codeworksh/harness/effect\";\nimport { Effect, Option } from \"effect\";\n\nexport const MODEL = \"model\";\nexport const THOUGHT_LEVEL = \"thought_level\";\n\nconst thinkingLabels: Record<Model.ThinkingLevel, string> = {\n\toff: \"Off\",\n\tminimal: \"Minimal\",\n\tlow: \"Low\",\n\tmedium: \"Medium\",\n\thigh: \"High\",\n\txhigh: \"Extra High\",\n\tmax: \"Max\",\n};\n\nexport const isThinkingLevel = (value: string): value is Model.ThinkingLevel => Object.hasOwn(thinkingLabels, value);\n\n/** Splits a `provider/model` option value on its first slash; model ids may contain more. */\nexport const parseModel = (value: string): Option.Option<{ readonly provider: string; readonly id: string }> => {\n\tconst slash = value.indexOf(\"/\");\n\tif (slash <= 0 || slash === value.length - 1) return Option.none();\n\treturn Option.some({ provider: value.slice(0, slash), id: value.slice(slash + 1) });\n};\n\n/** The catalog a session in `hostDir` sees: generated entries plus its settings' `models`. */\nconst catalogFor = (hostDir: string | undefined) =>\n\tEffect.gen(function* () {\n\t\tconst settings = yield* Settings.Service;\n\t\treturn yield* ModelCatalog.effective((yield* settings.load(hostDir)).models);\n\t}).pipe(Effect.orElseSucceed((): Model.BuiltInModels => ({})));\n\n/** The `model` and `thought_level` selectors for a session's current configuration. */\nexport const options = Effect.fn(\"ACP.config.options\")(function* (\n\tselection: State.Configuration,\n\thostDir: string | undefined,\n) {\n\tconst catalog = yield* catalogFor(hostDir);\n\t// Providers the harness has credentials for; the current model stays selectable even if not.\n\tconst providers = yield* ModelCatalog.available(hostDir === undefined ? {} : { hostDir }).pipe(\n\t\tEffect.orElseSucceed(() => []),\n\t);\n\n\tconst current = `${selection.provider}/${selection.model}`;\n\tconst models = providers.flatMap((provider) =>\n\t\tObject.entries(provider.models).map(([id, info]) => ({\n\t\t\tvalue: `${provider.id}/${id}`,\n\t\t\tname: `${info.provider.name}: ${info.name}`,\n\t\t})),\n\t);\n\tif (!models.some((option) => option.value === current)) models.unshift({ value: current, name: current });\n\n\tconst result: Array<Acp.SessionConfigOption> = [\n\t\t{ id: MODEL, name: \"Model\", category: \"model\", type: \"select\", currentValue: current, options: models },\n\t];\n\n\tconst info = catalog[selection.provider]?.[selection.model];\n\tconst levels = info === undefined ? [] : Model.getSupportedThinkingLevels(info);\n\tif (levels.some((level) => level !== \"off\")) {\n\t\tresult.push({\n\t\t\tid: THOUGHT_LEVEL,\n\t\t\tname: \"Thinking Effort\",\n\t\t\tcategory: \"thought_level\",\n\t\t\ttype: \"select\",\n\t\t\tcurrentValue: selection.thinkingLevel,\n\t\t\toptions: levels.map((level) => ({ value: level, name: thinkingLabels[level] })),\n\t\t});\n\t}\n\treturn result;\n});\n\n/** Whether a model is in the catalog a session in `hostDir` sees. */\nexport const known = Effect.fn(\"ACP.config.known\")(function* (\n\tmodel: { readonly provider: string; readonly id: string },\n\thostDir: string | undefined,\n) {\n\tconst catalog = yield* catalogFor(hostDir);\n\treturn catalog[model.provider]?.[model.id] !== undefined;\n});\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport { EventList, type EventSchema, type ThreadStore } from \"@codeworksh/harness/effect\";\nimport { Option, Schema } from \"effect\";\n\nconst isTextDelta = Schema.is(EventList.LLMTextDelta);\nconst isThinkingDelta = Schema.is(EventList.LLMThinkingDelta);\nconst isToolStarted = Schema.is(EventList.ToolStarted);\nconst isToolSettled = Schema.is(EventList.ToolSettled);\nconst isPluginUpdated = Schema.is(EventList.PluginUpdated);\n\nconst TextContent = Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String });\nconst ImageContent = Schema.Struct({ type: Schema.Literal(\"image\"), data: Schema.String, mimeType: Schema.String });\nconst ToolResult = Schema.Struct({\n\tcontent: Schema.Array(Schema.Union([TextContent, Schema.Struct({ type: Schema.Literal(\"image\") })])),\n\tisError: Schema.Boolean,\n});\nconst ToolCall = Schema.Struct({\n\ttype: Schema.Literal(\"toolCall\"),\n\tcallID: Schema.String,\n\tname: Schema.String,\n\targuments: Schema.Record(Schema.String, Schema.Json),\n\tstatus: Schema.String,\n\tresult: Schema.optional(ToolResult),\n});\nconst StoredPart = Schema.Union([\n\tTextContent,\n\tImageContent,\n\tSchema.Struct({ type: Schema.Literal(\"thinking\"), thinking: Schema.String }),\n\tToolCall,\n]);\nconst decodePart = Schema.decodeUnknownOption(Schema.fromJsonString(StoredPart));\n\ntype ToolCall = typeof ToolCall.Type;\n\nconst text = (value: string): Acp.ContentBlock => ({ type: \"text\", text: value });\n\n// The kind comes from the tool's name. Only `bash` ships built in; plugin tools report `other`.\nconst kind = (name: string): Acp.ToolKind => (name === \"bash\" ? \"execute\" : \"other\");\n\n/** The command for `bash`, otherwise the tool's label or name. */\nconst title = (name: string, args: Readonly<Record<string, unknown>>, label?: string): string =>\n\tname === \"bash\" && typeof args.command === \"string\" ? args.command : (label ?? name);\n\nconst settled = (call: Pick<ToolCall, \"callID\" | \"name\" | \"arguments\" | \"status\" | \"result\">): Acp.SessionUpdate => {\n\tconst output = call.result?.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n\treturn {\n\t\tsessionUpdate: \"tool_call_update\",\n\t\ttoolCallId: call.callID,\n\t\tkind: kind(call.name),\n\t\tstatus: call.status === \"completed\" ? \"completed\" : \"failed\",\n\t\trawInput: call.arguments,\n\t\t...(call.result === undefined ? {} : { rawOutput: call.result }),\n\t\t...(output ? { content: [{ type: \"content\", content: text(output) }] } : {}),\n\t};\n};\n\n/** The live `session/update` for a harness event, if the client should see one. */\nexport const update = (event: EventSchema.Payload): Option.Option<Acp.SessionUpdate> => {\n\tif (isTextDelta(event)) {\n\t\treturn Option.some({ sessionUpdate: \"agent_message_chunk\", content: text(event.data.delta) });\n\t}\n\tif (isThinkingDelta(event)) {\n\t\treturn Option.some({ sessionUpdate: \"agent_thought_chunk\", content: text(event.data.delta) });\n\t}\n\tif (isToolStarted(event)) {\n\t\treturn Option.some({\n\t\t\tsessionUpdate: \"tool_call\",\n\t\t\ttoolCallId: event.data.callID,\n\t\t\ttitle: title(event.data.name, event.data.arguments, event.data.label),\n\t\t\tkind: kind(event.data.name),\n\t\t\tstatus: \"in_progress\",\n\t\t\trawInput: event.data.arguments,\n\t\t});\n\t}\n\tif (isToolSettled(event)) return Option.some(settled(event.data.part));\n\treturn Option.none();\n};\n\n/**\n * Text for the user about a plugin that failed to load, such as one configured but not installed.\n * It belongs in the conversation because the user may never see this process's logs.\n */\nexport const notice = (event: EventSchema.Payload): Option.Option<string> =>\n\tisPluginUpdated(event) && event.data.status === \"failed\" && event.data.error !== undefined\n\t\t? Option.some(event.data.error)\n\t\t: Option.none();\n\n/** A notice shown to the user in the agent's message. */\nexport const noticeUpdate = (notice: string): Acp.SessionUpdate => ({\n\tsessionUpdate: \"agent_message_chunk\",\n\tcontent: text(`> ⚠ ${notice}\\n\\n`),\n});\n\n/** The `session/update`s that replay one stored entry during `session/load`. */\nexport const replay = ({ entry, parts }: ThreadStore.HydratedEntry): ReadonlyArray<Acp.SessionUpdate> => {\n\tif (entry.type !== \"user\" && entry.type !== \"assistant\") return [];\n\treturn parts.flatMap((row): ReadonlyArray<Acp.SessionUpdate> => {\n\t\tconst part = decodePart(row.data);\n\t\tif (Option.isNone(part)) return [];\n\t\tswitch (part.value.type) {\n\t\t\tcase \"text\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: entry.type === \"user\" ? \"user_message_chunk\" : \"agent_message_chunk\",\n\t\t\t\t\t\tcontent: text(part.value.text),\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\tcase \"image\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: entry.type === \"user\" ? \"user_message_chunk\" : \"agent_message_chunk\",\n\t\t\t\t\t\tcontent: { type: \"image\", data: part.value.data, mimeType: part.value.mimeType },\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\tcase \"thinking\":\n\t\t\t\treturn [{ sessionUpdate: \"agent_thought_chunk\", content: text(part.value.thinking) }];\n\t\t\tcase \"toolCall\":\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionUpdate: \"tool_call\",\n\t\t\t\t\t\ttoolCallId: part.value.callID,\n\t\t\t\t\t\ttitle: title(part.value.name, part.value.arguments),\n\t\t\t\t\t\tkind: kind(part.value.name),\n\t\t\t\t\t\tstatus: \"in_progress\",\n\t\t\t\t\t\trawInput: part.value.arguments,\n\t\t\t\t\t},\n\t\t\t\t\tsettled(part.value),\n\t\t\t\t];\n\t\t}\n\t});\n};\n","import type * as Acp from \"@agentclientprotocol/sdk\";\nimport {\n\tControl,\n\tEventList,\n\ttype Harness,\n\tPromptSchema,\n\tSession,\n\tSessionStore,\n\tThreadStore,\n} from \"@codeworksh/harness/effect\";\nimport { DateTime, Effect, Fiber, type Layer, Option, Schema, Stream } from \"effect\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\nimport * as Agent from \"./agent.ts\";\nimport * as Config from \"./config.ts\";\nimport * as Feed from \"./feed.ts\";\n\nconst PAGE_SIZE = 50;\n\nconst isRequestError = Schema.is(Agent.RequestError);\nconst isNotFound = Schema.is(SessionStore.SessionNotFoundError);\nconst isConflict = Schema.is(Control.PromptConflictError);\nconst isInvalidPrompt = Schema.is(PromptSchema.InvalidPromptError);\nconst isLLMEnded = Schema.is(EventList.LLMEnded);\nconst isFailed = Schema.is(EventList.ExecutionFailed);\nconst isInterrupted = Schema.is(EventList.ExecutionInterrupted);\nconst isRunFailed = Schema.is(EventList.RunFailed);\n\n/** Harness failures as JSON-RPC errors; handlers raise protocol-level ones directly. */\nconst toRequestError = (error: { readonly message: string }): Agent.RequestError => {\n\tif (isRequestError(error)) return error;\n\tif (isNotFound(error)) return Agent.RequestError.resourceNotFound(`Session not found: ${error.sessionId}`);\n\tif (isConflict(error)) return Agent.RequestError.invalidRequest(error.message);\n\tif (isInvalidPrompt(error)) return Agent.RequestError.invalidParams(error.message);\n\treturn Agent.RequestError.internalError(error.message);\n};\n\n/**\n * Prompt content as harness prompt parts, in order. Text, embedded context and images are\n * advertised; anything else is rejected. Adjacent text joins into one part. The harness checks\n * the images.\n */\nconst promptParts = Effect.fnUntraced(function* (blocks: ReadonlyArray<Acp.ContentBlock>) {\n\tconst parts: Array<PromptSchema.Part> = [];\n\tconst add = (part: PromptSchema.Part) => {\n\t\tconst last = parts.at(-1);\n\t\tif (part.type === \"text\" && last?.type === \"text\")\n\t\t\tparts[parts.length - 1] = { ...last, text: `${last.text}\\n\\n${part.text}` };\n\t\telse parts.push(part);\n\t};\n\tfor (const block of blocks) {\n\t\tswitch (block.type) {\n\t\t\tcase \"text\":\n\t\t\t\tadd({ type: \"text\", text: block.text });\n\t\t\t\tbreak;\n\t\t\tcase \"resource_link\":\n\t\t\t\tadd({ type: \"text\", text: `[${block.name}](${block.uri})` });\n\t\t\t\tbreak;\n\t\t\tcase \"image\":\n\t\t\t\tadd({ type: \"image\", data: block.data, mimeType: block.mimeType });\n\t\t\t\tbreak;\n\t\t\tcase \"resource\":\n\t\t\t\tif (\"text\" in block.resource) {\n\t\t\t\t\tadd({ type: \"text\", text: `\\`\\`\\`${block.resource.uri}\\n${block.resource.text}\\n\\`\\`\\`` });\n\t\t\t\t} else if (block.resource.mimeType?.startsWith(\"image/\")) {\n\t\t\t\t\tadd({ type: \"image\", data: block.resource.blob, mimeType: block.resource.mimeType });\n\t\t\t\t} else {\n\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unsupported binary resource: ${block.resource.uri}`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unsupported prompt content: ${block.type}`);\n\t\t}\n\t}\n\treturn parts;\n});\n\nconst threadId = (id: string) => Session.ThreadSchema.ID.make(id);\n\ntype Services = Layer.Success<ReturnType<typeof Harness.layer>>;\n\nexport const make = Effect.gen(function* () {\n\tconst control = yield* Control.Service;\n\tconst sessions = yield* SessionStore.Service;\n\tconst threads = yield* ThreadStore.Service;\n\t// Handlers run on the agent's fibers, outside this layer; they carry the harness with them.\n\tconst context = yield* Effect.context<Services>();\n\n\tconst running = new Set<string>();\n\n\t// Every thread is an ACP session of its own. The main thread keeps the CodeWork session's id,\n\t// so a session an editor knew before it had forks still loads; any other thread goes by its id.\n\tconst acpId = (thread: { readonly originKind: string; readonly sessionId: string; readonly id: string }) =>\n\t\tthread.originKind === \"main\" ? thread.sessionId : thread.id;\n\n\t/** The CodeWork session and thread an ACP session id names. */\n\tconst resolve = Effect.fn(\"ACP.resolve\")(function* (id: string) {\n\t\tconst session = yield* sessions.get(id);\n\t\tif (Option.isSome(session)) {\n\t\t\tconst main = yield* threads.main(session.value.id);\n\t\t\tif (Option.isSome(main)) return { session: session.value, threadId: threadId(main.value.id) };\n\t\t}\n\t\tconst thread = yield* threads.get(id);\n\t\tif (Option.isSome(thread)) {\n\t\t\tconst owner = yield* sessions.get(thread.value.sessionId);\n\t\t\tif (Option.isSome(owner)) return { session: owner.value, threadId: threadId(thread.value.id) };\n\t\t}\n\t\treturn yield* new SessionStore.SessionNotFoundError({ sessionId: id });\n\t});\n\n\tconst attach = Effect.fn(\"ACP.attach\")(function* (id: string) {\n\t\tconst { session, threadId } = yield* resolve(id);\n\t\tconst thread = yield* Session.attach({ sessionId: session.id, threadId });\n\t\treturn { thread, hostDir: Option.getOrUndefined(session.hostDir) };\n\t});\n\n\treturn (client: Agent.Client): Agent.Handlers => {\n\t\tconst run = <A, E extends { readonly message: string }>(effect: Effect.Effect<A, E, Services>) =>\n\t\t\teffect.pipe(Effect.provide(context), Effect.mapError(toRequestError));\n\n\t\treturn {\n\t\t\tinitialize: () =>\n\t\t\t\tEffect.succeed({\n\t\t\t\t\tprotocolVersion: 1,\n\t\t\t\t\tagentInfo: { name: \"codework\", version: pkg.version },\n\t\t\t\t\tagentCapabilities: {\n\t\t\t\t\t\tloadSession: true,\n\t\t\t\t\t\tpromptCapabilities: { embeddedContext: true, image: true },\n\t\t\t\t\t\tsessionCapabilities: { list: {}, fork: {} },\n\t\t\t\t\t},\n\t\t\t\t}),\n\n\t\t\tnewSession: ({ cwd }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst handle = yield* Session.create({ directory: cwd, hostDir: cwd });\n\t\t\t\t\t\tconst current = yield* Session.configuration(handle.main.id);\n\t\t\t\t\t\treturn { sessionId: handle.id, configOptions: yield* Config.options(current, cwd) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tloadSession: ({ sessionId: id }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { thread, hostDir } = yield* attach(id);\n\t\t\t\t\t\tconst current = yield* Session.configuration(thread.id);\n\t\t\t\t\t\t// A fork replays its whole line, the part it inherits included.\n\t\t\t\t\t\tfor (const entry of yield* thread.history()) {\n\t\t\t\t\t\t\tfor (const update of Feed.replay(entry)) {\n\t\t\t\t\t\t\t\tyield* client.sessionUpdate({ sessionId: id, update });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { configOptions: yield* Config.options(current, hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tlistSessions: ({ cwd, cursor }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst owners = new Map((yield* sessions.list()).map((row) => [row.id, row]));\n\t\t\t\t\t\tconst all = yield* threads.list();\n\t\t\t\t\t\tconst titles = new Map(all.map((thread) => [thread.id, Option.getOrUndefined(thread.title)]));\n\t\t\t\t\t\tconst rows = all\n\t\t\t\t\t\t\t.flatMap((thread) => {\n\t\t\t\t\t\t\t\tconst session = owners.get(thread.sessionId);\n\t\t\t\t\t\t\t\treturn session === undefined ? [] : [{ thread, session }];\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.filter(({ session }) => cwd == null || Option.getOrUndefined(session.hostDir) === cwd)\n\t\t\t\t\t\t\t.sort((a, b) =>\n\t\t\t\t\t\t\t\tDateTime.Order(\n\t\t\t\t\t\t\t\t\tb.thread.updatedAt ?? b.thread.createdAt,\n\t\t\t\t\t\t\t\t\ta.thread.updatedAt ?? a.thread.createdAt,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst offset = cursor == null ? 0 : Number(cursor);\n\t\t\t\t\t\tif (!Number.isSafeInteger(offset) || offset < 0) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Invalid cursor: ${cursor}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst next = offset + PAGE_SIZE;\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsessions: rows.slice(offset, next).map(({ thread, session }) => ({\n\t\t\t\t\t\t\t\tsessionId: acpId(thread),\n\t\t\t\t\t\t\t\tcwd: Option.getOrElse(session.hostDir, () => session.directory),\n\t\t\t\t\t\t\t\t// A fork is untitled until its own first prompt; it reads as its source until then.\n\t\t\t\t\t\t\t\ttitle:\n\t\t\t\t\t\t\t\t\ttitles.get(thread.id) ??\n\t\t\t\t\t\t\t\t\tOption.match(thread.originThreadId, {\n\t\t\t\t\t\t\t\t\t\tonNone: () => undefined,\n\t\t\t\t\t\t\t\t\t\tonSome: (origin) => titles.get(origin),\n\t\t\t\t\t\t\t\t\t}) ??\n\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\tupdatedAt: DateTime.formatIso(thread.updatedAt ?? thread.createdAt),\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t...(next < rows.length ? { nextCursor: String(next) } : {}),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tforkSession: ({ sessionId: id }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { thread, hostDir } = yield* attach(id);\n\t\t\t\t\t\t// ACP forks the conversation as it stands: at its last committed entry, of any type, so\n\t\t\t\t\t\t// a trailing tool result or compaction comes along.\n\t\t\t\t\t\tconst last = (yield* thread.history()).findLast(({ entry }) => entry.state === \"committed\");\n\t\t\t\t\t\tif (last === undefined) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidRequest(\n\t\t\t\t\t\t\t\t\"Nothing to fork yet: the session has no messages\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst forked = yield* thread.fork({ entryId: last.entry.id });\n\t\t\t\t\t\tconst current = yield* Session.configuration(forked.thread.id);\n\t\t\t\t\t\treturn { sessionId: forked.thread.id, configOptions: yield* Config.options(current, hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tsetConfigOption: (request) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst { session, threadId } = yield* resolve(request.sessionId);\n\t\t\t\t\t\tconst hostDir = Option.getOrUndefined(session.hostDir);\n\t\t\t\t\t\tconst value = String(request.value);\n\t\t\t\t\t\tlet runtime: Session.RuntimeInput;\n\t\t\t\t\t\tif (request.configId === Config.MODEL) {\n\t\t\t\t\t\t\tconst model = Option.getOrUndefined(Config.parseModel(value));\n\t\t\t\t\t\t\tif (model === undefined || !(yield* Config.known(model, hostDir))) {\n\t\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown model: ${value}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\truntime = { model };\n\t\t\t\t\t\t} else if (request.configId === Config.THOUGHT_LEVEL) {\n\t\t\t\t\t\t\tif (!Config.isThinkingLevel(value)) {\n\t\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown thinking level: ${value}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\truntime = { thinkingLevel: value };\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidParams(`Unknown config option: ${request.configId}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst thread = yield* Session.attach({ sessionId: session.id, threadId, ...runtime });\n\t\t\t\t\t\treturn { configOptions: yield* Config.options(yield* Session.configuration(thread.id), hostDir) };\n\t\t\t\t\t}),\n\t\t\t\t),\n\n\t\t\tprompt: ({ sessionId: id, prompt }) =>\n\t\t\t\trun(\n\t\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\t\tconst parts = yield* promptParts(prompt);\n\t\t\t\t\t\tconst { thread: handle } = yield* attach(id);\n\t\t\t\t\t\t// Keyed by thread: main answers to its session id and its own thread id alike.\n\t\t\t\t\t\tif (running.has(handle.id)) {\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.invalidRequest(\"A prompt is already running for this session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\trunning.add(handle.id);\n\t\t\t\t\t\tyield* Effect.addFinalizer(() => Effect.sync(() => running.delete(handle.id)));\n\n\t\t\t\t\t\t// Forward this execution's updates until it settles; the settling event decides the answer.\n\t\t\t\t\t\tlet reason: EventList.LLMEnded[\"data\"][\"reason\"] | undefined;\n\t\t\t\t\t\t// Plugins are checked every exchange; tell the user about each failure once per prompt.\n\t\t\t\t\t\tconst notices = new Set<string>();\n\t\t\t\t\t\tconst settled = yield* handle.events().pipe(\n\t\t\t\t\t\t\tStream.tap((event) => {\n\t\t\t\t\t\t\t\tif (isLLMEnded(event)) reason = event.data.reason;\n\t\t\t\t\t\t\t\tlet update = Feed.update(event);\n\t\t\t\t\t\t\t\tconst notice = Feed.notice(event);\n\t\t\t\t\t\t\t\tif (Option.isSome(notice) && !notices.has(notice.value)) {\n\t\t\t\t\t\t\t\t\tnotices.add(notice.value);\n\t\t\t\t\t\t\t\t\tupdate = Option.some(Feed.noticeUpdate(notice.value));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn Option.match(update, {\n\t\t\t\t\t\t\t\t\tonNone: () => Effect.void,\n\t\t\t\t\t\t\t\t\tonSome: (update) => client.sessionUpdate({ sessionId: id, update }).pipe(Effect.ignore),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tStream.filter(EventList.isRunEnded),\n\t\t\t\t\t\t\tStream.runHead,\n\t\t\t\t\t\t\tEffect.forkScoped({ startImmediately: true }),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst before = (yield* handle.info).title;\n\t\t\t\t\t\tyield* handle.run({ parts });\n\t\t\t\t\t\tconst end = yield* Fiber.join(settled);\n\n\t\t\t\t\t\t// The harness titles a thread from its first prompt; tell the editor.\n\t\t\t\t\t\tconst { title } = yield* handle.info;\n\t\t\t\t\t\tif (title !== undefined && title !== before) {\n\t\t\t\t\t\t\tyield* client\n\t\t\t\t\t\t\t\t.sessionUpdate({ sessionId: id, update: { sessionUpdate: \"session_info_update\", title } })\n\t\t\t\t\t\t\t\t.pipe(Effect.ignore);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (Option.isNone(end) || isInterrupted(end.value)) return { stopReason: \"cancelled\" as const };\n\t\t\t\t\t\tif (isFailed(end.value)) return yield* Agent.RequestError.internalError(end.value.data.error.message);\n\t\t\t\t\t\tif (isRunFailed(end.value)) {\n\t\t\t\t\t\t\tconst { reason, message } = end.value.data;\n\t\t\t\t\t\t\treturn yield* Agent.RequestError.internalError(message, { reason });\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { stopReason: reason === \"length\" ? (\"max_tokens\" as const) : (\"end_turn\" as const) };\n\t\t\t\t\t}).pipe(Effect.scoped),\n\t\t\t\t),\n\n\t\t\tcancel: ({ sessionId: id }) =>\n\t\t\t\tresolve(id).pipe(\n\t\t\t\t\tEffect.flatMap((found) => control.interrupt(found.threadId, { reason: \"user\" })),\n\t\t\t\t\tEffect.ignore,\n\t\t\t\t\tEffect.provide(context),\n\t\t\t\t),\n\t\t};\n\t};\n});\n","import { Control, Harness, Sandbox } from \"@codeworksh/harness/effect\";\nimport { Effect, Logger, Stdio } from \"effect\";\nimport * as Agent from \"./agent.ts\";\nimport * as Handlers from \"./handlers.ts\";\n\n// Sessions and managed sandboxes outlive any single request; the connection's end is what stops them.\nconst shutdown = Effect.gen(function* () {\n\tconst control = yield* Control.Service;\n\tyield* Effect.forEach(\n\t\tyield* control.active,\n\t\t(id) =>\n\t\t\tcontrol\n\t\t\t\t.interrupt(id, { reason: \"shutdown\", awaitSettlement: true })\n\t\t\t\t.pipe(Effect.timeout(\"10 seconds\"), Effect.ignore),\n\t\t{ concurrency: \"unbounded\", discard: true },\n\t);\n\tconst managed = (yield* Sandbox.list()).filter((info) => info.ownership === \"managed\");\n\tyield* Effect.forEach(\n\t\tmanaged,\n\t\t(info) =>\n\t\t\tSandbox.stop(info.id).pipe(\n\t\t\t\tEffect.timeout(\"10 seconds\"),\n\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\tEffect.logError(\"Failed to stop managed sandbox during ACP shutdown\", cause).pipe(\n\t\t\t\t\t\tEffect.annotateLogs({ sandboxInstanceId: info.id }),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t{ concurrency: \"unbounded\", discard: true },\n\t);\n});\n\n/**\n * Serves ACP v1 on stdio until the client disconnects.\n *\n * stdout carries the protocol, so logs go to stderr. The reference is set outside the harness layer\n * so the fibers it forks (turns, plugin loads) inherit it too.\n */\nexport const serve = (options: Harness.Options) =>\n\tEffect.gen(function* () {\n\t\tyield* Effect.addFinalizer(() => shutdown.pipe(Effect.ignore));\n\t\tconst handlers = yield* Handlers.make;\n\t\tyield* Agent.serve(yield* Stdio.Stdio, handlers);\n\t}).pipe(Effect.scoped, Effect.provide(Harness.layer(options)), Effect.provideService(Logger.LogToStderr, true));\n","import { Effect } from \"effect\";\nimport * as Server from \"../../../acp/server.ts\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport { reportFailure } from \"../../error.ts\";\nimport { harnessOptions } from \"../../harness.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.acp,\n\tEffect.fn(\"CLI.acp\", { level: \"Info\" })(function* () {\n\t\tconst shared = yield* Cmd.spec;\n\t\treturn yield* Server.serve(harnessOptions(shared)).pipe(Effect.catch(reportFailure));\n\t}),\n);\n"],"mappings":";;;;;;;;;;AAIA,IAAa,eAAb,MAAa,qBAAqB,OAAO,YAA0B,CAAC,CAAC,mBAAmB;CACvF,MAAM,OAAO;CACb,SAAS,OAAO;CAChB,MAAM,OAAO,YAAY,OAAO,IAAI;AACrC,CAAC,CAAC,CAAC;CACF,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AAO,QAAQ,YAAY,GAAG,OAAO,MAAM,GACnD;EAAE,aAAa;EAAa,SAAS;CAAK,CAC3C;CACA,MAAM,WAAW,OAAO,QAAQ,KAAK,EAAA,CAAG,QAAQ,SAAS,KAAK,cAAc,SAAS;CACrF,OAAO,OAAO,QACb,UACC,SACA,QAAQ,KAAK,KAAK,EAAE,CAAC,CAAC,KACrB,OAAO,QAAQ,YAAY,GAC3B,OAAO,YAAY,UAClB,OAAO,SAAS,sDAAsD,KAAK,CAAC,CAAC,KAC5E,OAAO,aAAa,EAAE,mBAAmB,KAAK,GAAG,CAAC,CACnD,CACD,CACD,GACD;EAAE,aAAa;EAAa,SAAS;CAAK,CAC3C;AACD,CAAC;;;;;;;AAQD,MAAa,SAAS,YACrB,OAAO,IAAI,aAAa;CACvB,OAAO,OAAO,mBAAmB,SAAS,KAAK,OAAO,MAAM,CAAC;CAC7D,MAAM,WAAW,OAAOK;CACxB,OAAOC,QAAY,OAAO,MAAM,OAAO,QAAQ;AAChD,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,QAAQ,QAAQ,MAAM,OAAO,CAAC,GAAG,OAAO,eAAe,OAAO,aAAa,IAAI,CAAC;;;ACpC/G,IAAA,cAAeC,QACd,IAAI,SAAS,KACb,OAAO,GAAG,WAAW,EAAE,OAAO,OAAO,CAAC,CAAC,CAAC,aAAa;CACpD,MAAM,SAAS,OAAO,IAAI;CAC1B,OAAO,OAAOC,MAAa,eAAe,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,aAAa,CAAC;AACpF,CAAC,CACF"}
@@ -1,8 +1,8 @@
1
1
  import { G as WorkspaceId, V as ConnectError, a as reportFailure, m as writeOut, t as InvalidInputError } from "./error-qctchbYS.mjs";
2
2
  import { i as Cmd, t as handler } from "./runtime-BC3hAvn_.mjs";
3
3
  import { n as home } from "./service-bQHXHYll.mjs";
4
- import { n as connect, t as Client } from "./relay-Ccwzl2lc.mjs";
5
- import { t as discover } from "./discovery-CULIX-ah.mjs";
4
+ import { n as connect, t as Client } from "./relay-Bp4GqpdD.mjs";
5
+ import { t as discover } from "./discovery-B9UpJs9z.mjs";
6
6
  import { Effect, Option, Schema } from "effect";
7
7
  //#region ../schema/src/shell.ts
8
8
  /** A path as one shell word: as is when it needs no quoting, else single-quoted. */
@@ -32,4 +32,4 @@ var connect_default = handler(Cmd.commands.connect, Effect.fn("CLI.connect")(fun
32
32
  //#endregion
33
33
  export { connect_default as default };
34
34
 
35
- //# sourceMappingURL=connect-Cwz4fwcc.mjs.map
35
+ //# sourceMappingURL=connect-Bg3kHbrx.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"connect-Cwz4fwcc.mjs","names":["Runtime.handler","Relay.WorkspaceId","Service.home","MachineRelay.connect","Discovery.discover","Machine.ConnectError"],"sources":["../../../schema/src/shell.ts","../../src/cli/cmd/handlers/connect.ts"],"sourcesContent":["/** A path as one shell word: as is when it needs no quoting, else single-quoted. */\nexport const shellQuoted = (path: string) => (/^[\\w./~-]+$/.test(path) ? path : `'${path.replaceAll(\"'\", \"'\\\\''\")}'`);\n","import { Machine, Relay, shellQuoted } from \"@codeworksh/schema\";\nimport { Effect, Option, Schema } from \"effect\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport * as MachineRelay from \"../../../machine/relay.ts\";\nimport * as Discovery from \"../../../server/discovery.ts\";\nimport { InvalidInputError, reportFailure } from \"../../error.ts\";\nimport { writeOut } from \"../../output.ts\";\nimport * as Service from \"../../service.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.connect,\n\tEffect.fn(\"CLI.connect\")(\n\t\tfunction* ({ workspace, machineId }) {\n\t\t\tconst workspaceId = Option.getOrUndefined(workspace);\n\t\t\tif (workspaceId !== undefined && !Schema.is(Relay.WorkspaceId)(workspaceId)) {\n\t\t\t\treturn yield* new InvalidInputError({\n\t\t\t\t\tmessage: \"--workspace must be a Workspace ID; copy it from Settings → Machines in the CodeWork app\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst spec = yield* Cmd.spec;\n\t\t\tconst paths = yield* Service.home(spec);\n\t\t\tconst connected = yield* MachineRelay.connect({\n\t\t\t\thome: paths.home,\n\t\t\t\tworkspaceId,\n\t\t\t\tmachineId: Option.getOrUndefined(machineId),\n\t\t\t\tonCode: (code) => writeOut(`Approve this machine in the CodeWork app with code ${code}\\n`),\n\t\t\t});\n\t\t\tyield* writeOut(`Connected to ${connected.workspace.name}\\n`);\n\t\t\t// The workspace sees a machine online while its server runs; say how when it doesn't yet.\n\t\t\tif ((yield* Discovery.discover(paths.home)) === undefined) {\n\t\t\t\tconst home = Option.match(spec.home, {\n\t\t\t\t\tonNone: () => \"\",\n\t\t\t\t\tonSome: (path) => ` --home ${shellQuoted(path)}`,\n\t\t\t\t});\n\t\t\t\tyield* writeOut(`It shows online once its server runs: codework service start${home}\\n`);\n\t\t\t}\n\t\t},\n\t\tEffect.catchReason(\"HttpClientError\", \"TransportError\", (reason) =>\n\t\t\tEffect.fail(\n\t\t\t\tnew Machine.ConnectError({\n\t\t\t\t\tmessage: `Can't reach Relay servers at ${new URL(reason.request.url).origin}; check your connection, then run connect again`,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tEffect.provide(MachineRelay.Client.layer),\n\t\tEffect.catch(reportFailure),\n\t),\n);\n"],"mappings":";;;;;;;;AACA,MAAa,eAAe,SAAkB,cAAc,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,KAAK,OAAO,EAAE;;;ACSlH,IAAA,kBAAeA,QACd,IAAI,SAAS,SACb,OAAO,GAAG,aAAa,CAAC,CACvB,WAAW,EAAE,WAAW,aAAa;CACpC,MAAM,cAAc,OAAO,eAAe,SAAS;CACnD,IAAI,gBAAgB,KAAA,KAAa,CAAC,OAAO,GAAGC,WAAiB,CAAC,CAAC,WAAW,GACzE,OAAO,OAAO,IAAI,kBAAkB,EACnC,SAAS,2FACV,CAAC;CAEF,MAAM,OAAO,OAAO,IAAI;CACxB,MAAM,QAAQ,OAAOC,KAAa,IAAI;CACtC,MAAM,YAAY,OAAOC,QAAqB;EAC7C,MAAM,MAAM;EACZ;EACA,WAAW,OAAO,eAAe,SAAS;EAC1C,SAAS,SAAS,SAAS,sDAAsD,KAAK,GAAG;CAC1F,CAAC;CACD,OAAO,SAAS,gBAAgB,UAAU,UAAU,KAAK,GAAG;CAE5D,KAAK,OAAOC,SAAmB,MAAM,IAAI,OAAO,KAAA,GAAW;EAC1D,MAAM,OAAO,OAAO,MAAM,KAAK,MAAM;GACpC,cAAc;GACd,SAAS,SAAS,WAAW,YAAY,IAAI;EAC9C,CAAC;EACD,OAAO,SAAS,+DAA+D,KAAK,GAAG;CACxF;AACD,GACA,OAAO,YAAY,mBAAmB,mBAAmB,WACxD,OAAO,KACN,IAAIC,aAAqB,EACxB,SAAS,gCAAgC,IAAI,IAAI,OAAO,QAAQ,GAAG,CAAC,CAAC,OAAO,iDAC7E,CAAC,CACF,CACD,GACA,OAAO,QAAA,OAA4B,KAAK,GACxC,OAAO,MAAM,aAAa,CAC3B,CACD"}
1
+ {"version":3,"file":"connect-Bg3kHbrx.mjs","names":["Runtime.handler","Relay.WorkspaceId","Service.home","MachineRelay.connect","Discovery.discover","Machine.ConnectError"],"sources":["../../../schema/src/shell.ts","../../src/cli/cmd/handlers/connect.ts"],"sourcesContent":["/** A path as one shell word: as is when it needs no quoting, else single-quoted. */\nexport const shellQuoted = (path: string) => (/^[\\w./~-]+$/.test(path) ? path : `'${path.replaceAll(\"'\", \"'\\\\''\")}'`);\n","import { Machine, Relay, shellQuoted } from \"@codeworksh/schema\";\nimport { Effect, Option, Schema } from \"effect\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport * as MachineRelay from \"../../../machine/relay.ts\";\nimport * as Discovery from \"../../../server/discovery.ts\";\nimport { InvalidInputError, reportFailure } from \"../../error.ts\";\nimport { writeOut } from \"../../output.ts\";\nimport * as Service from \"../../service.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.connect,\n\tEffect.fn(\"CLI.connect\")(\n\t\tfunction* ({ workspace, machineId }) {\n\t\t\tconst workspaceId = Option.getOrUndefined(workspace);\n\t\t\tif (workspaceId !== undefined && !Schema.is(Relay.WorkspaceId)(workspaceId)) {\n\t\t\t\treturn yield* new InvalidInputError({\n\t\t\t\t\tmessage: \"--workspace must be a Workspace ID; copy it from Settings → Machines in the CodeWork app\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst spec = yield* Cmd.spec;\n\t\t\tconst paths = yield* Service.home(spec);\n\t\t\tconst connected = yield* MachineRelay.connect({\n\t\t\t\thome: paths.home,\n\t\t\t\tworkspaceId,\n\t\t\t\tmachineId: Option.getOrUndefined(machineId),\n\t\t\t\tonCode: (code) => writeOut(`Approve this machine in the CodeWork app with code ${code}\\n`),\n\t\t\t});\n\t\t\tyield* writeOut(`Connected to ${connected.workspace.name}\\n`);\n\t\t\t// The workspace sees a machine online while its server runs; say how when it doesn't yet.\n\t\t\tif ((yield* Discovery.discover(paths.home)) === undefined) {\n\t\t\t\tconst home = Option.match(spec.home, {\n\t\t\t\t\tonNone: () => \"\",\n\t\t\t\t\tonSome: (path) => ` --home ${shellQuoted(path)}`,\n\t\t\t\t});\n\t\t\t\tyield* writeOut(`It shows online once its server runs: codework service start${home}\\n`);\n\t\t\t}\n\t\t},\n\t\tEffect.catchReason(\"HttpClientError\", \"TransportError\", (reason) =>\n\t\t\tEffect.fail(\n\t\t\t\tnew Machine.ConnectError({\n\t\t\t\t\tmessage: `Can't reach Relay servers at ${new URL(reason.request.url).origin}; check your connection, then run connect again`,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t\tEffect.provide(MachineRelay.Client.layer),\n\t\tEffect.catch(reportFailure),\n\t),\n);\n"],"mappings":";;;;;;;;AACA,MAAa,eAAe,SAAkB,cAAc,KAAK,IAAI,IAAI,OAAO,IAAI,KAAK,WAAW,KAAK,OAAO,EAAE;;;ACSlH,IAAA,kBAAeA,QACd,IAAI,SAAS,SACb,OAAO,GAAG,aAAa,CAAC,CACvB,WAAW,EAAE,WAAW,aAAa;CACpC,MAAM,cAAc,OAAO,eAAe,SAAS;CACnD,IAAI,gBAAgB,KAAA,KAAa,CAAC,OAAO,GAAGC,WAAiB,CAAC,CAAC,WAAW,GACzE,OAAO,OAAO,IAAI,kBAAkB,EACnC,SAAS,2FACV,CAAC;CAEF,MAAM,OAAO,OAAO,IAAI;CACxB,MAAM,QAAQ,OAAOC,KAAa,IAAI;CACtC,MAAM,YAAY,OAAOC,QAAqB;EAC7C,MAAM,MAAM;EACZ;EACA,WAAW,OAAO,eAAe,SAAS;EAC1C,SAAS,SAAS,SAAS,sDAAsD,KAAK,GAAG;CAC1F,CAAC;CACD,OAAO,SAAS,gBAAgB,UAAU,UAAU,KAAK,GAAG;CAE5D,KAAK,OAAOC,SAAmB,MAAM,IAAI,OAAO,KAAA,GAAW;EAC1D,MAAM,OAAO,OAAO,MAAM,KAAK,MAAM;GACpC,cAAc;GACd,SAAS,SAAS,WAAW,YAAY,IAAI;EAC9C,CAAC;EACD,OAAO,SAAS,+DAA+D,KAAK,GAAG;CACxF;AACD,GACA,OAAO,YAAY,mBAAmB,mBAAmB,WACxD,OAAO,KACN,IAAIC,aAAqB,EACxB,SAAS,gCAAgC,IAAI,IAAI,OAAO,QAAQ,GAAG,CAAC,CAAC,OAAO,iDAC7E,CAAC,CACF,CACD,GACA,OAAO,QAAA,OAA4B,KAAK,GACxC,OAAO,MAAM,aAAa,CAC3B,CACD"}
@@ -1,7 +1,7 @@
1
1
  import { a as reportFailure, m as writeOut, t as InvalidInputError } from "./error-qctchbYS.mjs";
2
2
  import { i as Cmd, t as handler } from "./runtime-BC3hAvn_.mjs";
3
3
  import { n as home } from "./service-bQHXHYll.mjs";
4
- import { c as read, r as disconnect } from "./relay-Ccwzl2lc.mjs";
4
+ import { c as read, r as disconnect } from "./relay-Bp4GqpdD.mjs";
5
5
  import { Effect, Option } from "effect";
6
6
  //#region src/cli/cmd/handlers/disconnect.ts
7
7
  var disconnect_default = handler(Cmd.commands.disconnect, Effect.fn("CLI.disconnect")(function* ({ workspace }) {
@@ -18,4 +18,4 @@ var disconnect_default = handler(Cmd.commands.disconnect, Effect.fn("CLI.disconn
18
18
  //#endregion
19
19
  export { disconnect_default as default };
20
20
 
21
- //# sourceMappingURL=disconnect-D4g8ISX9.mjs.map
21
+ //# sourceMappingURL=disconnect-hDfEVmWt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"disconnect-D4g8ISX9.mjs","names":["Runtime.handler","Service.home","File.read","Relay.disconnect"],"sources":["../../src/cli/cmd/handlers/disconnect.ts"],"sourcesContent":["import { Effect, Option } from \"effect\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport * as File from \"../../../machine/file.ts\";\nimport * as Relay from \"../../../machine/relay.ts\";\nimport { InvalidInputError, reportFailure } from \"../../error.ts\";\nimport { writeOut } from \"../../output.ts\";\nimport * as Service from \"../../service.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.disconnect,\n\tEffect.fn(\"CLI.disconnect\")(function* ({ workspace }) {\n\t\tconst paths = yield* Service.home(yield* Cmd.spec);\n\t\tconst connected = Option.match(yield* File.read(paths.home), {\n\t\t\tonNone: () => [],\n\t\t\tonSome: (machine) => Object.keys(machine.workspaces),\n\t\t});\n\t\tconst workspaceId = Option.getOrUndefined(workspace) ?? (connected.length === 1 ? connected[0] : undefined);\n\t\tif (workspaceId === undefined) {\n\t\t\treturn yield* new InvalidInputError({\n\t\t\t\tmessage:\n\t\t\t\t\tconnected.length === 0\n\t\t\t\t\t\t? \"This machine is not connected to any workspace\"\n\t\t\t\t\t\t: `Connected to ${connected.length} workspaces; name one with --workspace (${connected.join(\", \")})`,\n\t\t\t});\n\t\t}\n\t\tconst result = yield* Relay.disconnect(paths.home, workspaceId);\n\t\tyield* writeOut(\n\t\t\tresult.revoked\n\t\t\t\t? `Disconnected from ${result.workspace}\\n`\n\t\t\t\t: `Leaving ${result.workspace}: Relay didn’t confirm, so this machine keeps the link until it does. The server retries while it runs.\\n`,\n\t\t);\n\t}, Effect.catch(reportFailure)),\n);\n"],"mappings":";;;;;;AASA,IAAA,qBAAeA,QACd,IAAI,SAAS,YACb,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAAW,EAAE,aAAa;CACrD,MAAM,QAAQ,OAAOC,KAAa,OAAO,IAAI,IAAI;CACjD,MAAM,YAAY,OAAO,MAAM,OAAOC,KAAU,MAAM,IAAI,GAAG;EAC5D,cAAc,CAAC;EACf,SAAS,YAAY,OAAO,KAAK,QAAQ,UAAU;CACpD,CAAC;CACD,MAAM,cAAc,OAAO,eAAe,SAAS,MAAM,UAAU,WAAW,IAAI,UAAU,KAAK,KAAA;CACjG,IAAI,gBAAgB,KAAA,GACnB,OAAO,OAAO,IAAI,kBAAkB,EACnC,SACC,UAAU,WAAW,IAClB,mDACA,gBAAgB,UAAU,OAAO,0CAA0C,UAAU,KAAK,IAAI,EAAE,GACrG,CAAC;CAEF,MAAM,SAAS,OAAOC,WAAiB,MAAM,MAAM,WAAW;CAC9D,OAAO,SACN,OAAO,UACJ,qBAAqB,OAAO,UAAU,MACtC,WAAW,OAAO,UAAU,0GAChC;AACD,GAAG,OAAO,MAAM,aAAa,CAAC,CAC/B"}
1
+ {"version":3,"file":"disconnect-hDfEVmWt.mjs","names":["Runtime.handler","Service.home","File.read","Relay.disconnect"],"sources":["../../src/cli/cmd/handlers/disconnect.ts"],"sourcesContent":["import { Effect, Option } from \"effect\";\nimport * as Runtime from \"../../../framework/runtime.ts\";\nimport * as File from \"../../../machine/file.ts\";\nimport * as Relay from \"../../../machine/relay.ts\";\nimport { InvalidInputError, reportFailure } from \"../../error.ts\";\nimport { writeOut } from \"../../output.ts\";\nimport * as Service from \"../../service.ts\";\nimport { Cmd } from \"../cmd.ts\";\n\nexport default Runtime.handler(\n\tCmd.commands.disconnect,\n\tEffect.fn(\"CLI.disconnect\")(function* ({ workspace }) {\n\t\tconst paths = yield* Service.home(yield* Cmd.spec);\n\t\tconst connected = Option.match(yield* File.read(paths.home), {\n\t\t\tonNone: () => [],\n\t\t\tonSome: (machine) => Object.keys(machine.workspaces),\n\t\t});\n\t\tconst workspaceId = Option.getOrUndefined(workspace) ?? (connected.length === 1 ? connected[0] : undefined);\n\t\tif (workspaceId === undefined) {\n\t\t\treturn yield* new InvalidInputError({\n\t\t\t\tmessage:\n\t\t\t\t\tconnected.length === 0\n\t\t\t\t\t\t? \"This machine is not connected to any workspace\"\n\t\t\t\t\t\t: `Connected to ${connected.length} workspaces; name one with --workspace (${connected.join(\", \")})`,\n\t\t\t});\n\t\t}\n\t\tconst result = yield* Relay.disconnect(paths.home, workspaceId);\n\t\tyield* writeOut(\n\t\t\tresult.revoked\n\t\t\t\t? `Disconnected from ${result.workspace}\\n`\n\t\t\t\t: `Leaving ${result.workspace}: Relay didn’t confirm, so this machine keeps the link until it does. The server retries while it runs.\\n`,\n\t\t);\n\t}, Effect.catch(reportFailure)),\n);\n"],"mappings":";;;;;;AASA,IAAA,qBAAeA,QACd,IAAI,SAAS,YACb,OAAO,GAAG,gBAAgB,CAAC,CAAC,WAAW,EAAE,aAAa;CACrD,MAAM,QAAQ,OAAOC,KAAa,OAAO,IAAI,IAAI;CACjD,MAAM,YAAY,OAAO,MAAM,OAAOC,KAAU,MAAM,IAAI,GAAG;EAC5D,cAAc,CAAC;EACf,SAAS,YAAY,OAAO,KAAK,QAAQ,UAAU;CACpD,CAAC;CACD,MAAM,cAAc,OAAO,eAAe,SAAS,MAAM,UAAU,WAAW,IAAI,UAAU,KAAK,KAAA;CACjG,IAAI,gBAAgB,KAAA,GACnB,OAAO,OAAO,IAAI,kBAAkB,EACnC,SACC,UAAU,WAAW,IAClB,mDACA,gBAAgB,UAAU,OAAO,0CAA0C,UAAU,KAAK,IAAI,EAAE,GACrG,CAAC;CAEF,MAAM,SAAS,OAAOC,WAAiB,MAAM,MAAM,WAAW;CAC9D,OAAO,SACN,OAAO,UACJ,qBAAqB,OAAO,UAAU,MACtC,WAAW,OAAO,UAAU,0GAChC;AACD,GAAG,OAAO,MAAM,aAAa,CAAC,CAC/B"}
@@ -1,6 +1,6 @@
1
1
  import { g as make, h as layer } from "./error-qctchbYS.mjs";
2
2
  import { i as read, n as file, r as log, t as command } from "./registration-C6yiv31r.mjs";
3
- import { n as current } from "./identity--j8hMb07.mjs";
3
+ import { n as current } from "./identity-DQYgsuek.mjs";
4
4
  import { Effect, FileSystem, Layer, Option, Schedule, Schema } from "effect";
5
5
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
6
6
  //#region src/server/health.ts
@@ -171,4 +171,4 @@ const spawn = (options) => Effect.gen(function* () {
171
171
  //#endregion
172
172
  export { ensure as n, stop as r, discover as t };
173
173
 
174
- //# sourceMappingURL=discovery-CULIX-ah.mjs.map
174
+ //# sourceMappingURL=discovery-B9UpJs9z.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"discovery-CULIX-ah.mjs","names":["Client.layer","Client.make","Registration.read","Health.probe","Registration.file","log","Registration.log","Registration.command"],"sources":["../../src/server/health.ts","../../src/server/discovery.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport * as Client from \"./client.ts\";\n\n/**\n * One `server.info` call, with the answer normalized to `undefined` for every\n * way a server can fail to answer: unreachable, slow, refusing the token, or\n * speaking a different protocol. A health check that throws where it should say\n * \"no\" would make every caller wrap it in a catch.\n */\nexport const probe = (server: Client.Target) =>\n\tEffect.gen(function* () {\n\t\tconst context = yield* Layer.build(Client.layer(server)).pipe(Effect.orElseSucceed(() => undefined));\n\t\tif (context === undefined) return undefined;\n\t\treturn yield* Effect.gen(function* () {\n\t\t\tconst rpc = yield* Client.make;\n\t\t\treturn yield* rpc[\"server.info\"]({}).pipe(Effect.timeout(\"1 second\"));\n\t\t}).pipe(\n\t\t\tEffect.provideContext(context),\n\t\t\tEffect.orElseSucceed(() => undefined),\n\t\t);\n\t}).pipe(Effect.scoped);\n","import { type Duration, Effect, FileSystem, Option, Schedule, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport * as Health from \"./health.ts\";\nimport * as Identity from \"./identity.ts\";\nimport * as Registration from \"./registration.ts\";\n\n/** A server a client can connect to, the process and port behind it, and the token it takes. */\nexport interface Endpoint {\n\treadonly url: string;\n\treadonly pid: number;\n\treadonly port: number;\n\treadonly token: string;\n}\n\n/** A managed server could not be produced, in the words the CLI prints. */\nclass ServerStartError extends Schema.TaggedError<ServerStartError>()(\"Discovery.ServerStartError\", {\n\tmessage: Schema.String,\n}) {}\n\nexport interface Options {\n\t/** The CodeWork home whose `service.json` names the server. */\n\treadonly home: string;\n\t/** The home's log directory, where a background server writes `server.log`. */\n\treadonly log: string;\n\treadonly host: string;\n\treadonly port: number;\n\t/** Server-owned flags placed before `serve`. */\n\treadonly args: ReadonlyArray<string>;\n}\n\nconst START_TIMEOUT = \"20 seconds\";\nconst RACE_GRACE = \"2 seconds\";\nconst STOP_TIMEOUT = \"5 seconds\";\n\nconst remove = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tyield* fs.remove(path);\n\t}).pipe(Effect.ignore);\n\n/** Whether `pid` is a running process. EPERM means it exists but belongs to someone else. */\nconst alive = (pid: number) =>\n\tEffect.try({ try: () => process.kill(pid, 0), catch: (error) => (error as NodeJS.ErrnoException).code }).pipe(\n\t\tEffect.as(true),\n\t\tEffect.catch((code) => Effect.succeed(code === \"EPERM\")),\n\t);\n\n/** Whether `pid` exits within `timeout`. */\nconst exits = (pid: number, timeout: typeof STOP_TIMEOUT) =>\n\talive(pid).pipe(\n\t\tEffect.repeat({ while: (running) => running, schedule: Schedule.spaced(\"50 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.isSome),\n\t);\n\n/**\n * The registered server, with `live` set when the process answering its endpoint\n * is the one that registered. The file is a hint, never proof: a different server\n * on a reused port must not pass for it.\n */\nconst registered = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst info = yield* Registration.read(path);\n\t\tif (info === undefined) return undefined;\n\t\tconst live = yield* Health.probe(info);\n\t\treturn { info, live: live?.pid === info.pid ? live : undefined };\n\t});\n\nconst endpoint = (info: Registration.Info): Endpoint => ({\n\turl: info.url,\n\tpid: info.pid,\n\tport: info.port,\n\ttoken: info.token,\n});\n\n/** The running server registered for `home`, with the build it reports. */\nexport const discover = (home: string) =>\n\tregistered(Registration.file(home)).pipe(\n\t\tEffect.map((found) =>\n\t\t\tfound?.live === undefined ? undefined : { ...endpoint(found.info), version: found.live.version },\n\t\t),\n\t);\n\n/**\n * Stop the server registered for `home`, returning it, or undefined when none\n * answers. Only a server that confirms it is the registrant is signalled: a pid\n * on file may since have been reused by an unrelated process.\n */\nexport const stop = (home: string) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(home);\n\t\tconst found = yield* registered(path);\n\t\tif (found === undefined) return undefined;\n\t\tif (found.live === undefined) {\n\t\t\tif (!(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\treturn undefined;\n\t\t}\n\t\tyield* terminate(path, found.info.pid);\n\t\treturn endpoint(found.info);\n\t});\n\n/**\n * Ensure a healthy local server for `home`: reuse the registered one, replace it\n * when `replace` is set and it runs a different build, or start a background one.\n *\n * The background server is detached and outlives this caller, so the next\n * invocation reuses it. When two callers race, only the contender that binds the\n * port registers; the loser exits and both adopt the winner, because a caller\n * only ever believes a registration it can confirm over the wire.\n */\nexport const ensure = (options: Options & { readonly replace: boolean }) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(options.home);\n\t\tconst found = yield* registered(path);\n\t\tif (found?.live !== undefined) {\n\t\t\tif (!options.replace || found.live.version === Identity.current.version) return endpoint(found.info);\n\t\t\tyield* terminate(path, found.info.pid);\n\t\t} else {\n\t\t\t// A file nothing answers for, left by a crash, must not mislead the next caller.\n\t\t\tif (found !== undefined && !(yield* alive(found.info.pid))) yield* remove(path);\n\t\t}\n\t\treturn yield* start(path, options);\n\t});\n\n/** The registered server once it answers, polled every 200ms for up to `timeout`. */\nconst ready = (path: string, timeout: Duration.Input, pending: Effect.Effect<boolean>) =>\n\tEffect.gen(function* () {\n\t\tconst next = yield* registered(path);\n\t\tif (next?.live !== undefined) return Option.some(endpoint(next.info));\n\t\t// A live registrant that does not answer yet is another caller's server starting up.\n\t\tconst waiting = (yield* pending) || (next !== undefined && (yield* alive(next.info.pid)));\n\t\treturn waiting ? Option.none() : yield* Effect.fail(\"exited\" as const);\n\t}).pipe(\n\t\tEffect.repeat({ until: Option.isSome, schedule: Schedule.spaced(\"200 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.flatten),\n\t\tEffect.orElseSucceed(() => Option.none<Endpoint>()),\n\t);\n\n/**\n * Start a background server and wait for it to register, quoting the reason\n * from its log when it cannot.\n *\n * The contender stays tied to this scope until it is the server adopted: a\n * timeout, an interrupt, or another caller winning the race stops it rather than\n * leaving an unmanaged server behind.\n */\nconst start = (path: string, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst contender = yield* spawn(options);\n\t\tconst won = yield* ready(path, START_TIMEOUT, contender.isRunning.pipe(Effect.orElseSucceed(() => false)));\n\t\t// A contender that lost the bind race exits before the winner may have filed its\n\t\t// registration; give the winner a moment before calling the start a failure.\n\t\tconst server = Option.isSome(won) ? won : yield* ready(path, RACE_GRACE, Effect.succeed(true));\n\t\tif (Option.isSome(server)) {\n\t\t\tif (server.value.pid === contender.pid) yield* contender.unref.pipe(Effect.asVoid);\n\t\t\treturn server.value;\n\t\t}\n\n\t\tconst log = Registration.log(options.log);\n\t\tconst reason = yield* lastLine(log);\n\t\treturn yield* new ServerStartError({\n\t\t\tmessage: [\n\t\t\t\t`could not start a CodeWork server on ${options.host}:${options.port}`,\n\t\t\t\t...(reason === undefined ? [] : [`reason: ${reason}`]),\n\t\t\t\t`log: ${log}`,\n\t\t\t\t\"hint: pass --port to use another port\",\n\t\t\t].join(\"\\n\"),\n\t\t});\n\t}).pipe(Effect.scoped);\n\n/** Ask `pid` to shut down, escalating to SIGKILL, and retire its registration. */\nconst terminate = (path: string, pid: number) =>\n\tEffect.gen(function* () {\n\t\tconst signal = (name: NodeJS.Signals) => Effect.try(() => process.kill(pid, name)).pipe(Effect.ignore);\n\t\tyield* signal(\"SIGTERM\");\n\t\tif (!(yield* exits(pid, STOP_TIMEOUT))) {\n\t\t\tyield* signal(\"SIGKILL\");\n\t\t\tyield* exits(pid, STOP_TIMEOUT);\n\t\t}\n\t\t// A server removes its own file on a clean exit; this covers the SIGKILL path.\n\t\tconst info = yield* Registration.read(path);\n\t\tif (info?.pid === pid) yield* remove(path);\n\t});\n\nconst lastLine = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => \"\"));\n\t\treturn text\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.findLast((line) => line.length > 0);\n\t});\n\n/**\n * Spawn `codework serve --service` detached, inheriting this environment so it\n * resolves the same home, catalog and credentials. It writes its own log, so no\n * stdio is tied to this short-lived caller. It stays referenced, and so stopped\n * with the scope, until `start` adopts it.\n */\nconst spawn = (options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst [file, ...base] = Registration.command();\n\t\tif (file === undefined) return yield* Effect.die(new Error(\"could not resolve the codework entrypoint\"));\n\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\tconst handle = yield* spawner.spawn(\n\t\t\tChildProcess.make(\n\t\t\t\tfile,\n\t\t\t\t[...base, ...options.args, \"serve\", \"--service\", \"--host\", options.host, \"--port\", String(options.port)],\n\t\t\t\t{ detached: true, stdin: \"ignore\", stdout: \"ignore\", stderr: \"ignore\" },\n\t\t\t),\n\t\t);\n\t\treturn handle;\n\t});\n"],"mappings":";;;;;;;;;;;;AASA,MAAa,SAAS,WACrB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,CAAC;AACF,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM;;AAGtB,MAAM,aAAa,MAAc,QAChC,OAAO,IAAI,aAAa;CACvB,MAAM,UAAU,SAAyB,OAAO,UAAU,QAAQ,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM;CACrG,OAAO,OAAO,SAAS;CACvB,IAAI,EAAE,OAAO,MAAM,KAAK,YAAY,IAAI;EACvC,OAAO,OAAO,SAAS;EACvB,OAAO,MAAM,KAAK,YAAY;CAC/B;CAGA,KAAI,OADgBH,KAAkB,IAAI,EAAA,EAChC,QAAQ,KAAK,OAAO,OAAO,IAAI;AAC1C,CAAC;AAEF,MAAM,YAAY,SACjB,OAAO,IAAI,aAAa;CAGvB,QAAO,QADa,OADF,WAAW,WAAA,CACN,eAAe,IAAI,CAAC,CAAC,KAAK,OAAO,oBAAoB,EAAE,CAAC,EAAA,CAE7E,MAAM,IAAI,CAAC,CACX,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,CAC1B,UAAU,SAAS,KAAK,SAAS,CAAC;AACrC,CAAC;;;;;;;AAQF,MAAM,SAAS,YACd,OAAO,IAAI,aAAa;CACvB,MAAM,CAAC,MAAM,GAAG,QAAQK,QAAqB;CAC7C,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,2CAA2C,CAAC;CASvG,OAAO,QAPe,OADC,oBAAoB,oBAAA,CACb,MAC7B,aAAa,KACZ,MACA;EAAC,GAAG;EAAM,GAAG,QAAQ;EAAM;EAAS;EAAa;EAAU,QAAQ;EAAM;EAAU,OAAO,QAAQ,IAAI;CAAC,GACvG;EAAE,UAAU;EAAM,OAAO;EAAU,QAAQ;EAAU,QAAQ;CAAS,CACvE,CACD;AAED,CAAC"}
1
+ {"version":3,"file":"discovery-B9UpJs9z.mjs","names":["Client.layer","Client.make","Registration.read","Health.probe","Registration.file","log","Registration.log","Registration.command"],"sources":["../../src/server/health.ts","../../src/server/discovery.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport * as Client from \"./client.ts\";\n\n/**\n * One `server.info` call, with the answer normalized to `undefined` for every\n * way a server can fail to answer: unreachable, slow, refusing the token, or\n * speaking a different protocol. A health check that throws where it should say\n * \"no\" would make every caller wrap it in a catch.\n */\nexport const probe = (server: Client.Target) =>\n\tEffect.gen(function* () {\n\t\tconst context = yield* Layer.build(Client.layer(server)).pipe(Effect.orElseSucceed(() => undefined));\n\t\tif (context === undefined) return undefined;\n\t\treturn yield* Effect.gen(function* () {\n\t\t\tconst rpc = yield* Client.make;\n\t\t\treturn yield* rpc[\"server.info\"]({}).pipe(Effect.timeout(\"1 second\"));\n\t\t}).pipe(\n\t\t\tEffect.provideContext(context),\n\t\t\tEffect.orElseSucceed(() => undefined),\n\t\t);\n\t}).pipe(Effect.scoped);\n","import { type Duration, Effect, FileSystem, Option, Schedule, Schema } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport * as Health from \"./health.ts\";\nimport * as Identity from \"./identity.ts\";\nimport * as Registration from \"./registration.ts\";\n\n/** A server a client can connect to, the process and port behind it, and the token it takes. */\nexport interface Endpoint {\n\treadonly url: string;\n\treadonly pid: number;\n\treadonly port: number;\n\treadonly token: string;\n}\n\n/** A managed server could not be produced, in the words the CLI prints. */\nclass ServerStartError extends Schema.TaggedError<ServerStartError>()(\"Discovery.ServerStartError\", {\n\tmessage: Schema.String,\n}) {}\n\nexport interface Options {\n\t/** The CodeWork home whose `service.json` names the server. */\n\treadonly home: string;\n\t/** The home's log directory, where a background server writes `server.log`. */\n\treadonly log: string;\n\treadonly host: string;\n\treadonly port: number;\n\t/** Server-owned flags placed before `serve`. */\n\treadonly args: ReadonlyArray<string>;\n}\n\nconst START_TIMEOUT = \"20 seconds\";\nconst RACE_GRACE = \"2 seconds\";\nconst STOP_TIMEOUT = \"5 seconds\";\n\nconst remove = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tyield* fs.remove(path);\n\t}).pipe(Effect.ignore);\n\n/** Whether `pid` is a running process. EPERM means it exists but belongs to someone else. */\nconst alive = (pid: number) =>\n\tEffect.try({ try: () => process.kill(pid, 0), catch: (error) => (error as NodeJS.ErrnoException).code }).pipe(\n\t\tEffect.as(true),\n\t\tEffect.catch((code) => Effect.succeed(code === \"EPERM\")),\n\t);\n\n/** Whether `pid` exits within `timeout`. */\nconst exits = (pid: number, timeout: typeof STOP_TIMEOUT) =>\n\talive(pid).pipe(\n\t\tEffect.repeat({ while: (running) => running, schedule: Schedule.spaced(\"50 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.isSome),\n\t);\n\n/**\n * The registered server, with `live` set when the process answering its endpoint\n * is the one that registered. The file is a hint, never proof: a different server\n * on a reused port must not pass for it.\n */\nconst registered = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst info = yield* Registration.read(path);\n\t\tif (info === undefined) return undefined;\n\t\tconst live = yield* Health.probe(info);\n\t\treturn { info, live: live?.pid === info.pid ? live : undefined };\n\t});\n\nconst endpoint = (info: Registration.Info): Endpoint => ({\n\turl: info.url,\n\tpid: info.pid,\n\tport: info.port,\n\ttoken: info.token,\n});\n\n/** The running server registered for `home`, with the build it reports. */\nexport const discover = (home: string) =>\n\tregistered(Registration.file(home)).pipe(\n\t\tEffect.map((found) =>\n\t\t\tfound?.live === undefined ? undefined : { ...endpoint(found.info), version: found.live.version },\n\t\t),\n\t);\n\n/**\n * Stop the server registered for `home`, returning it, or undefined when none\n * answers. Only a server that confirms it is the registrant is signalled: a pid\n * on file may since have been reused by an unrelated process.\n */\nexport const stop = (home: string) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(home);\n\t\tconst found = yield* registered(path);\n\t\tif (found === undefined) return undefined;\n\t\tif (found.live === undefined) {\n\t\t\tif (!(yield* alive(found.info.pid))) yield* remove(path);\n\t\t\treturn undefined;\n\t\t}\n\t\tyield* terminate(path, found.info.pid);\n\t\treturn endpoint(found.info);\n\t});\n\n/**\n * Ensure a healthy local server for `home`: reuse the registered one, replace it\n * when `replace` is set and it runs a different build, or start a background one.\n *\n * The background server is detached and outlives this caller, so the next\n * invocation reuses it. When two callers race, only the contender that binds the\n * port registers; the loser exits and both adopt the winner, because a caller\n * only ever believes a registration it can confirm over the wire.\n */\nexport const ensure = (options: Options & { readonly replace: boolean }) =>\n\tEffect.gen(function* () {\n\t\tconst path = Registration.file(options.home);\n\t\tconst found = yield* registered(path);\n\t\tif (found?.live !== undefined) {\n\t\t\tif (!options.replace || found.live.version === Identity.current.version) return endpoint(found.info);\n\t\t\tyield* terminate(path, found.info.pid);\n\t\t} else {\n\t\t\t// A file nothing answers for, left by a crash, must not mislead the next caller.\n\t\t\tif (found !== undefined && !(yield* alive(found.info.pid))) yield* remove(path);\n\t\t}\n\t\treturn yield* start(path, options);\n\t});\n\n/** The registered server once it answers, polled every 200ms for up to `timeout`. */\nconst ready = (path: string, timeout: Duration.Input, pending: Effect.Effect<boolean>) =>\n\tEffect.gen(function* () {\n\t\tconst next = yield* registered(path);\n\t\tif (next?.live !== undefined) return Option.some(endpoint(next.info));\n\t\t// A live registrant that does not answer yet is another caller's server starting up.\n\t\tconst waiting = (yield* pending) || (next !== undefined && (yield* alive(next.info.pid)));\n\t\treturn waiting ? Option.none() : yield* Effect.fail(\"exited\" as const);\n\t}).pipe(\n\t\tEffect.repeat({ until: Option.isSome, schedule: Schedule.spaced(\"200 millis\") }),\n\t\tEffect.timeoutOption(timeout),\n\t\tEffect.map(Option.flatten),\n\t\tEffect.orElseSucceed(() => Option.none<Endpoint>()),\n\t);\n\n/**\n * Start a background server and wait for it to register, quoting the reason\n * from its log when it cannot.\n *\n * The contender stays tied to this scope until it is the server adopted: a\n * timeout, an interrupt, or another caller winning the race stops it rather than\n * leaving an unmanaged server behind.\n */\nconst start = (path: string, options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst contender = yield* spawn(options);\n\t\tconst won = yield* ready(path, START_TIMEOUT, contender.isRunning.pipe(Effect.orElseSucceed(() => false)));\n\t\t// A contender that lost the bind race exits before the winner may have filed its\n\t\t// registration; give the winner a moment before calling the start a failure.\n\t\tconst server = Option.isSome(won) ? won : yield* ready(path, RACE_GRACE, Effect.succeed(true));\n\t\tif (Option.isSome(server)) {\n\t\t\tif (server.value.pid === contender.pid) yield* contender.unref.pipe(Effect.asVoid);\n\t\t\treturn server.value;\n\t\t}\n\n\t\tconst log = Registration.log(options.log);\n\t\tconst reason = yield* lastLine(log);\n\t\treturn yield* new ServerStartError({\n\t\t\tmessage: [\n\t\t\t\t`could not start a CodeWork server on ${options.host}:${options.port}`,\n\t\t\t\t...(reason === undefined ? [] : [`reason: ${reason}`]),\n\t\t\t\t`log: ${log}`,\n\t\t\t\t\"hint: pass --port to use another port\",\n\t\t\t].join(\"\\n\"),\n\t\t});\n\t}).pipe(Effect.scoped);\n\n/** Ask `pid` to shut down, escalating to SIGKILL, and retire its registration. */\nconst terminate = (path: string, pid: number) =>\n\tEffect.gen(function* () {\n\t\tconst signal = (name: NodeJS.Signals) => Effect.try(() => process.kill(pid, name)).pipe(Effect.ignore);\n\t\tyield* signal(\"SIGTERM\");\n\t\tif (!(yield* exits(pid, STOP_TIMEOUT))) {\n\t\t\tyield* signal(\"SIGKILL\");\n\t\t\tyield* exits(pid, STOP_TIMEOUT);\n\t\t}\n\t\t// A server removes its own file on a clean exit; this covers the SIGKILL path.\n\t\tconst info = yield* Registration.read(path);\n\t\tif (info?.pid === pid) yield* remove(path);\n\t});\n\nconst lastLine = (path: string) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst text = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => \"\"));\n\t\treturn text\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.findLast((line) => line.length > 0);\n\t});\n\n/**\n * Spawn `codework serve --service` detached, inheriting this environment so it\n * resolves the same home, catalog and credentials. It writes its own log, so no\n * stdio is tied to this short-lived caller. It stays referenced, and so stopped\n * with the scope, until `start` adopts it.\n */\nconst spawn = (options: Options) =>\n\tEffect.gen(function* () {\n\t\tconst [file, ...base] = Registration.command();\n\t\tif (file === undefined) return yield* Effect.die(new Error(\"could not resolve the codework entrypoint\"));\n\t\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\t\tconst handle = yield* spawner.spawn(\n\t\t\tChildProcess.make(\n\t\t\t\tfile,\n\t\t\t\t[...base, ...options.args, \"serve\", \"--service\", \"--host\", options.host, \"--port\", String(options.port)],\n\t\t\t\t{ detached: true, stdin: \"ignore\", stdout: \"ignore\", stderr: \"ignore\" },\n\t\t\t),\n\t\t);\n\t\treturn handle;\n\t});\n"],"mappings":";;;;;;;;;;;;AASA,MAAa,SAAS,WACrB,OAAO,IAAI,aAAa;CACvB,MAAM,UAAU,OAAO,MAAM,MAAMA,MAAa,MAAM,CAAC,CAAC,CAAC,KAAK,OAAO,oBAAoB,KAAA,CAAS,CAAC;CACnG,IAAI,YAAY,KAAA,GAAW,OAAO,KAAA;CAClC,OAAO,OAAO,OAAO,IAAI,aAAa;EAErC,OAAO,QAAO,OADKC,KAAAA,CACD,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,CAAC;CACrE,CAAC,CAAC,CAAC,KACF,OAAO,eAAe,OAAO,GAC7B,OAAO,oBAAoB,KAAA,CAAS,CACrC;AACD,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM;;;;ACLtB,IAAM,mBAAN,cAA+B,OAAO,YAA8B,CAAC,CAAC,8BAA8B,EACnG,SAAS,OAAO,OACjB,CAAC,CAAC,CAAC,CAAC;AAaJ,MAAM,gBAAgB;AACtB,MAAM,aAAa;AACnB,MAAM,eAAe;AAErB,MAAM,UAAU,SACf,OAAO,IAAI,aAAa;CAEvB,QAAO,OADW,WAAW,WAAA,CACnB,OAAO,IAAI;AACtB,CAAC,CAAC,CAAC,KAAK,O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a;CACvB,MAAM,CAAC,MAAM,GAAG,QAAQK,QAAqB;CAC7C,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,2CAA2C,CAAC;CASvG,OAAO,QAPe,OADC,oBAAoB,oBAAA,CACb,MAC7B,aAAa,KACZ,MACA;EAAC,GAAG;EAAM,GAAG,QAAQ;EAAM;EAAS;EAAa;EAAU,QAAQ;EAAM;EAAU,OAAO,QAAQ,IAAI;CAAC,GACvG;EAAE,UAAU;EAAM,OAAO;EAAU,QAAQ;EAAU,QAAQ;CAAS,CACvE,CACD;AAED,CAAC"}
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-B5dVwZ1g.mjs";
1
+ import { t as version } from "./package-CssYvr3o.mjs";
2
2
  import { Context, Effect, Layer } from "effect";
3
3
  import { NodeServices } from "@effect/platform-node";
4
4
  import os from "node:os";
@@ -23,4 +23,4 @@ const layer = Layer.effect(Service, hostName.pipe(Effect.map((name) => Service.o
23
23
  //#endregion
24
24
  export { layer as i, current as n, hostName as r, Service as t };
25
25
 
26
- //# sourceMappingURL=identity--j8hMb07.mjs.map
26
+ //# sourceMappingURL=identity-DQYgsuek.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"identity--j8hMb07.mjs","names":["pkg.version"],"sources":["../../src/server/identity.ts"],"sourcesContent":["/* @effect-diagnostics nodeBuiltinImport:off -- the host's name is the OS's hostname. */\nimport os from \"node:os\";\nimport { NodeServices } from \"@effect/platform-node\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\n/**\n * What a running server is, as its clients need to know it.\n *\n * A discovery registration names the pid and version it wrote; `server.info`\n * answers with the live ones so a caller can tell the process it reached is the\n * one that registered rather than a different server that took the same port.\n */\nexport interface Interface {\n\treadonly pid: number;\n\treadonly version: string;\n\t/** The machine it runs on, by the name its user knows it; none when the OS names it nothing. */\n\treadonly host?: { readonly name: string };\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/cli/server/identity/Service\") {}\n\n/** This process: a server answers with it, a client compares a server's version against it. */\nexport const current: Interface = { pid: process.pid, version: pkg.version };\n\n// macOS's computer name is the one Finder and sharing show; its hostname is a mangled copy of it.\n/** The machine's name as its user knows it, read from the OS; empty when it names nothing. */\nexport const hostName = Effect.gen(function* () {\n\tif (process.platform !== \"darwin\") return os.hostname().trim();\n\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\tconst computer = yield* spawner\n\t\t.string(ChildProcess.make(\"scutil\", [\"--get\", \"ComputerName\"]))\n\t\t.pipe(Effect.orElseSucceed(() => \"\"));\n\treturn (\n\t\tcomputer.trim() ||\n\t\tos\n\t\t\t.hostname()\n\t\t\t.replace(/\\.local$/, \"\")\n\t\t\t.trim()\n\t);\n});\n\n/** The host's name is read once, when the server starts. */\nexport const layer = Layer.effect(\n\tService,\n\thostName.pipe(Effect.map((name) => Service.of(name === \"\" ? current : { ...current, host: { name } }))),\n).pipe(Layer.provide(NodeServices.layer));\n"],"mappings":";;;;;;AAqBA,IAAa,UAAb,cAA6B,QAAQ,QAA4B,CAAC,CAAC,yCAAyC,CAAC,CAAC,CAAC;;AAG/G,MAAa,UAAqB;CAAE,KAAK,QAAQ;CAAcA;AAAY;;AAI3E,MAAa,WAAW,OAAO,IAAI,aAAa;CAC/C,IAAI,QAAQ,aAAa,UAAU,OAAO,GAAG,SAAS,CAAC,CAAC,KAAK;CAK7D,QACC,QAJuB,OADD,oBAAoB,oBAAA,CAEzC,OAAO,aAAa,KAAK,UAAU,CAAC,SAAS,cAAc,CAAC,CAAC,CAAC,CAC9D,KAAK,OAAO,oBAAoB,EAAE,CAAC,EAAA,CAE3B,KAAK,KACd,GACE,SAAS,CAAC,CACV,QAAQ,YAAY,EAAE,CAAC,CACvB,KAAK;AAET,CAAC;;AAGD,MAAa,QAAQ,MAAM,OAC1B,SACA,SAAS,KAAK,OAAO,KAAK,SAAS,QAAQ,GAAG,SAAS,KAAK,UAAU;CAAE,GAAG;CAAS,MAAM,EAAE,KAAK;AAAE,CAAC,CAAC,CAAC,CACvG,CAAC,CAAC,KAAK,MAAM,QAAQ,aAAa,KAAK,CAAC"}
1
+ {"version":3,"file":"identity-DQYgsuek.mjs","names":["pkg.version"],"sources":["../../src/server/identity.ts"],"sourcesContent":["/* @effect-diagnostics nodeBuiltinImport:off -- the host's name is the OS's hostname. */\nimport os from \"node:os\";\nimport { NodeServices } from \"@effect/platform-node\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\n/**\n * What a running server is, as its clients need to know it.\n *\n * A discovery registration names the pid and version it wrote; `server.info`\n * answers with the live ones so a caller can tell the process it reached is the\n * one that registered rather than a different server that took the same port.\n */\nexport interface Interface {\n\treadonly pid: number;\n\treadonly version: string;\n\t/** The machine it runs on, by the name its user knows it; none when the OS names it nothing. */\n\treadonly host?: { readonly name: string };\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@codeworksh/cli/server/identity/Service\") {}\n\n/** This process: a server answers with it, a client compares a server's version against it. */\nexport const current: Interface = { pid: process.pid, version: pkg.version };\n\n// macOS's computer name is the one Finder and sharing show; its hostname is a mangled copy of it.\n/** The machine's name as its user knows it, read from the OS; empty when it names nothing. */\nexport const hostName = Effect.gen(function* () {\n\tif (process.platform !== \"darwin\") return os.hostname().trim();\n\tconst spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\tconst computer = yield* spawner\n\t\t.string(ChildProcess.make(\"scutil\", [\"--get\", \"ComputerName\"]))\n\t\t.pipe(Effect.orElseSucceed(() => \"\"));\n\treturn (\n\t\tcomputer.trim() ||\n\t\tos\n\t\t\t.hostname()\n\t\t\t.replace(/\\.local$/, \"\")\n\t\t\t.trim()\n\t);\n});\n\n/** The host's name is read once, when the server starts. */\nexport const layer = Layer.effect(\n\tService,\n\thostName.pipe(Effect.map((name) => Service.of(name === \"\" ? current : { ...current, host: { name } }))),\n).pipe(Layer.provide(NodeServices.layer));\n"],"mappings":";;;;;;AAqBA,IAAa,UAAb,cAA6B,QAAQ,QAA4B,CAAC,CAAC,yCAAyC,CAAC,CAAC,CAAC;;AAG/G,MAAa,UAAqB;CAAE,KAAK,QAAQ;CAAcA;AAAY;;AAI3E,MAAa,WAAW,OAAO,IAAI,aAAa;CAC/C,IAAI,QAAQ,aAAa,UAAU,OAAO,GAAG,SAAS,CAAC,CAAC,KAAK;CAK7D,QACC,QAJuB,OADD,oBAAoB,oBAAA,CAEzC,OAAO,aAAa,KAAK,UAAU,CAAC,SAAS,cAAc,CAAC,CAAC,CAAC,CAC9D,KAAK,OAAO,oBAAoB,EAAE,CAAC,EAAA,CAE3B,KAAK,KACd,GACE,SAAS,CAAC,CACV,QAAQ,YAAY,EAAE,CAAC,CACvB,KAAK;AAET,CAAC;;AAGD,MAAa,QAAQ,MAAM,OAC1B,SACA,SAAS,KAAK,OAAO,KAAK,SAAS,QAAQ,GAAG,SAAS,KAAK,UAAU;CAAE,GAAG;CAAS,MAAM,EAAE,KAAK;AAAE,CAAC,CAAC,CAAC,CACvG,CAAC,CAAC,KAAK,MAAM,QAAQ,aAAa,KAAK,CAAC"}
package/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-B5dVwZ1g.mjs";
2
+ import { t as version } from "./package-CssYvr3o.mjs";
3
3
  import { i as Cmd, n as handlers, r as run } from "./runtime-BC3hAvn_.mjs";
4
4
  import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5
5
  import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -21,15 +21,15 @@ const Handlers = handlers(Cmd, {
21
21
  reconnect: () => import("./reconnect-BFaxT1DU.mjs"),
22
22
  disconnect: () => import("./disconnect-CjiHyadm.mjs")
23
23
  },
24
- connect: () => import("./connect-Cwz4fwcc.mjs"),
25
- disconnect: () => import("./disconnect-D4g8ISX9.mjs"),
24
+ connect: () => import("./connect-Bg3kHbrx.mjs"),
25
+ disconnect: () => import("./disconnect-hDfEVmWt.mjs"),
26
26
  run: () => import("./run-DEE9e1dU.mjs"),
27
- serve: () => import("./serve-CkGkCgTL.mjs"),
27
+ serve: () => import("./serve-DfixsOeg.mjs"),
28
28
  service: {
29
- start: () => import("./start-t0FCZvYw.mjs"),
30
- restart: () => import("./restart-9yoKrlmo.mjs"),
31
- status: () => import("./status-2NsYhn1K.mjs"),
32
- stop: () => import("./stop-CDk0lO6x.mjs"),
29
+ start: () => import("./start-BNhwppz_.mjs"),
30
+ restart: () => import("./restart-De6ylFk3.mjs"),
31
+ status: () => import("./status-B5-Cuqpo.mjs"),
32
+ stop: () => import("./stop-MCLYgwMu.mjs"),
33
33
  pair: () => import("./pair-BDsnQtS0.mjs"),
34
34
  devices: () => import("./devices-CgsNM40i.mjs"),
35
35
  revoke: () => import("./revoke-BCWK0foJ.mjs")
@@ -42,7 +42,7 @@ const Handlers = handlers(Cmd, {
42
42
  list: () => import("./list-Bf7dMOGL.mjs"),
43
43
  fork: () => import("./fork-DyTp6gur.mjs")
44
44
  },
45
- acp: () => import("./acp-NKndM0y4.mjs"),
45
+ acp: () => import("./acp-CrNOJRGe.mjs"),
46
46
  plugin: {
47
47
  add: () => import("./add-Dnl6Cvyn.mjs"),
48
48
  check: () => import("./check-CvJjC0rF.mjs"),
@@ -0,0 +1,6 @@
1
+ //#region package.json
2
+ var version = "0.9.0-canary.163.1.g9e8c1408";
3
+ //#endregion
4
+ export { version as t };
5
+
6
+ //# sourceMappingURL=package-CssYvr3o.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-CssYvr3o.mjs","names":[],"sources":["../../package.json"],"sourcesContent":[""],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeworksh/cli",
3
- "version": "0.9.0-canary.161.1.gdb3b1409",
3
+ "version": "0.9.0-canary.163.1.g9e8c1408",
4
4
  "description": "CLI for running CodeWork coding agent harness.",
5
5
  "keywords": [
6
6
  "agent",
@@ -40,8 +40,8 @@
40
40
  },
41
41
  "dependencies": {
42
42
  "@agentclientprotocol/sdk": "1.5.1",
43
- "@codeworksh/aikit": "0.14.1-canary.161.1.gdb3b1409",
44
- "@codeworksh/harness": "0.9.0-canary.161.1.gdb3b1409",
43
+ "@codeworksh/aikit": "0.14.1-canary.163.1.g9e8c1408",
44
+ "@codeworksh/harness": "0.9.0-canary.163.1.g9e8c1408",
45
45
  "@effect/platform-node": "4.0.5",
46
46
  "@effect/platform-node-shared": "4.0.5",
47
47
  "effect": "4.0.5",
@@ -1,7 +1,7 @@
1
1
  import { $ as sign, H as Api, K as PrivateKey, Q as publicOf, U as IdSource, V as ConnectError, W as MachineId, Y as generate, et as thumbprint } from "./error-qctchbYS.mjs";
2
- import { t as version } from "./package-B5dVwZ1g.mjs";
2
+ import { t as version } from "./package-CssYvr3o.mjs";
3
3
  import { o as write$1 } from "./registration-C6yiv31r.mjs";
4
- import { r as hostName } from "./identity--j8hMb07.mjs";
4
+ import { r as hostName } from "./identity-DQYgsuek.mjs";
5
5
  import { Clock, Config, Context, Duration, Effect, FileSystem, Layer, Option, Schedule, Schema } from "effect";
6
6
  import { FetchHttpClient } from "effect/http";
7
7
  import { uuidv7 } from "uuidv7";
@@ -74,7 +74,11 @@ const update = (home, options, change) => locked(home, Effect.gen(function* () {
74
74
  const existing = yield* read(home);
75
75
  const machine = yield* Option.match(existing, {
76
76
  onNone: () => Effect.succeed(created(options.machineId)),
77
- onSome: (machine) => options.machineId === void 0 || options.machineId === machine.id ? Effect.succeed(machine) : Effect.fail(new MachineError({ message: `This home is machine ${machine.id}; its id can't change to ${options.machineId}. Use another --home.` }))
77
+ onSome: (machine) => options.machineId === void 0 || options.machineId === machine.id ? Effect.succeed(machine) : machine.source === "generated" && Object.keys(machine.workspaces).length === 0 ? Effect.succeed({
78
+ ...machine,
79
+ id: options.machineId,
80
+ source: "flag"
81
+ }) : Effect.fail(new MachineError({ message: `This home is machine ${machine.id}; its id can't change to ${options.machineId}. Use another --home.` }))
78
82
  });
79
83
  const identity = machine.identity ?? (yield* newIdentity);
80
84
  const next = yield* change({
@@ -316,4 +320,4 @@ const disconnect = Effect.fn("Machine.disconnect")(function* (home, workspaceId,
316
320
  //#endregion
317
321
  export { rename as a, read as c, heartbeat as i, connect as n, status as o, disconnect as r, identity as s, Client as t };
318
322
 
319
- //# sourceMappingURL=relay-Ccwzl2lc.mjs.map
323
+ //# sourceMappingURL=relay-Bp4GqpdD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay-Bp4GqpdD.mjs","names":["Jws.PrivateKey","Relay.IdSource","Private.write","Jws.generate","Jws.thumbprint","Jws.publicOf","Relay.MachineId","Relay.Api","pkg.version","File.read","File.update","File.checkId","Jws.generate","Jws.thumbprint","Jws.publicOf","Jws.sign","Machine.ConnectError","File.removeLink","File.markLeaving"],"sources":["../../src/machine/file.ts","../../src/machine/relay.ts"],"sourcesContent":["import { Jws, Relay } from \"@codeworksh/schema\";\nimport { Effect, FileSystem, Option, Schedule, Schema } from \"effect\";\nimport { uuidv7 } from \"uuidv7\";\nimport * as Private from \"../framework/private.ts\";\n\n/**\n * `<home>/machine.json`: who this home is as a machine, and its link to each connected workspace.\n *\n * It survives restarts (unlike `service.json`, which a server writes and removes) and holds private\n * keys, so it is written 0600, atomically, and under a lock shared by `serve` and `codework connect`.\n */\nconst Link = Schema.Struct({\n\tname: Schema.String,\n\towner: Schema.Struct({ id: Schema.String, name: Schema.NullOr(Schema.String) }),\n\t/** The relay the link was made with; heartbeats and disconnect go there. */\n\trelay: Schema.String,\n\tkey: Jws.PrivateKey,\n\tkeyId: Schema.String,\n\t/** Left locally, but the relay hasn't confirmed: the key is kept to revoke it once the relay answers. */\n\tleaving: Schema.optionalKey(Schema.Boolean),\n});\n\n/** One key per home, vouching for each link key, so the relay knows every link of this home is one machine. */\nconst Identity = Schema.Struct({ key: Jws.PrivateKey, keyId: Schema.String });\ntype Identity = typeof Identity.Type;\n\nexport const Machine = Schema.Struct({\n\tid: Schema.String,\n\tsource: Relay.IdSource,\n\t/** The user's own name for the machine; shown in place of the OS host name when set. */\n\tgivenName: Schema.optional(Schema.String),\n\t// Optional only for homes connected before identities existed; `update` gives every home one.\n\tidentity: Schema.optional(Identity),\n\tworkspaces: Schema.Record(Schema.String, Link),\n});\nexport type Machine = typeof Machine.Type;\n/** The machine as {@link update} hands it out: always with its identity. */\ntype Identified = Machine & { readonly identity: Identity };\n\nconst json = Schema.fromJsonString(Machine);\n\nclass MachineError extends Schema.TaggedError<MachineError>()(\"Machine.MachineError\", {\n\tmessage: Schema.String,\n}) {}\n\nconst file = (home: string) => `${home}/machine.json`;\n\n/** The machine as stored, or none before its first run. */\nexport const read = Effect.fn(\"Machine.read\")(function* (home: string) {\n\tconst fs = yield* FileSystem.FileSystem;\n\tconst path = file(home);\n\tif (!(yield* fs.exists(path))) return Option.none<Machine>();\n\tconst text = yield* fs.readFileString(path);\n\treturn Option.some(\n\t\tyield* Schema.decodeEffect(json)(text).pipe(\n\t\t\tEffect.mapError(() => new MachineError({ message: `${path} is not a valid machine file` })),\n\t\t),\n\t);\n});\n\n// One writer at a time: creating a directory either succeeds or fails, so it serves as a lock.\nconst locked = <A, E, R>(home: string, effect: Effect.Effect<A, E, R>) =>\n\tEffect.gen(function* () {\n\t\tconst fs = yield* FileSystem.FileSystem;\n\t\tconst lock = `${file(home)}.lock`;\n\t\tyield* fs.makeDirectory(home, { recursive: true });\n\t\tyield* fs.makeDirectory(lock).pipe(\n\t\t\tEffect.retry({ schedule: Schedule.spaced(\"50 millis\"), times: 100 }),\n\t\t\tEffect.mapError(() => new MachineError({ message: `${lock} is held by another process` })),\n\t\t);\n\t\treturn yield* effect.pipe(Effect.ensuring(fs.remove(lock, { recursive: true }).pipe(Effect.ignore)));\n\t});\n\nconst write = (home: string, machine: Machine) =>\n\tSchema.encodeEffect(json)(machine).pipe(Effect.flatMap((encoded) => Private.write(file(home), encoded)));\n\nconst newIdentity = Effect.gen(function* () {\n\tconst key = yield* Jws.generate();\n\treturn { key, keyId: yield* Jws.thumbprint(Jws.publicOf(key)) } satisfies Identity;\n});\n\n/** Reads, changes and writes the machine under the lock, creating its identity on first use. */\nexport const update = <E, R>(\n\thome: string,\n\toptions: { readonly machineId?: string | undefined },\n\tchange: (machine: Identified) => Effect.Effect<Identified, E, R>,\n) =>\n\tlocked(\n\t\thome,\n\t\tEffect.gen(function* () {\n\t\t\tconst existing = yield* read(home);\n\t\t\tconst machine = yield* Option.match(existing, {\n\t\t\t\tonNone: () => Effect.succeed(created(options.machineId)),\n\t\t\t\tonSome: (machine) =>\n\t\t\t\t\toptions.machineId === undefined || options.machineId === machine.id\n\t\t\t\t\t\t? Effect.succeed(machine)\n\t\t\t\t\t\t: // `serve` generates an id at startup, so a rebuilt machine has one before it reclaims its old id;\n\t\t\t\t\t\t\t// one no workspace has seen yet can still give way.\n\t\t\t\t\t\t\tmachine.source === \"generated\" && Object.keys(machine.workspaces).length === 0\n\t\t\t\t\t\t\t? Effect.succeed({ ...machine, id: options.machineId, source: \"flag\" as const })\n\t\t\t\t\t\t\t: Effect.fail(\n\t\t\t\t\t\t\t\t\tnew MachineError({\n\t\t\t\t\t\t\t\t\t\tmessage: `This home is machine ${machine.id}; its id can't change to ${options.machineId}. Use another --home.`,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t),\n\t\t\t});\n\t\t\tconst identity = machine.identity ?? (yield* newIdentity);\n\t\t\tconst next = yield* change({ ...machine, identity });\n\t\t\tyield* write(home, next);\n\t\t\treturn next;\n\t\t}),\n\t);\n\n/** The home's identity, created with the machine on first use. */\nexport const identity = Effect.fn(\"Machine.identity\")(function* (home: string) {\n\tconst stored = yield* read(home);\n\tif (Option.isSome(stored) && stored.value.identity !== undefined) return stored.value.identity;\n\treturn (yield* update(home, {}, Effect.succeed)).identity;\n});\n\nconst created = (machineId: string | undefined): Machine =>\n\tmachineId === undefined\n\t\t? { id: uuidv7(), source: \"generated\", workspaces: {} }\n\t\t: { id: machineId, source: \"flag\", workspaces: {} };\n\n/** Validates a `--machine-id` before anything is written. */\nexport const checkId = (machineId: string | undefined) =>\n\tmachineId === undefined || Schema.is(Relay.MachineId)(machineId)\n\t\t? Effect.void\n\t\t: Effect.fail(\n\t\t\t\tnew MachineError({\n\t\t\t\t\tmessage: `--machine-id must be 1-64 lowercase letters, digits or dashes, starting with a letter or digit`,\n\t\t\t\t}),\n\t\t\t);\n\n/**\n * Forgets the link to a workspace, only while it still holds `keyId`: a reconnect that saved a new key in\n * the meantime keeps its link.\n */\nexport const removeLink = (home: string, workspaceId: string, keyId: string) =>\n\tupdate(home, {}, (machine) => {\n\t\tconst { [workspaceId]: link, ...workspaces } = machine.workspaces;\n\t\treturn Effect.succeed(link === undefined || link.keyId !== keyId ? machine : { ...machine, workspaces });\n\t});\n\n/** Marks the link as leaving, only while it still holds `keyId`. */\nexport const markLeaving = (home: string, workspaceId: string, keyId: string) =>\n\tupdate(home, {}, (machine) => {\n\t\tconst link = machine.workspaces[workspaceId];\n\t\treturn Effect.succeed(\n\t\t\tlink === undefined || link.keyId !== keyId\n\t\t\t\t? machine\n\t\t\t\t: { ...machine, workspaces: { ...machine.workspaces, [workspaceId]: { ...link, leaving: true } } },\n\t\t);\n\t});\n","import { NodeServices } from \"@effect/platform-node\";\nimport { Jws, Machine, Relay } from \"@codeworksh/schema\";\nimport { Clock, Config, Context, Duration, Effect, Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { HttpApiClient } from \"effect/http-api\";\nimport { uuidv7 } from \"uuidv7\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\nimport { hostName } from \"../server/identity.ts\";\nimport * as File from \"./file.ts\";\n\n/** The relay's typed client at `url`. */\nconst at = (url: string) => HttpApiClient.make(Relay.Api, { baseUrl: url }).pipe(Effect.provide(FetchHttpClient.layer));\n\n/**\n * The relay new connects go to: `CODEWORK_RELAY_URL`, default https://relay.codework.sh. A link keeps\n * talking to the relay it was made with, whatever this says later.\n */\nexport class Client extends Context.Service<\n\tClient,\n\t{ readonly url: string; readonly api: HttpApiClient.ForApi<typeof Relay.Api> }\n>()(\"@codeworksh/cli/machine/relay/Client\") {\n\tstatic readonly layer = Layer.effect(\n\t\tClient,\n\t\tEffect.gen(function* () {\n\t\t\tconst url = yield* Config.String(\"CODEWORK_RELAY_URL\").pipe(Config.withDefault(\"https://relay.codework.sh\"));\n\t\t\treturn { url, api: yield* at(url) };\n\t\t}),\n\t);\n}\n\n/** What this machine says about itself to the relay. */\nconst describe = Effect.fn(\"Machine.describe\")(function* (machine: File.Machine) {\n\tconst localHostName = yield* hostName.pipe(Effect.provide(NodeServices.layer));\n\treturn {\n\t\tid: machine.id,\n\t\tsource: machine.source,\n\t\tlocalHostName,\n\t\tgivenName: machine.givenName ?? null,\n\t\tos: process.platform,\n\t\tarch: process.arch,\n\t\tversion: pkg.version,\n\t} satisfies Relay.MachineInfo;\n});\n\n/** This machine and its workspaces, as the desktop app shows them. */\nexport const status = Effect.fn(\"Machine.status\")(function* (home: string) {\n\tconst stored = yield* File.read(home);\n\tconst localHostName = yield* hostName.pipe(Effect.provide(NodeServices.layer));\n\tif (stored._tag === \"None\")\n\t\treturn { id: null, localHostName, givenName: null, workspaces: [] } satisfies Machine.Status;\n\tconst machine = stored.value;\n\treturn {\n\t\tid: machine.id,\n\t\tlocalHostName,\n\t\tgivenName: machine.givenName ?? null,\n\t\tworkspaces: Object.entries(machine.workspaces).map(([id, link]) => ({\n\t\t\tid,\n\t\t\tname: link.name,\n\t\t\tkeyId: link.keyId,\n\t\t\tleaving: link.leaving === true,\n\t\t})),\n\t} satisfies Machine.Status;\n});\n\n/**\n * Names this machine for people: empty clears the name back to the OS's. The relay hears it on the\n * next heartbeat.\n */\nexport const rename = Effect.fn(\"Machine.rename\")(function* (home: string, givenName: string) {\n\tconst name = givenName.trim();\n\tyield* File.update(home, {}, ({ givenName: _previous, ...machine }) =>\n\t\tEffect.succeed(name === \"\" ? machine : { ...machine, givenName: name }),\n\t);\n\treturn yield* status(home);\n});\n\n/**\n * Pairs this home with a workspace: registers a fresh key with the relay, shows the code a member\n * approves, and polls with that key until the relay links it, then saves the link. Each workspace gets\n * its own key, and only this process can take the link: a connect that stops is never linked.\n */\nexport const connect = Effect.fn(\"Machine.connect\")(function* (options: {\n\treadonly home: string;\n\treadonly workspaceId?: string | undefined;\n\treadonly machineId?: string | undefined;\n\treadonly onCode: (userCode: string) => Effect.Effect<void>;\n}) {\n\tconst client = yield* Client;\n\tyield* File.checkId(options.machineId);\n\tconst machine = yield* File.update(options.home, { machineId: options.machineId }, Effect.succeed);\n\tconst key = yield* Jws.generate();\n\tconst keyId = yield* Jws.thumbprint(Jws.publicOf(key));\n\tconst iat = yield* Clock.currentTimeMillis;\n\tconst binding: Relay.IdentityClaims = { op: \"identity.bind\", iat, keyId };\n\tconst claims: Relay.PairingClaims = {\n\t\top: \"pairing.create\",\n\t\tiat,\n\t\tmachine: yield* describe(machine),\n\t\tworkspaceId: options.workspaceId ?? null,\n\t\tidentity: yield* Jws.sign(binding, machine.identity.key, { embed: true }),\n\t};\n\tconst pairing = yield* client.api.machine\n\t\t.pair({ payload: { jws: yield* Jws.sign(claims, key, { embed: true }) } })\n\t\t.pipe(\n\t\t\tEffect.catchTag(\"Relay.NotFound\", () =>\n\t\t\t\tEffect.fail(new Machine.ConnectError({ message: \"No such workspace\" })),\n\t\t\t),\n\t\t);\n\tyield* options.onCode(pairing.userCode);\n\n\tconst poll = Effect.gen(function* () {\n\t\tconst claims: Relay.PollClaims = { op: \"pairing.poll\", iat: yield* Clock.currentTimeMillis };\n\t\treturn yield* client.api.machine.poll({ payload: { jws: yield* Jws.sign(claims, key, { kid: keyId }) } });\n\t}).pipe(\n\t\t// A dropped request or a relay restart doesn't end the connect; the next poll asks again.\n\t\tEffect.catchTag(\"HttpClientError\", (error) =>\n\t\t\tEffect.logDebug(\"Pairing poll failed\", error).pipe(Effect.as(undefined)),\n\t\t),\n\t);\n\tlet previous = machine;\n\tconst deadline = (yield* Clock.currentTimeMillis) + pairing.expiresIn * 1000;\n\twhile ((yield* Clock.currentTimeMillis) < deadline) {\n\t\tyield* Effect.sleep(Duration.seconds(pairing.interval));\n\t\tconst status = yield* poll;\n\t\tif (status === undefined) continue;\n\t\tif (status.status !== \"approved\") {\n\t\t\tif (status.status === \"pending\") continue;\n\t\t\tif (status.status === \"expired\") break;\n\t\t\treturn yield* new Machine.ConnectError({\n\t\t\t\tmessage:\n\t\t\t\t\tstatus.status === \"declined\"\n\t\t\t\t\t\t? \"The connect was declined; run connect again for a new code\"\n\t\t\t\t\t\t: \"Another connect for this machine finished first\",\n\t\t\t});\n\t\t}\n\t\tconst { connected } = status;\n\t\t// A poll response can arrive after another connect saved a different key.\n\t\t// Observe that change under the lock, then poll again before replacing it.\n\t\tconst id = connected.workspace.id;\n\t\tconst stored = yield* File.update(options.home, {}, (current) =>\n\t\t\tEffect.succeed(\n\t\t\t\tcurrent.workspaces[id]?.keyId !== previous.workspaces[id]?.keyId\n\t\t\t\t\t? current\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t...current,\n\t\t\t\t\t\t\tworkspaces: {\n\t\t\t\t\t\t\t\t...current.workspaces,\n\t\t\t\t\t\t\t\t[connected.workspace.id]: {\n\t\t\t\t\t\t\t\t\tname: connected.workspace.name,\n\t\t\t\t\t\t\t\t\towner: connected.owner,\n\t\t\t\t\t\t\t\t\trelay: client.url,\n\t\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\t\tkeyId,\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),\n\t\t);\n\t\tif (stored.workspaces[id]?.keyId === keyId) return connected;\n\t\tprevious = stored;\n\t}\n\treturn yield* new Machine.ConnectError({ message: \"The code expired before it was approved; run connect again\" });\n});\n\n/**\n * Asks the link's relay to revoke it, signed with its own key: true once the relay confirms, or says it\n * was revoked already; false when it can't be reached in time.\n */\nconst revoke = (machineId: string, workspaceId: string, link: File.Machine[\"workspaces\"][string]) =>\n\tEffect.gen(function* () {\n\t\tconst claims: Relay.RevokeClaims = {\n\t\t\top: \"machine.revoke\",\n\t\t\tiat: yield* Clock.currentTimeMillis,\n\t\t\tjti: uuidv7(),\n\t\t\tworkspaceId,\n\t\t\tmachineId,\n\t\t};\n\t\tconst api = yield* at(link.relay);\n\t\tyield* api.machine.revoke({ payload: { jws: yield* Jws.sign(claims, link.key, { kid: link.keyId }) } });\n\t}).pipe(\n\t\t// Leave time for the local update before the desktop RPC expires.\n\t\tEffect.timeout(\"3 seconds\"),\n\t\tEffect.as(true),\n\t\tEffect.catchTag(\"Relay.MachineRevoked\", () => Effect.succeed(true)),\n\t\tEffect.catch((error) => Effect.logDebug(`Revoke at ${link.name} failed`, error).pipe(Effect.as(false))),\n\t);\n\n/**\n * One heartbeat per connected workspace, each to the relay its link was made with, all at once. A link\n * the relay refuses as revoked is removed, but only while it still holds the refused key. A leaving link\n * asks for its revoke again instead, and is removed once the relay confirms.\n */\nexport const heartbeat = Effect.fn(\"Machine.heartbeat\")(function* (home: string) {\n\tconst stored = yield* File.read(home);\n\tif (stored._tag === \"None\") return;\n\tconst machine = stored.value;\n\tconst info = yield* describe(machine);\n\tyield* Effect.forEach(\n\t\tObject.entries(machine.workspaces),\n\t\t([workspaceId, link]) =>\n\t\t\tlink.leaving === true\n\t\t\t\t? revoke(machine.id, workspaceId, link).pipe(\n\t\t\t\t\t\tEffect.flatMap((revoked) =>\n\t\t\t\t\t\t\trevoked ? File.removeLink(home, workspaceId, link.keyId).pipe(Effect.asVoid) : Effect.void,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.catch((error) => Effect.logDebug(`Leaving ${link.name} failed`, error)),\n\t\t\t\t\t)\n\t\t\t\t: Effect.gen(function* () {\n\t\t\t\t\t\tconst api = yield* at(link.relay);\n\t\t\t\t\t\tconst claims: Relay.HeartbeatClaims = {\n\t\t\t\t\t\t\top: \"machine.heartbeat\",\n\t\t\t\t\t\t\tiat: yield* Clock.currentTimeMillis,\n\t\t\t\t\t\t\tworkspaceId,\n\t\t\t\t\t\t\tmachine: info,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tyield* api.machine.heartbeat({\n\t\t\t\t\t\t\tpayload: { jws: yield* Jws.sign(claims, link.key, { kid: link.keyId }) },\n\t\t\t\t\t\t});\n\t\t\t\t\t}).pipe(\n\t\t\t\t\t\tEffect.timeout(\"10 seconds\"),\n\t\t\t\t\t\tEffect.catchTags({\n\t\t\t\t\t\t\t\"Relay.MachineRevoked\": (revoked) =>\n\t\t\t\t\t\t\t\tEffect.logWarning(`Disconnected from ${link.name}: ${revoked.message}`).pipe(\n\t\t\t\t\t\t\t\t\tEffect.andThen(File.removeLink(home, workspaceId, link.keyId)),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t// Refused but not revoked, most often a clock more than a minute off: worth seeing in the log.\n\t\t\t\t\t\t\t\"Relay.Unauthorized\": (refused) =>\n\t\t\t\t\t\t\t\tEffect.logWarning(`Heartbeat to ${link.name} refused: ${refused.message}`),\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tEffect.catch((error) => Effect.logDebug(`Heartbeat to ${link.name} failed`, error)),\n\t\t\t\t\t),\n\t\t{ concurrency: \"unbounded\", discard: true },\n\t);\n});\n\n/**\n * Leaves a workspace: asks the link's relay to revoke it, then forgets it locally. When the relay can't\n * confirm, the link is kept as leaving, with its key, and each heartbeat asks again until it does; the\n * relay still lists it until then. `revoked` says whether it confirmed now.\n */\nexport const disconnect = Effect.fn(\"Machine.disconnect\")(function* (\n\thome: string,\n\tworkspaceId: string,\n\texpectedKeyId?: string,\n) {\n\tconst stored = yield* File.read(home);\n\tconst link = stored._tag === \"Some\" ? stored.value.workspaces[workspaceId] : undefined;\n\tif (stored._tag === \"None\" || link === undefined) {\n\t\treturn yield* new Machine.ConnectError({ message: `This machine is not connected to workspace ${workspaceId}` });\n\t}\n\tif (expectedKeyId !== undefined && link.keyId !== expectedKeyId)\n\t\treturn yield* new Machine.ConnectError({ message: \"This machine link has changed\" });\n\tconst revoked = yield* revoke(stored.value.id, workspaceId, link);\n\tyield* revoked ? File.removeLink(home, workspaceId, link.keyId) : File.markLeaving(home, workspaceId, link.keyId);\n\treturn { workspace: link.name, revoked };\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAM,OAAO,OAAO,OAAO;CAC1B,MAAM,OAAO;CACb,OAAO,OAAO,OAAO;EAAE,IAAI,OAAO;EAAQ,MAAM,OAAO,OAAO,OAAO,MAAM;CAAE,CAAC;;CAE9E,OAAO,OAAO;CACd,KAAKA;CACL,OAAO,OAAO;;CAEd,SAAS,OAAO,YAAY,OAAO,OAAO;AAC3C,CAAC;;AAGD,MAAM,WAAW,OAAO,OAAO;CAAE,KAAKA;CAAgB,OAAO,OAAO;AAAO,CAAC;AAG5E,MAAa,UAAU,OAAO,OAAO;CACpC,IAAI,OAAO;CACX,QAAQC;;CAER,WAAW,OAAO,SAAS,OAAO,MAAM;CAExC,UAAU,OAAO,SAAS,QAAQ;CAClC,YAAY,OAAO,OAAO,OAAO,QAAQ,IAAI;AAC9C,CAAC;AAKD,MAAM,OAAO,OAAO,eAAe,OAAO;AAE1C,IAAM,eAAN,cAA2B,OAAO,YAA0B,CAAC,CAAC,wBAAwB,EACrF,SAAS,OAAO,OACjB,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAM,QAAQ,SAAiB,GAAG,KAAK;;AAGvC,MAAa,OAAO,OAAO,GAAG,cAAc,CAAC,CAAC,WAAW,MAAc;CACtE,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,OAAO,KAAK,IAAI;CACtB,IAAI,EAAE,OAAO,GAAG,OAAO,IAAI,IAAI,OAAO,OAAO,KAAc;CAC3D,MAAM,OAAO,OAAO,GAAG,eAAe,IAAI;CAC1C,OAAO,OAAO,KACb,OAAO,OAAO,aAAa,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