Members

(constant) AddPayload

Payload schema for adding an MCP server: its name and configuration.

(constant) ApplyPatchTool

The "apply_patch" tool definition. Parses the patch into hunks, derives the new content for each add/update/move/delete (computing per-file diffs and addition/deletion counts), asks for a single "edit" permission covering all affected paths, applies the writes/removes/moves, runs the configured formatter, publishes file/edit events, refreshes the LSP and appends any diagnostics to the output.

(constant) AuthCallbackPayload

Payload schema for the MCP OAuth callback: the authorization code returned by the provider.

(constant) AuthMiddleware

HTTP Basic auth middleware, active only when CLOSEDCODE_SERVER_PASSWORD is set. Accepts credentials via the Authorization header or an auth_token query param; responds 401 when they do not match the configured username/password.

(constant) AuthRemoveResponse

Success schema for removing MCP OAuth credentials: a constant success flag.

(constant) AuthStartResponse

Success schema for starting MCP OAuth: the authorization URL plus the opaque OAuth state token.

(constant) BlockAnchorReplacer

Replacer for blocks of 3+ lines that anchors on the trimmed first and last lines, then scores candidate blocks by middle-line similarity (Levenshtein-based) and yields the best/only acceptable match's raw substring. Tolerates differences in the interior lines.

(constant) ClosedCodeHttpApi

Top-level HttpApi combining root, event stream, instance, and PTY-connect APIs, with shared Event/SyncEvent schemas annotated.

(constant) CommandInput

Input schema for command: the slash command name plus arguments, optional agent/model/variant, and optional file parts.

(constant) CommandPayload

Request body schema for sending a command, derived from SessionPrompt.CommandInput minus the path-supplied sessionID.

(constant) CommandPayload

Request body schema for executing a TUI command, carrying the command string.

(constant) CompressionMiddleware

gzip-compresses responses when the client accepts gzip, transparently wrapping res.write/res.end through a gzip stream. Skips SSE/streaming endpoints (/event, /global/event, and session message/prompt_async POSTs) so they can flush incrementally.

(constant) ConfigApi

Effect HttpApi group exposing GET /config, PATCH /config, and GET /config/providers.

(constant) ConsoleSwitchPayload

Payload selecting the account/org to make active when switching Console orgs.

(constant) ContextAwareReplacer

Replacer for blocks of 3+ lines that anchors on the trimmed first and last lines and accepts a block of the same length only when at least half of its interior non-empty lines match (after trimming), yielding the matching raw substring.

(constant) ControlApi

Effect HttpApi group exposing PUT/DELETE /auth/:providerID and POST /log.

(constant) ControlPaths

Route paths exposed by the control API group.

(constant) CreatePayload

Request body schema for creating a workspace, derived from Workspace.CreateInput minus projectID, with extra made optional.

(constant) Cursor :Object

Schema describing the decoded pagination cursor payload (message id, time, order, and direction).

Type:
  • Object

(constant) CursorQuery

Query schema carrying an optional pagination/stream cursor.

(constant) DefaultMessagesLimit :number

Default number of messages returned per page when no limit is supplied.

Type:
  • number

(constant) DefaultSessionsLimit :number

Default number of sessions returned per page when no limit is supplied.

Type:
  • number

(constant) DiffInput

Schema for diff requests: a required sessionID and optional messageID.

(constant) DiffQuery

Query-string schema for the diff endpoint, derived from SessionSummary.DiffInput minus the path-supplied sessionID.

(constant) Disabled

Schema for an explicitly disabled LSP server entry ({ disabled: true }). Exposes a derived .zod compatibility schema.

(constant) EditTool

The "edit" tool definition. Validates the arguments, resolves the path, and under a per-file lock either creates the file (when oldString is empty) or applies a find-and-replace (preserving the file's existing line endings and BOM). It asks for "edit" permission, writes and optionally formats the file, publishes edit/update events, computes a trimmed diff plus addition/deletion counts, and appends any LSP diagnostics to the output.

(constant) Entry

Schema for a single formatter entry: optional disabled flag, command argv, environment variables, and the extensions it applies to. Exposes a derived .zod compatibility schema.

(constant) Entry

Schema for a single LSP server entry: either Disabled or an object with command, optional extensions, disabled, env, and initialization options. Exposes a derived .zod compatibility schema.

(constant) ErrorMiddleware

Express error handler. Maps known error types to HTTP status codes (NotFound -> 404, model/auth/worktree validation -> 400, else 500) and serializes them as JSON.

(constant) EscapeNormalizedReplacer

Replacer that interprets backslash escape sequences (\n, \t, \r, quotes, \, $) in the search text, then yields either the unescaped string if found directly or any content block whose own unescaping matches the unescaped search text.

(constant) Event :Object

Server lifecycle events published on the bus.

  • Connected: emitted when the server has connected ("server.connected").
  • Disposed: emitted on global teardown ("global.disposed").
Type:
  • Object

(constant) Event

Bus event definitions for session status changes.

Properties
NameTypeDescription
StatusObject

Published whenever a session's status changes; carries sessionID and the new status.

IdleObject

Deprecated; published when a session becomes idle; carries only sessionID.

(constant) Event

Bus event definitions for the todo list.

Properties
NameTypeDescription
UpdatedObject

Published when a session's todo list changes; carries sessionID and the full todos array.

(constant) EventApi

Effect HttpApi group exposing the GET /event SSE subscribe endpoint.

(constant) EventPaths

Route paths exposed by the event API group.

(constant) EventTuiCommandExecute

Discriminated-union member schema for the command-execute TUI event.

(constant) EventTuiPromptAppend

Discriminated-union member schema for the prompt-append TUI event.

(constant) EventTuiSessionSelect

Discriminated-union member schema for the session-select TUI event.

(constant) EventTuiToastShow

Discriminated-union member schema for the toast-show TUI event.

(constant) ExperimentalApi

Effect HttpApi group exposing the experimental endpoints (Console, tools, worktrees, sessions, resources).

(constant) ExperimentalPaths

Route paths exposed by the experimental API group.

(constant) FenceMiddleware

Hono-style middleware that, for mutating requests, snapshots event sequences before and after the handler runs and, if any aggregate advanced, attaches the diff to the response via the x-closedcode-sync header so a proxy can fence reads.

(constant) FileApi

HttpApi definition for the experimental file route group. Bundles the find/list/read/status endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) FilePaths

URL path constants for each file route, keyed by endpoint name.

(constant) FileQuery

Query schema for endpoints that target a single file by path.

(constant) FindFileQuery

Query schema for the find-file endpoint: search query plus optional dir/type filters and a result limit.

(constant) FindSymbolQuery

Query schema for the find-symbol endpoint: a workspace symbol search query.

(constant) FindTextQuery

Query schema for the find-text endpoint: a ripgrep search pattern.

(constant) ForkPayload

Request body schema for forking a session, derived from Session.ForkInput minus the path-supplied sessionID.

(constant) GlobTool

The "glob" tool definition. Resolves the search directory (defaulting to the instance directory), asks for glob/external-directory permission, runs ripgrep's file matcher, sorts results newest-first, and truncates to 100 results with a notice when more exist.

(constant) GlobalApi

HttpApi definition for the global route group. Bundles the health, event-stream, config get/update, dispose, and upgrade endpoints (no instance middleware).

(constant) GlobalBus

Shared process-wide bus emitter used to relay events across instances.

(constant) GlobalEventSchema

Schema for a single global event: its directory/project/workspace scope plus a bus or sync event payload.

(constant) GlobalHealth

Success schema for the health endpoint: a constant healthy flag plus the server version.

(constant) GlobalPaths

URL path constants for each global route, keyed by endpoint name.

(constant) GlobalUpgradeInput

Payload schema for the upgrade endpoint: an optional target version (latest when omitted).

(constant) GlobalUpgradeResult

Success schema for the upgrade endpoint: either success with the new version or failure with an error message.

(constant) GrepDefinition

Shared grep/search tool definition Effect. Resolves the search target (file or directory), asks for grep/external-directory permission, runs the ripgrep search, collects file modification times concurrently, sorts matches newest-first, truncates to 100, and formats the matches grouped by file (long lines clamped to MAX_LINE_LENGTH).

(constant) GrepTool

The "grep" tool, built from the shared GrepDefinition (also re-exposed as "search" in tool/search.js).

(constant) HistoryEvent

Schema for a single sync event returned by the history endpoint (uses snake_case aggregate_id on the wire).

(constant) HistoryPayload

Request body schema for the history endpoint: a map of aggregate ID to the last known sequence number.

(constant) IndentationFlexibleReplacer

Replacer that matches blocks after stripping their common leading indentation, so the search text can be matched regardless of how deeply the original block is indented; yields the matching raw substring.

(constant) Info

Schema for a session's status: one of "idle", "busy", or "retry" (with attempt count, message, and next-retry timestamp).

(constant) Info

Schema for a single todo item: a content description, a status (pending/in_progress/completed/cancelled), and a priority (high/medium/low).

(constant) Info

Schema for the formatter config value: either a boolean toggle for built-ins or a record of formatter id to Entry overrides. Exposes a derived .zod schema.

(constant) Info

Schema for the lsp config value: either a boolean toggle for built-ins or a record of server id to Entry, checked by requiresExtensionsForCustomServers. Exposes a derived .zod compatibility schema.

(constant) Info :Schema.Struct

Schema for the skills section of the configuration. Carries optional additional skill folder paths and optional remote skill URLs, with a derived zod static for zod-based validation.

Type:
  • Schema.Struct

(constant) InitPayload

Request body schema for initializing a session: the provider/model to use and the seed message ID.

(constant) InstanceApi

HttpApi definition for the experimental instance read route group. Bundles the dispose/path/vcs/command/agent/skill/lsp/formatter endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) InstanceHttpApi

Instance HttpApi: all per-instance route groups (config, file, session, sync, etc.).

(constant) InstancePaths

URL path constants for each instance read route, keyed by endpoint name.

(constant) InvalidError

Error raised when a parsed config fails schema validation. Payload carries the file path, optional validation issues, and an optional message.

(constant) InvalidTool

The "invalid" tool. It is never meant to be invoked deliberately ("Do not use"); it merely echoes back the validation error describing why a previous tool call's arguments were rejected.

(constant) JsonError

Error raised when a config file cannot be parsed as JSON/JSONC. Payload carries the file path and an optional parser message.

(constant) Keybinds

Zod-compatible object schema for the keybindings config, derived from KeybindsSchema; exposes .shape so consumers can parse individual fields.

(constant) KeybindsSchema

Effect Schema describing every configurable keybinding field and its default.

(constant) Layout

Schema for the layout config value, one of "auto" or "stretch". Exposes a derived .zod compatibility schema. (Deprecated: layout is always stretch.)

(constant) LineTrimmedReplacer

Replacer that matches a block of lines ignoring leading/trailing whitespace on each line, yielding the corresponding raw substring of the original content.

(constant) ListQuery

Query-string schema for listing sessions, with optional directory, scope, path, roots-only, pagination, and search filters.

(constant) LogInput

Schema for a log entry payload posted to the /log endpoint.

(constant) LspTool

The "lsp" tool definition. Resolves the file path, asks for lsp/external-directory permission, converts the 1-based line/character into a 0-based LSP position, verifies the file exists and an LSP client is available, then dispatches the requested operation and serializes the result as JSON.

(constant) MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD

Minimum middle-line similarity required to accept the best candidate when multiple block-anchor candidates exist.

(constant) McpApi

HttpApi definition for the experimental MCP route group. Bundles the status/add/auth/connect/disconnect endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) McpPaths

URL path constants for each MCP route, keyed by endpoint name.

(constant) McpResult

Schema for the relevant slice of an MCP tools/call result: result.content[] items with type and text.

(constant) MessageGroup

Experimental v2 message route group, exposing a single endpoint that retrieves projected v2 messages for a session with order-based or cursor-based pagination. Guarded by authorization middleware.

(constant) MessageID

Branded schema for message identifiers. Exposes static helpers: ascending(id) to make a time-ascending message ID and zod for the zod codec.

(constant) MessagesQuery

Query-string schema for listing messages, supporting an optional non-negative integer limit and a before cursor.

(constant) MultiOccurrenceReplacer

Replacer that yields the exact search string once for every occurrence in the content, letting the caller decide how to handle multiple matches (e.g. via replaceAll).

(constant) Parameters

Parameter schema for the apply_patch tool: the full patchText describing all file changes.

(constant) Parameters

Parameter schema for the edit tool: the filePath to modify, the oldString to find, the newString to substitute, and an optional replaceAll flag.

(constant) Parameters

Parameter schema for the glob tool: the required glob pattern and an optional path directory to search in.

(constant) Parameters

Parameter schema for the grep tool: the required regex pattern, an optional path to search in, and an optional include glob to limit which files are scanned.

(constant) Parameters

Parameter schema for the invalid tool: the offending tool name and the validation error message.

(constant) Parameters

Parameter schema for the lsp tool: the operation to run, the filePath, the 1-based line and character position, and an optional query (used by workspaceSymbol).

(constant) Parameters :Object

Parameter schema for the plan_exit tool: takes no parameters.

Type:
  • Object

(constant) Parameters :Object

Parameter schema for the question tool: a mutable array of question prompts.

Type:
  • Object

(constant) Parameters :Object

Parameter schema for the read tool: an absolute file or directory path with optional 1-indexed offset and limit line/entry counts.

Type:
  • Object

(constant) Parameters :Object

Default shell tool parameter schema, using the bash description text.

Type:
  • Object

(constant) Parameters

Schema for the skill tool parameters: the name of the skill to load.

(constant) Parameters

Schema for the task tool parameters: description, prompt, subagent_type, and optional task_id (to resume) and command.

(constant) Parameters

Schema for the todowrite tool parameters: the full updated array of todo items.

(constant) Parameters

Schema for the webfetch tool parameters: url, output format (text/markdown/html, default markdown), and optional timeout in seconds.

(constant) Parameters

Schema for the websearch tool parameters: query, optional numResults, livecrawl mode, search type, and contextMaxCharacters.

(constant) Parameters

Schema for the write tool parameters: the content to write and the absolute filePath to write it to.

(constant) Params

Path-params schema identifying a PTY session by its id.

(constant) PartID

Branded schema for message part identifiers. Exposes static helpers: ascending(id) to make a time-ascending part ID and zod for the zod codec.

(constant) PathInfo

Success schema for the path endpoint: the instance's home, state, config, worktree, and directory paths.

(constant) PermissionApi

HttpApi definition for the experimental permission route group. Bundles the list and reply endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) PermissionResponsePayload

Request body schema for responding to a permission request, carrying the user's approve/deny reply.

(constant) PlanExitTool :Object

The "plan_exit" tool. Prompts the user to approve the completed plan; on "No" it raises a RejectedError to stay in the plan agent, and on approval it appends a synthetic user message switching the session to the build agent (reusing the last user model, or the provider default) and instructing it to execute the plan.

Type:
  • Object

(constant) ProjectApi

HttpApi definition for the experimental project route group. Bundles the list/current/initGit/update endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) PromptInput

Input schema for prompt: the session, optional model/agent/variant, output format, and the prompt parts (text/file/agent/subtask).

(constant) PromptPayload

Request body schema for sending a prompt, derived from SessionPrompt.PromptInput minus the path-supplied sessionID.

(constant) ProviderApi

HttpApi definition for the experimental provider route group. Bundles the list/auth/authorize/callback endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) PtyApi

HttpApi definition for the experimental PTY route group. Bundles the shells/list/create/get/update/remove endpoints under instance-context, workspace-routing, and authorization middleware.

(constant) PtyConnectApi

HttpApi definition for the PTY websocket connect route group. Exposes the single connect endpoint used to attach to a PTY session in real time (no instance middleware).

(constant) PtyPaths

URL path constants for each PTY route, keyed by endpoint name.

(constant) PublicApi

The public closedcode HttpApi, annotated with OpenAPI metadata and the legacy-compatibility spec transform.

(constant) QueryBoolean

Query-string boolean schema that decodes the strings "true"/"false" to a boolean and back.

(constant) QuestionApi

HttpApi surface for the question group, exposing endpoints to list pending question requests and to reply to or reject a specific request. The group is guarded by instance-context, workspace-routing, and authorization middleware.

(constant) QuestionTool :Object

The "question" tool. Presents the supplied questions to the user via the Question service, then returns a human-readable summary of the answers (with unanswered questions marked "Unanswered") plus the raw answers in metadata.

Type:
  • Object

(constant) ReadTool :Object

The "read" tool. Resolves the requested path, checks permissions and external directory access, then renders a directory listing, an image/PDF attachment, or a paged, byte/line-capped text view; binary files are rejected. Also warms the LSP and appends any resolved instruction files as a system reminder.

Type:
  • Object

(constant) ReplayEvent

Schema for a single sync event to replay, identified by event ID, aggregate ID, sequence number, type, and free-form data.

(constant) ReplayPayload

Request body schema for the replay endpoint: the target directory and a non-empty array of events to replay.

(constant) ReplayResponse

Response schema for the replay endpoint, returning the session ID produced by the replay.

(constant) ReplyPayload

Payload schema for replying to a permission request: the reply decision plus an optional message.

(constant) ReplyPayload

Request body schema for replying to a question: an array of user answers, one per question, in order.

(constant) RequestPlan

Tagged enum describing how a request should be handled: Local, Remote, or MissingWorkspace.

(constant) RevertInput

Input schema for a revert request: the session plus the message (and optional part) to revert back to.

(constant) RevertPayload

Request body schema for reverting a message, derived from SessionRevert.RevertInput minus the path-supplied sessionID.

(constant) RootHttpApi

Root (control-plane) HttpApi: control + global route groups.

(constant) SINGLE_CANDIDATE_SIMILARITY_THRESHOLD

Minimum middle-line similarity to accept a block-anchor match when there is exactly one candidate (anchors alone suffice).

(constant) SYNTHETIC_ATTACHMENT_PROMPT

Error shape thrown by fetch() when gzip/br decompression fails mid-stream

(constant) SearchArgs

Schema for the arguments passed to the Exa search tool: query, search type, result count, livecrawl mode, and optional context size cap.

(constant) SearchTool :Object

The "search" tool: a plain alias that exposes the grep implementation under the id "search" so models that insist on calling a search tool succeed.

Type:
  • Object

(constant) SessionApi

Experimental HttpApi surface for the session group, exposing the full set of session endpoints (list, status, get, children, todo, diff, messages, create, delete, update, fork, abort, init, share, summarize, prompt, command, shell, revert, permission response, and message/part mutations). The group is guarded by instance-context, workspace-routing, and authorization middleware.

(constant) SessionCursor :Object

Schema describing the decoded session pagination cursor, including the active list filters so paging keeps them stable.

Type:
  • Object

(constant) SessionGroup

Experimental v2 session route group, exposing endpoints to list sessions (order-based or cursor-based pagination), send a prompt, compact the conversation, wait for the agent loop to become idle, and retrieve the active context messages. Guarded by authorization middleware.

(constant) SessionID

Branded schema for session identifiers. Exposes static helpers: descending(id) to make a time-descending session ID and zod for the zod codec.

(constant) SessionListQuery

Query params for filtering the cross-project session list (directory, roots, time, search, pagination, archived).

(constant) SessionPaths

Map of endpoint name to URL path template for every session route.

(constant) SessionRestorePayload

Request body schema for restoring a session into a workspace, derived from Workspace.SessionRestoreInput minus the path-supplied workspaceID.

(constant) SessionRestoreResponse

Response schema for the session-restore endpoint, returning the total number of events scheduled for replay.

(constant) ShellInput

Input schema for shell: the session, agent/model, and the command string to run.

(constant) ShellItem

Schema for a discoverable shell: its path, display name, and whether it is acceptable for use.

(constant) ShellPayload

Request body schema for running a shell command, derived from SessionPrompt.ShellInput minus the path-supplied sessionID.

(constant) ShellTool :Object

The shell tool. Selects the configured shell, parses each command to find the file/path arguments and directories it touches (prompting for read/external access permissions), then runs the command with streamed output, byte/line truncation to a spill file, a configurable timeout, and abort handling.

Type:
  • Object

(constant) SimpleReplacer

Replacer that yields the search string verbatim (exact match candidate).

(constant) SkillTool

The "skill" tool. Resolves a skill by name, asks for permission to load it, then returns the skill's markdown content plus a sampled list of its files (excluding SKILL.md) so the model can reference them by absolute path. Fails if the named skill is not found, listing the available skills.

(constant) Status

Effect Schema describing a formatter's reported status: its name, supported extensions, and whether it is enabled.

(constant) StatusMap

Schema mapping each MCP server name to its connection status.

(constant) StatusMap

Response schema mapping each session ID to its current status info.

(constant) SummarizePayload

Request body schema for summarizing a session: the provider/model to use and an optional auto flag.

(constant) SyncApi

Experimental HttpApi surface for the sync group, exposing endpoints to start workspace sync loops, replay a complete event history, and list sync events. The group is guarded by instance-context, workspace-routing, and authorization middleware.

(constant) SyncPaths

Map of endpoint name to URL path template for every sync route.

(constant) TRUNCATION_DIR

Absolute path to the directory holding persisted full tool output ("tool-output" under the global data path).

(constant) TaskTool

The "task" tool. Validates the requested subagent type and permissions, creates a fresh child session (or resumes the one named by task_id), derives the model from the agent or the parent assistant message, runs the subagent prompt to completion, and returns its last text part as the result. Wires the abort signal to cancel the subagent run.

(constant) TodoItem

Schema for a single todo item: content (description), status, and priority.

(constant) TodoWriteTool

The "todowrite" tool. After requesting permission, replaces the current session's todo list with the supplied array and returns a summary of the remaining (non-completed) count plus the serialized list.

(constant) ToolID :Object

Branded ToolID schema with attached static helpers. Exposes ascending(id) to mint a new monotonically-increasing tool ID and zod for the equivalent Zod schema.

Type:
  • Object

(constant) ToolID :string

The stable, externally-visible tool ID and permission key for the shell tool. Kept as "bash" for backwards compatibility with plugins and saved permissions.

Type:
  • string

(constant) ToolListQuery

Query params selecting the provider/model whose tools should be listed.

(constant) TrimmedBoundaryReplacer

Replacer that retries matching after trimming the search text's leading/trailing whitespace, yielding the trimmed string if found directly or any content block whose trimmed form equals it. No-ops when the search text is already trimmed.

(constant) TuiApi

Experimental HttpApi surface for the TUI group, exposing endpoints to append or submit prompts, open dialogs, show toasts, execute and publish events, select sessions, and pump the control request/response queue. The group is guarded by instance-context, workspace-routing, and authorization middleware.

(constant) TuiPaths

Map of endpoint name to URL path template for every TUI route.

(constant) TuiPublishPayload

Request body schema for the publish endpoint: any one of the supported TUI events.

(constant) TuiRequestPayload

Schema for a queued TUI control request, describing the target path and an opaque body.

(constant) URL

Exa MCP endpoint URL, with the EXA_API_KEY query param appended when that env var is set.

(constant) UpdatePayload

Payload schema for updating a project: optional name, icon, and commands fields.

(constant) UpdatePayload

Request body schema for updating a session: optional title, permission ruleset, and archived timestamp.

(constant) V2Api

Experimental v2 HttpApi surface, composed of the v2 session group and the v2 message group.

(constant) VcsDiffQuery

Query schema for the VCS diff endpoint: which diff mode to compute (e.g. working tree vs default branch).

(constant) WebFetchTool

The "webfetch" tool. Validates the URL scheme, requests permission, fetches the URL with a format-aware Accept header (retrying with an honest UA when blocked by Cloudflare), enforces a 5MB response cap and timeout, and returns the body in the requested format. Images are returned as a base64 data-URL attachment.

(constant) WebSearchTool

The "websearch" tool. After requesting permission, calls the Exa web_search_exa MCP endpoint with the query and options, and returns the resulting context string (or a not-found message). The description is rendered dynamically with the current year substituted for {{year}}.

(constant) WhitespaceNormalizedReplacer

Replacer that matches by collapsing all runs of whitespace to single spaces, handling both single-line (full-line or substring) and multi-line matches, and yields the matching raw substring of the content.

(constant) WorkspaceApi

Experimental HttpApi surface for the workspace group, exposing endpoints to list available workspace adapters, list/create workspaces, query connection status, remove a workspace, and restore a session's events into a workspace. The group is guarded by instance-context, workspace-routing, and authorization middleware.

(constant) WorkspacePaths

Map of endpoint name to URL path template for every workspace route.

(constant) WriteTool

The "write" tool. Resolves the target path (relative to the instance directory if needed), guards external-directory access, computes a diff for the permission prompt, writes the content while preserving any byte-order mark, runs the configured formatter, publishes file edit/update events, and appends LSP diagnostics (for the written file and up to a few other affected files) to the output.

(constant) adapter :Object

The Express runtime adapter implementation.

Type:
  • Object

(constant) ask

Issue the permission prompts implied by a scan result: an external-directory prompt for out-of-tree file directories and a shell-command prompt for the command patterns.

(constant) assertExternalDirectoryEffect

Effect that asserts a target path lies within the current instance directory, and otherwise raises an "external_directory" permission prompt for the target's containing directory. Resolves to nothing (the side effect is the permission check); does not modify the path.

(constant) authorizationLayer

Layer implementing the Authorization HttpApi middleware service. Wires the basic and authToken security schemes to credential validation against ServerAuthConfig.

(constant) authorizationRouterMiddleware

Router middleware that enforces authorization for raw (non-HttpApi) routes. When auth is required, it reads the credential from the Authorization: Basic header or the auth_token query parameter (or an empty credential as a last resort) and validates it before delegating to the wrapped effect.

(constant) biome :Object

Biome formatter for web/JS/TS and config/markup files. enabled(context) looks for biome.json/biome.jsonc up the tree, then resolves @biomejs/biome via npm.

Type:
  • Object

(constant) call

Invokes a named Exa MCP tool over HTTP and returns its first text content block.

(constant) clang :Object

clang-format formatter for C/C++ files. enabled(context) requires a .clang-format config up the tree and clang-format on PATH.

Type:
  • Object

(constant) client

The createClientConfig() function will be called on client initialization and the returned object will become the client's initial configuration.

You may want to initialize your client this way instead of calling setConfig(). This is useful for example if you're using Next.js to ensure your client always has the correct values.

(constant) cljfmt :Object

cljfmt formatter for Clojure files. Enabled when cljfmt is on PATH.

Type:
  • Object

(constant) commandAliases :Object

Maps legacy TUI command names to their current canonical command ids.

Type:
  • Object

(constant) configHandlers

Builds the request handlers for the "config" HttpApi group, wiring the get, update, and providers endpoints to the Config and Provider services.

(constant) context

Shared, empty Effect context used as the base context for the server's request runtime.

(constant) controlHandlers :Object

Registers the handlers for the "control" HTTP API group on the root API.

Type:
  • Object

(constant) create

Validated entry point that starts a new compaction for a session. Validates input against the schema, then runs the service's create method.

(constant) cursor :Object

Codec for the message pagination cursor: a base64url-encoded JSON blob carrying a message id, its creation time (epoch millis), the sort order, and the paging direction.

Type:
  • Object

(constant) cursor

Opaque pagination cursor codec: encodes/decodes a { id, time } keyset cursor as a base64url string for use in message pagination.

(constant) dart :Object

dart formatter for Dart files. Enabled when dart is on PATH.

Type:
  • Object

(constant) decode

Decoder that parses a JSON string into an McpResult.

(constant) decodePtyID :function

Synchronously decodes and validates an unknown value into a PtyID, throwing on invalid input.

Type:
  • function

(constant) defaultLayer

The SessionStatus layer with its Bus dependency provided.

(constant) defaultLayer

The SessionSummary layer with all its dependencies (Session, Snapshot, Storage, Bus) provided.

(constant) defaultLayer

The SystemPrompt layer with its Skill dependency provided.

(constant) defaultLayer

The SessionTodo layer with its Bus dependency provided.

(constant) defaultLayer :Object

The ToolRegistry layer wired with all of its default dependency layers (config, plugin, question, todo, skill, agent, session, provider, LSP, etc.).

Type:
  • Object

(constant) defaultLayer

Format service Layer with its default Config and cross-spawn spawner dependencies provided.

(constant) defaultWebHandler

Lazily-constructed default web handler over routes, with deferred instance disposal as outer middleware.

description

Tool description with the {{year}} placeholder replaced by the current year.

(constant) dfmt :Object

dfmt formatter for D files. Enabled when dfmt is on PATH.

Type:
  • Object

(constant) disposeAllInstancesAndEmitGlobalDisposed

Dispose every active instance from the InstanceStore and then emit the global "disposed" event. The whole sequence is run uninterruptibly so disposal and notification cannot be torn apart.

(constant) disposeMiddleware

Outer server middleware that performs deferred instance disposal after a handler has produced its response. Looks up any instance previously marked via markInstanceForDisposal (keyed by the request source), removes the mark, and uninterruptibly runs the store disposal before returning the response.

(constant) emitGlobalDisposed :Effect

Effect that emits a global "disposed" event on the global bus for the "global" directory.

Type:
  • Effect

(constant) emptyConsoleState

A default, empty ConsoleState (no managed providers, no active org).

environment

Builds the <env> system-prompt block describing the model id, working/worktree directories, VCS, platform, and date.

(constant) eventApiRoutes

Layer building the event (SSE) API routes, served behind the instance router middleware.

(constant) eventHandlers

Effect HttpApi handler group wiring the "subscribe" endpoint to the SSE event response.

(constant) experimentalHandlers :Object

Registers the handlers for the "experimental" HTTP API group on the instance API.

Type:
  • Object

(constant) fileHandlers :Object

Registers the handlers for the "file" HTTP API group on the instance API.

Type:
  • Object

(constant) filterCompactedEffect

Effect variant of filterCompacted that streams a session's messages from the database, collects them, and returns the compaction-filtered list.

(constant) getParseAs

Infers parseAs value from provided Content-Type header.

(constant) gleam :Object

gleam formatter for Gleam files. Enabled when gleam is on PATH.

Type:
  • Object

(constant) globalHandlers :Object

Registers the handlers for the "global" HTTP API group on the root API.

Type:
  • Object

(constant) gofmt :Object

gofmt formatter for Go files. Enabled when gofmt is on PATH. enabled() returns the command array or false.

Type:
  • Object

(constant) hop :Set.<string>

Set of hop-by-hop header names that must not be forwarded to an upstream target.

Type:
  • Set.<string>

(constant) htmlbeautifier :Object

htmlbeautifier formatter for ERB/HTML-ERB files. Enabled when htmlbeautifier is on PATH.

Type:
  • Object

(constant) inputUndoDefault

Default binding for input_undo, with ctrl+z prepended on Windows.

(constant) instanceApiRoutes

Layer building the full instance HttpApi from every instance-scoped handler group.

(constant) instanceContextLayer

Layer implementing the InstanceContextMiddleware HttpApi service, providing instance context via the InstanceStore.

(constant) instanceHandlers :Object

Registers the handlers for the "instance" HTTP API group on the instance API.

Type:
  • Object

(constant) instanceRouterLayer

Combined router middleware (authorization + instance context + workspace routing) for raw instance routes.

(constant) instanceRouterMiddleware

Router-level middleware that provides the instance context for raw (non-HttpApi) routes via the InstanceStore.

(constant) instanceRoutes

Combined instance routes (raw + HttpApi) with authorization, workspace routing, and instance-context middleware provided.

(constant) ktlint :Object

ktlint formatter for Kotlin files. Enabled when ktlint is on PATH.

Type:
  • Object

(constant) latexindent :Object

latexindent formatter for LaTeX files. Enabled when latexindent is on PATH.

Type:
  • Object

(constant) layer

Layer that builds the SessionProcessor service, exposing a create factory for per-message processors.

(constant) layer

Layer that builds the SessionPrompt service (prompt / loop / shell / command / cancel operations).

(constant) layer

Layer that builds the SessionRevert service (revert / unrevert / cleanup operations).

(constant) layer

Layer that builds the SessionRunState service: keeps a map of session ID to Runner.

(constant) layer

Effect Layer providing the SessionStatus service, which keeps per-session status in instance state and publishes status changes on the bus.

(constant) layer

Effect Layer providing the SessionSummary service, which derives file diffs between snapshots, stores them, and exposes summarize/diff/computeDiff operations.

(constant) layer

Effect Layer providing the SystemPrompt service, which produces the environment block and the available-skills block for a prompt.

(constant) layer

Effect Layer providing the SessionTodo service, which stores todos in the database and publishes Updated events.

(constant) layer :Object

Layer that constructs the ToolRegistry service. It discovers custom tools (from tool(s)/*.js|ts in config directories and from plugins), initializes the built-in tools, and exposes ids, all, named, and tools for resolving the active tool set for a given model/agent.

Type:
  • Object

(constant) layer

Layer constructing the Truncate service. Provides cleanup, write, output, and limits operations, and forks a background fiber that purges expired truncation files once per hour (after a 1-minute startup delay).

(constant) layer

Effect Layer that constructs the Format service, wiring config and a child-process spawner into formatter discovery and execution.

(constant) locks

Per-file semaphores keyed by resolved path, used to serialize concurrent edits to the same file.

(constant) markInstanceForDisposal

Mark the current request's instance to be disposed after the response is sent. Registers a pre-response handler that stashes the captured services keyed by the source Request, which disposeMiddleware later reads to perform the teardown.

(constant) markInstanceForReload

Mark the current request's instance to be reloaded after the response is sent. Registers a pre-response handler that, once the response is ready, uninterruptibly runs the store reload using the captured bridge and returns the original response unchanged.

(constant) mcpHandlers :Object

Registers the handlers for the "mcp" HTTP API group on the instance API.

Type:
  • Object

(constant) messageHandlers :Object

Builds the "v2.message" HTTP API handler group: a single "messages" endpoint that returns a page of messages plus previous/next cursors derived from the first/last items.

Type:
  • Object

(constant) mix :Object

mix formatter for Elixir files. Enabled when mix is on PATH.

Type:
  • Object

mode

Deprecated
  • Yes

(constant) nixfmt :Object

nixfmt formatter for Nix files. Enabled when nixfmt is on PATH.

Type:
  • Object

(constant) ocamlformat :Object

ocamlformat formatter for OCaml files. enabled(context) requires ocamlformat on PATH and a .ocamlformat config up the tree.

Type:
  • Object

(constant) operations

Supported LSP operation names accepted by the tool's operation parameter.

(constant) ormolu :Object

ormolu formatter for Haskell files. Enabled when ormolu is on PATH.

Type:
  • Object

(constant) oxfmt :Object

oxfmt formatter for JS/TS files (gated behind the experimental flag). enabled(context) requires the flag and an oxfmt (dev)dependency in a nearby package.json.

Type:
  • Object

(constant) parse

Parse a command string into a tree-sitter syntax tree using the bash or PowerShell grammar.

(constant) parseSse

Parses a Server-Sent Events response body, decoding each data: line as an MCP result and returning the first non-empty text content found.

(constant) parser

Lazily initialize tree-sitter and load the bash and PowerShell grammars once, returning the two configured parsers.

(constant) permissionHandlers :Object

Registers the handlers for the "permission" HTTP API group on the instance API.

Type:
  • Object

(constant) pint :Object

Laravel Pint formatter for PHP files. enabled(context) requires laravel/pint listed in a composer.json up the tree.

Type:
  • Object

(constant) prettier :Object

Prettier formatter for web/JS/TS and many config/markup files. enabled(context) walks up from context.directory to context.worktree looking for a package.json that lists prettier as a (dev)dependency, then resolves the binary via npm.

Type:
  • Object

(constant) projectHandlers :Object

Registers the handlers for the "project" HTTP API group on the instance API.

Type:
  • Object

(constant) providerHandlers :Object

Registers the handlers for the "provider" HTTP API group on the instance API.

Type:
  • Object

(constant) ptyConnectRoute :Object

Registers the GET WebSocket route that connects a client to a PTY: it upgrades the request to a socket, adapts the socket into a minimal WebSocket-like object so the Pty service can stream output, replays from an optional cursor, and forwards incoming socket messages as PTY input until the socket closes.

Type:
  • Object

(constant) ptyHandlers :Object

Builds the "pty" HTTP API handler group: shells/list/create/get/update/remove endpoints backed by the Pty service.

Type:
  • Object

(constant) queryKeyJsonReplacer

Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.

(constant) questionHandlers :Object

Builds the "question" HTTP API handler group, wiring list/reply/reject endpoints to the Question service.

Type:
  • Object

(constant) rawInstanceRoutes

Layer for raw (non-HttpApi) instance routes such as the PTY connect upgrade, behind the instance router middleware.

(constant) requiresExtensionsForCustomServers

For custom (non-builtin) LSP server entries, extensions is required so the client knows which files the server should attach to. Builtin server IDs and explicitly disabled entries are exempt.

(constant) rlang :Object

air formatter for R files. enabled() confirms the air binary is the R language server/formatter via its --help output.

Type:
  • Object

(constant) root

Base URL path for the permission route group.

(constant) root

Base URL path for the project route group.

(constant) root

Base URL path for the provider route group.

(constant) root

Base URL path for the PTY route group.

(constant) root

Base URL path prefix for all question endpoints.

(constant) root

Base URL path prefix for all session endpoints.

(constant) root

Base URL path prefix for all sync endpoints.

(constant) root

Base URL path prefix for all TUI endpoints.

(constant) root

Base URL path prefix for all experimental workspace endpoints.

(constant) rootApiRoutes

Layer building the root (non-instance) API routes from control-plane and global handlers.

(constant) routes

The default route layer built with no custom CORS options.

(constant) rubocop :Object

rubocop formatter for Ruby files. Enabled when rubocop is on PATH.

Type:
  • Object

(constant) ruff :Object

ruff formatter for Python files. enabled(context) requires ruff on PATH plus either a ruff config (with [tool.ruff] when in pyproject.toml) or a dependency manifest that mentions ruff.

Type:
  • Object

(constant) runtime

Router middleware that selects the server backend and annotates the current span with backend attributes before running each handler.

(constant) rustfmt :Object

rustfmt formatter for Rust files. Enabled when rustfmt is on PATH.

Type:
  • Object

(constant) serializeQueryKeyValue

Normalizes any accepted value into a JSON-friendly shape for query keys.

(constant) sessionCursor :Object

Codec for the session pagination cursor: a base64url-encoded JSON blob carrying a session id, its creation time, the sort order, the paging direction, and the active list filters (so subsequent pages keep them).

Type:
  • Object

(constant) sessionHandlers :Object

Builds the "session" HTTP API handler group: the full set of session lifecycle, message, prompt, share, revert, permission, and part endpoints backed by the session-related services.

Type:
  • Object

(constant) sessionHandlers :Object

Builds the "v2.session" HTTP API handler group: sessions (paginated list), prompt, compact, wait, and context endpoints.

Type:
  • Object

(constant) shfmt :Object

shfmt formatter for shell scripts. Enabled when shfmt is on PATH.

Type:
  • Object

skills

Builds the available-skills section of the system prompt for the given agent, or returns nothing when the skill permission is disabled.

(constant) standardrb :Object

standardrb formatter for Ruby files. Enabled when standardrb is on PATH.

Type:
  • Object

(constant) stringifyToJsonValue

Safely stringifies a value and parses it back into a JsonValue.

(constant) syncHandlers :Object

Builds the "sync" HTTP API handler group: start/replay/history endpoints for cross-instance event sync.

Type:
  • Object

(constant) terraform :Object

terraform formatter for Terraform files. Enabled when terraform is on PATH.

Type:
  • Object

(constant) toModelMessagesEffect

Convert stored session messages into provider model messages. Maps each part type to its model representation: user text/file/compaction/subtask parts, assistant text/reasoning/step-start parts, and tool parts (completed, error, and interrupted pending/running calls, which are forced to errors so every tool_use has a matching tool_result as Anthropic/Claude APIs require). Media from tool results is split into a synthetic follow-up user message when the provider can't carry media in tool results. Optionally strips media and truncates tool output for compaction.

(constant) tuiHandlers :Object

Builds the "tui" HTTP API handler group: endpoints that publish TUI control events onto the bus.

Type:
  • Object

(constant) uiRoute

Catch-all UI route layer that serves the web UI (and proxies dev assets) behind authorization middleware.

(constant) uvformat :Object

uv formatter for Python files, used only when ruff is not already enabled. enabled(context) checks uv is on PATH and supports format via its --help output.

Type:
  • Object

(constant) v2Handlers :Object

Combined v2 handlers layer: merges the v2 session and message handler groups and provides the SessionV2 default layer.

Type:
  • Object

(constant) workspaceHandlers :Object

Builds the "workspace" HTTP API handler group: adapters/list/create/status/remove/sessionRestore endpoints.

Type:
  • Object

(constant) workspaceRouterMiddleware

Router-level workspace routing middleware for raw (non-HttpApi) routes; plans and routes each request without session lookup.

(constant) workspaceRoutingLayer

Layer implementing the WorkspaceRoutingMiddleware HttpApi service, wiring the WebSocket constructor, Workspace service, and HTTP client into routing.

(constant) zig :Object

zig formatter for Zig files. Enabled when zig is on PATH.

Type:
  • Object

Methods

ConfigRoutes(registry) → {express.Router}

Build the Express router for the "/config" route group (GET/PATCH "/" and GET "/providers").

Parameters:
NameTypeDescription
registryObject

Optional OpenAPI registry to record operation metadata against; falsy disables registration.

Returns:

The configured Express router.

Type: 
express.Router

ControlPlaneRoutes(registry) → {express.Router}

Build the Express router for the control-plane route group (PUT/DELETE "/auth/:providerID", GET "/doc", POST "/log").

Parameters:
NameTypeDescription
registryObject

Optional OpenAPI registry to record operation metadata against; also used to build the /doc spec.

Returns:

The configured Express router.

Type: 
express.Router

CorsMiddleware(opts) → {function}

Build CORS middleware whose origin callback delegates to isAllowedCorsOrigin(opts).

Parameters:
NameTypeDescription
optsObject

Options forwarded to the origin check (opts.cors allow-list).

Returns:

The configured cors() Express middleware.

Type: 
function

EventRoutes(registry) → {express.Router}

Build the Express router exposing GET "/event", a Server-Sent Events stream of bus events. Each connection emits an initial "server.connected" event, periodic "server.heartbeat" events, and forwards all subscribed bus events until the client disconnects or the instance is disposed.

Parameters:
NameTypeDescription
registryObject

Optional OpenAPI registry to record operation metadata against; falsy disables registration.

Returns:

The configured Express router.

Type: 
express.Router

ExperimentalRoutes(registry) → {express.Router}

Build the Express router for the "/experimental" route group (Console org metadata/list/switch, tool ids/list, worktree create/list/remove/reset, global session list, and MCP resources).

Parameters:
NameTypeDescription
registryObject

Optional OpenAPI registry to record operation metadata against; falsy disables registration.

Returns:

The configured Express router.

Type: 
express.Router

FileRoutes(registry) → {Object}

Builds the Express router for the file/find route group (find text/files/symbols, list, read, git status).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

GlobalRoutes(registry) → {Object}

Builds the Express router for the /global route group (health, SSE event stream, global config, dispose, upgrade).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

InstanceMiddleware(envWorkspaceID) → {function}

Build the instance-resolution middleware. For each request it resolves the effective workspace and adapter target, then: responds 500 for a missing workspace, proxies remote targets, or runs downstream handlers locally with the resolved (or default) directory.

Parameters:
NameTypeDescription
envWorkspaceIDstring

Optional workspace ID from the environment/flag to bias resolution.

Returns:

An Express middleware (req, res, next).

Type: 
function

InstanceMiddleware(workspaceID) → {function}

Build middleware that establishes the workspace and instance context for a request. Resolves the target directory from the directory query param or x-closedcode-directory/x-opencode-directory headers (falling back to the process cwd), then runs the next handler inside that workspace and instance scope.

Parameters:
NameTypeDescription
workspaceIDstring

The workspace identifier to bind for the request.

Returns:

An async middleware (c, next) that provides workspace and instance context.

Type: 
function

InstanceRoutes(registry, upgradeWebSocket) → {Object}

Builds the aggregate Express router for an instance: mounts every instance route group and the inline instance-root routes (/instance/dispose, /path, /vcs, /command, /agent, /skill, /lsp, /formatter).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

upgradeWebSocketfunction

Adapter factory that produces WebSocket-upgrade middleware (forwarded to PtyRoutes).

Returns:

The configured Express Router for the instance.

Type: 
Object

LoggerMiddleware(backendAttributes) → {function}

Build request-logging middleware that logs each request (skipping /log) and times it until the response finishes or closes.

Parameters:
NameTypeDescription
backendAttributesObject

Backend attributes merged into every log entry.

Returns:

An Express middleware (req, res, next).

Type: 
function

McpRequest(args) → {Object}

Builds the JSON-RPC tools/call request schema for a given arguments schema.

Parameters:
NameTypeDescription
argsObject

The Effect Schema describing the tool's arguments payload.

Returns:

A Schema.Struct describing the full JSON-RPC request envelope.

Type: 
Object

McpRoutes(registry) → {Object}

Builds the Express router for the /mcp route group (MCP server status/add/connect/disconnect and OAuth flows).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

PermissionRoutes(registry) → {Object}

Builds the Express router for the /permission route group (reply to a permission request, list pending requests).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

ProjectRoutes(registry) → {Object}

Builds the Express router for the /project route group (list projects, current project, git init, update).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

ProviderRoutes(registry) → {Object}

Builds the Express router for the /provider route group (list providers, auth methods, OAuth authorize/callback).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

PtyRoutes(registry, upgradeWebSocket) → {Object}

Builds the Express router for the /pty route group (list shells, PTY session list/create/get/update/remove, and a WebSocket route for real-time PTY interaction).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

upgradeWebSocketfunction

Adapter factory that produces WebSocket-upgrade middleware for the connect route.

Returns:

The configured Express Router for this group.

Type: 
Object

QuestionRoutes(registry) → {Object}

Builds the Express router for the /question route group (list pending questions, reply with answers, reject).

Parameters:
NameTypeDescription
registryObject

The OpenAPI registry used to register route metadata (may be falsy to skip).

Returns:

The configured Express Router for this group.

Type: 
Object

SessionRoutes(registry) → {Object}

Builds the Express router for the instance /session endpoints (list, get, create, update, fork, abort, share, messages, parts, prompts, commands, revert, permissions, etc.).

Parameters:
NameTypeDescription
registryObject

OpenAPI operation registry; route metadata is registered against it when present.

Returns:

Configured Express Router.

Type: 
Object

SyncRoutes(registry) → {Object}

Builds the Express router for the instance /sync endpoints: start workspace syncing, replay a full sync event history, and list sync events since known sequence IDs.

Parameters:
NameTypeDescription
registryObject

OpenAPI operation registry; route metadata is registered against it when present.

Returns:

Configured Express Router.

Type: 
Object

TuiRoutes(registry) → {Object}

Builds the Express router for the instance /tui endpoints: publishing TUI events (prompt append/submit/clear, open dialogs, toasts, command execution, session select) and the /control request/response queue bridge.

Parameters:
NameTypeDescription
registryObject

OpenAPI operation registry; route metadata is registered against it when present.

Returns:

Configured Express Router.

Type: 
Object

UIRoutes(registry) → {Object}

Builds the Express router that serves the embedded web UI via a catch-all route.

Parameters:
NameTypeDescription
registryObject

OpenAPI operation registry (unused here; this route registers no metadata).

Returns:

Configured Express Router.

Type: 
Object

WorkspaceRoutes(registry) → {express.Router}

Build the Express router for the "/experimental/workspace" route group (adapter listing, workspace create/list/status/remove, and session restore).

Parameters:
NameTypeDescription
registryObject

Optional OpenAPI registry to record operation metadata against; falsy disables registration.

Returns:

The configured Express router.

Type: 
express.Router

addLegacyErrorSchemas(spec) → {void}

Add the legacy BadRequestError and NotFoundError component schemas the old SDK expected.

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

applyLegacySchemaOverrides(spec) → {void}

Apply hand-tuned schema overrides so specific component schemas match the legacy SDK (e.g. open additionalProperties, string Command.template, and nullable Workspace/session/provider fields).

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

assertExternalDirectory(ctx, target, options) → {Promise.<void>}

Promise-returning wrapper around assertExternalDirectoryEffect for callers outside the Effect runtime; runs the guard with the logger layer provided.

Parameters:
NameTypeDescription
ctxObject

Tool execution context exposing the ask permission helper.

targetstring

The absolute path the tool intends to access.

optionsObject

Optional behavior flags (bypass, kind) passed through to the underlying Effect.

Returns:

Resolves once the path is allowed or permission has been granted.

Type: 
Promise.<void>

attributes(selection) → {Object}

Build telemetry/log attributes describing the selected backend and installation.

Parameters:
NameTypeDescription
selectionObject

The backend selection to describe.

Returns:

A flat map of dotted attribute keys to their string values.

Type: 
Object

auto(key, cwd, shell) → {string}

Resolve the value of an automatic shell variable (HOME, PWD, PSHOME).

Parameters:
NameTypeDescription
keystring

The variable name (case-insensitive).

cwdstring

The current working directory (value for PWD).

shellstring

The shell executable path (PSHOME is its directory).

Returns:

The variable value, or undefined if not an automatic variable.

Type: 
string

bashCommandSection(chain, limits) → {string}

Build the bash-specific "command section" of the tool description, covering directory verification, quoting, output limits, and command chaining.

Parameters:
NameTypeDescription
chainstring

The chaining guidance sentence to embed.

limitsObject

Output limits with maxLines and maxBytes.

Returns:

The rendered bash command-section text.

Type: 
string

bridgeRemote(inbound, wsURL, protocols, headers) → {void}

Bridge an already-upgraded inbound WebSocket to a freshly-dialed outbound one. Inbound messages are queued until the outbound socket opens, then forwarded raw in both directions; close/error codes propagate across (1011 on error), with invalid close codes guarded so close() can't throw.

Parameters:
NameTypeDescription
inboundObject

The upgraded inbound ws connection.

wsURLstring

The remote WebSocket target URL.

protocolsArray.<string>

WebSocket subprotocols to request (empty = none).

headersObject

Outbound handshake headers (sanitized + target auth).

Returns:
Type: 
void

buildPrompt(input) → {string}

Compose the compaction prompt: an anchor instruction (create-new vs update-existing), the fixed summary template, and any plugin-supplied context.

Parameters:
NameTypeDescription
inputObject

{ previousSummary, context } where previousSummary may be undefined and context is an array of extra strings.

Returns:

The full prompt text sent to the compaction model.

Type: 
string

buildSpec(registry, documentation) → {Object}

Build the final OpenAPI document from the registry, merged with the Effect httpapi contract's paths and components on top of a plain base document.

Parameters:
NameTypeDescription
registryObject

The registry of collected operations and schemas.

documentationObject

Top-level overrides (openapi version, info).

Returns:

The complete OpenAPI document.

Type: 
Object

callTui(ctx) → {Promise.<*>}

Forwards a request to the TUI and waits for its matching response. Reads the JSON body from the context, enqueues a TUI request, then awaits the next response.

Parameters:
NameTypeDescription
ctxObject

Request context exposing req.json() and req.path.

Returns:

Promise resolving to the TUI's response payload.

Type: 
Promise.<*>

canonicalRef(ref, schemas) → {string}

Resolve a $ref to its canonical form, mapping numeric-suffixed names to their base name when that base exists.

Parameters:
NameTypeDescription
refstring

The original $ref string.

schemasObject

The component schemas map used to detect base names.

Returns:

The canonical $ref string.

Type: 
string

canonicalizeSchema(input, schemas) → {*}

Recursively canonicalize a schema for structural comparison: sort object keys, drop description, and rewrite $refs to their canonical (base) form.

Parameters:
NameTypeDescription
input*

The schema (or fragment) to canonicalize.

schemasObject

The component schemas map used to canonicalize $refs.

Returns:

The canonicalized schema value.

Type: 
*

cap(ms) → {number}

Clamps a delay so it never exceeds the maximum safe setTimeout value.

Parameters:
NameTypeDescription
msnumber

Proposed delay in milliseconds.

Returns:

The delay capped at RETRY_MAX_DELAY.

Type: 
number

chainGuidance(name) → {string}

Return guidance on how to chain dependent commands for the given shell (PowerShell 5.1 lacks &&; other shells get &&/& advice).

Parameters:
NameTypeDescription
namestring

Shell name.

Returns:

The chaining guidance sentence for that shell.

Type: 
string

cmd(shell, command, cwd, env) → {Object}

Build the ChildProcess spec to run a command: on Windows PowerShell it invokes the shell with -Command, otherwise it runs the command through the shell's -c/shell option, detaching on non-Windows platforms.

Parameters:
NameTypeDescription
shellstring

The shell executable path.

commandstring

The command string to execute.

cwdstring

The working directory.

envObject

The environment variables.

Returns:

A ChildProcess specification.

Type: 
Object

cmdCommandSection(chain, limits) → {string}

Build the cmd.exe-specific "command section" of the tool description, covering notes, directory verification, quoting, output limits, and chaining.

Parameters:
NameTypeDescription
chainstring

The chaining guidance sentence to embed.

limitsObject

Output limits with maxLines and maxBytes.

Returns:

The rendered cmd.exe command-section text.

Type: 
string

collapseDuplicateComponents(spec) → {void}

Collapse numeric-suffixed duplicate component schemas (e.g. Foo2) into their base name (Foo) when the schemas are structurally equal, rewriting all $refs and deleting the duplicate.

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

commands(node) → {Array}

Collect all command descendant nodes within a parse tree node.

Parameters:
NameTypeDescription
nodeObject

A tree-sitter syntax node (typically the root).

Returns:

An Array of command syntax nodes.

Type: 
Array

completedCompactions(messages) → {Array}

Find the prior completed compactions in a message list: each is an assistant summary message that finished without error, paired with the index of the user (compaction) message that triggered it.

Parameters:
NameTypeDescription
messagesArray

Ordered session messages, each { info, parts }.

Returns:

Items { userIndex, assistantIndex, summary } for every completed compaction.

Type: 
Array

componentTypeName(name) → {string}

Convert a dotted component name into a PascalCase type name, dropping purely numeric path segments.

Parameters:
NameTypeDescription
namestring

The component name (possibly dotted, e.g. foo.bar.2).

Returns:

The PascalCase type name (unchanged when the name contains no dot).

Type: 
string

configEntryNameFromPath(filePath, searchRoots) → {string}

Compute the config entry name for a file: the path after a matching search root (or the basename when none match), with its extension stripped.

Parameters:
NameTypeDescription
filePathstring

The config file path.

searchRootsArray.<string>

Root substrings used to make the name relative.

Returns:

The extension-less entry name.

Type: 
string

configuredWorkspaceID() → {*}

Read the workspace ID pinned via the CLOSEDCODE_WORKSPACE_ID flag, if any.

Returns:

The configured WorkspaceID, or undefined when the flag is unset.

Type: 
*

convertHTMLToMarkdown(html) → {string}

Converts an HTML document to Markdown using Turndown, removing script, style, meta, and link elements.

Parameters:
NameTypeDescription
htmlstring

The raw HTML source.

Returns:

The Markdown rendering of the HTML.

Type: 
string

convertToLineEnding(text, ending) → {string}

Converts LF line endings in the text to the requested ending.

Parameters:
NameTypeDescription
textstring

LF-normalized text.

endingstring

The target line ending ("\n" leaves the text unchanged, otherwise CRLF is used).

Returns:

The text with line endings converted to ending.

Type: 
string

cors(corsOptions) → {*}

Build a global CORS router middleware that allows origins per the configured CORS options.

Parameters:
NameTypeDescription
corsOptions*

The server CORS configuration consulted by the allowed-origin check.

Returns:

A global router middleware layer applying CORS with a one-day max-age.

Type: 
*

createExpress(opts, selection) → {Object}

Build the Express application: wires the root middleware chain, mounts every route group against a shared OpenAPI registry, builds the OpenAPI spec, serves the docs, and registers the error handler.

Parameters:
NameTypeDescription
optsObject

Server options (e.g. opts.cors allow-list) passed to CorsMiddleware.

selectionObject

The backend selection; defaults to ServerBackend.select().

Returns:

The fetch-wrapped Express app, the adapter runtime, and a getter returning the built OpenAPI spec.

Type: 
Object

createInProcessFetch(expressApp) → {Object}

Wrap an Express app with fetch/request methods that drive it over an in-process loopback HTTP server. The lazily-started server has per-request timeouts disabled so long agent loops (run inside a single request) are not capped at 5 minutes. Does not mutate expressApp.request.

Parameters:
NameTypeDescription
expressAppObject

The Express application to wrap.

Returns:

An object exposing fetch(input, init) and request(input, init).

Type: 
Object

createRegistry() → {Object}

Create an empty per-app registry for collecting OpenAPI operations and named schemas.

Returns:

A fresh registry.

Type: 
Object

createRoutes(corsOptions) → {*}

Build the complete route layer for the server, merging root, event, instance, and UI routes and providing all required service layers (CORS, runtime, and every feature service layer).

Parameters:
NameTypeDescription
corsOptions*

The server CORS configuration applied to the global CORS middleware.

Returns:

A fully-wired Effect Layer for the HTTP router.

Type: 
*

createStructuredOutputTool(input) → {*}

Builds the special StructuredOutput AI SDK tool used when the prompt requests JSON-schema output. The tool validates the model's arguments against the schema (with $schema stripped) and invokes onSuccess with the captured output.

Parameters:
NameTypeDescription
inputObject

{ schema, onSuccess } where schema is the JSON schema and onSuccess receives the validated output.

Returns:

An AI SDK tool definition.

Type: 
*

createWebSocket() → {Object}

Build the WebSocket upgrade machinery for the Express adapter. Returns an upgradeWebSocket route-handler factory (registers per-path WS handlers) and an injectWebSocket(server) injector that handles HTTP upgrade events, dispatching to local routes or remote-workspace proxying.

Returns:

An object with upgradeWebSocket and injectWebSocket.

Type: 
Object

decode(input) → {string}

URI-decode a value, returning the original input unchanged if decoding throws.

Parameters:
NameTypeDescription
inputstring

The possibly URI-encoded string.

Returns:

The decoded string, or input when decoding fails.

Type: 
string

decodeCredential(input) → {Effect}

Decode a Base64-encoded username:password string into a credential, falling back to empty values on failure.

Parameters:
NameTypeDescription
inputstring

The Base64-encoded username:password string.

Returns:

An effect resolving to {username, password} with a Redacted password.

Type: 
Effect

defaultDirectory(req) → {string}

Resolve the project directory for the plain (non-workspace) path from the request's directory query param or x-closedcode/x-opencode-directory header, falling back to the current working directory.

Parameters:
NameTypeDescription
reqObject

The Express request (uses query.directory and directory headers).

Returns:

The resolved absolute directory path.

Type: 
string

defaultDirectory(request, url) → {string}

Resolve the directory for a locally handled request from the directory query param, the x-closedcode-directory/x-opencode-directory headers, or the process cwd.

Parameters:
NameTypeDescription
requestObject

The HTTP server request.

urlURL

The parsed request URL.

Returns:

The resolved working directory.

Type: 
string

define(id, init) → {Effect}

Defines a tool. Returns an Effect (with an attached id) that resolves the tool's setup, acquires the Truncate and Agent services, and yields a record with the tool id plus a lazy init (the wrapped execute pipeline).

Parameters:
NameTypeDescription
idstring

The tool identifier.

initEffect

An Effect that resolves the tool's base info (description, parameters, execute).

Returns:

An Effect yielding {id, init}, with id also attached to the Effect object itself.

Type: 
Effect

define(type, properties) → {Object}

Register an event type with its property schema and remember it in the registry.

Parameters:
NameTypeDescription
typestring

Unique event type identifier (e.g. "server.instance.disposed").

properties*

Effect Schema describing the event's properties shape.

Returns:

The registered event definition.

Type: 
Object

delay(attempt, error) → {number}

Computes the wait before the next retry attempt. Prefers the provider's retry-after-ms / retry-after response headers (seconds or HTTP date); otherwise falls back to exponential backoff capped per the no-headers limit.

Parameters:
NameTypeDescription
attemptnumber

1-based attempt number.

error*

Optional APIError-like value carrying data.responseHeaders.

Returns:

Delay in milliseconds before retrying.

Type: 
number

described(schema, description) → {Object}

Annotate a schema with a human-readable description for OpenAPI documentation.

Parameters:
NameTypeDescription
schemaObject

The Effect schema to annotate.

descriptionstring

The description to attach to the schema.

Returns:

A new schema carrying the description annotation.

Type: 
Object

detectLineEnding(text) → {string}

Detects the dominant line ending of a text.

Parameters:
NameTypeDescription
textstring

The text to inspect.

Returns:

"\r\n" if any CRLF is present, otherwise "\n".

Type: 
string

diff(prev, next) → {Object}

Compute the aggregates whose sequence number changed between two sequence maps.

Parameters:
NameTypeDescription
prevObject

Sequence map (aggregate_id to seq) captured before the change.

nextObject

Sequence map (aggregate_id to seq) captured after the change.

Returns:

A map of aggregate_id to its new seq (-1 if absent in next), including only changed entries.

Type: 
Object

dir(input) → {string}

Resolve the base directory used to resolve relative {file:...} references.

Parameters:
NameTypeDescription
inputObject

Either a {type: "path", path} input or one carrying its own dir.

Returns:

The directory of the config file when type is "path", otherwise the provided dir.

Type: 
string

dynamic(text, ps) → {boolean}

Detect whether a token contains dynamic/computed content (subexpressions, command substitution, or unresolved variables) that cannot be treated as a static path for permission scanning.

Parameters:
NameTypeDescription
textstring

The token to inspect.

psboolean

Whether the active shell is PowerShell.

Returns:

True if the token is dynamic and not a literal path.

Type: 
boolean

effectPayloads() → {Array.<Object>}

Build Effect Schema.Struct schemas for every registered event, each annotated with an Event.<type> identifier.

Returns:

Array of Effect Schema structs, one per registered event type.

Type: 
Array.<Object>

embeddedUI() → {Promise.<Object>}

Resolves the lazily-loaded embedded web UI asset map.

Returns:

Promise resolving to the embedded asset map, or null when disabled/unavailable.

Type: 
Promise.<Object>

embeddedUI() → {Promise.<Object>}

Resolve the lazily-imported embedded web UI bundle (a map of asset path to on-disk file path), or null when the embedded UI is disabled or unavailable.

Returns:

The embedded UI manifest object, or null.

Type: 
Promise.<Object>

encodeDateTimes(value) → {*}

Recursively converts any Effect DateTime values within a structure to epoch milliseconds so the data can be JSON-serialized into a sqlite column.

Parameters:
NameTypeDescription
value*

Arbitrary value, array, or object to encode.

Returns:

The value with all DateTimes replaced by epoch-millisecond numbers.

Type: 
*

encodeMessageData(value) → {*}

Encodes a message's data payload for storage (currently just DateTime encoding).

Parameters:
NameTypeDescription
value*

The message data to encode.

Returns:

The storage-ready encoded value.

Type: 
*

envValue(key) → {string}

Look up an environment variable, matching case-insensitively on Windows.

Parameters:
NameTypeDescription
keystring

The environment variable name.

Returns:

The variable's value, or undefined if unset.

Type: 
string

errors(…codes) → {Object}

Build a responses fragment for the given HTTP error status codes, for spreading into a route's describeRoute responses (e.g. ...errors(400, 404)).

Parameters:
NameTypeAttributesDescription
codesnumber<repeatable>

One or more status codes present in ERRORS (400, 404).

Returns:

A map of status code to its shared error response definition.

Type: 
Object

eventData(data) → {Object}

Wraps a bus event payload into an SSE "message" frame with a JSON-encoded body.

Parameters:
NameTypeDescription
dataObject

The event payload to serialise.

Returns:

SSE frame descriptor consumed by the SSE encoder.

Type: 
Object

eventData(data) → {Object}

Wraps a payload into an SSE "message" event envelope with a JSON-serialized data field.

Parameters:
NameTypeDescription
data*

The payload to serialize into the event's data field.

Returns:

An SSE event object {_tag, event, id, data}.

Type: 
Object

eventResponse(bus) → {Object}

Builds the streaming SSE HTTP response: emits a server.connected event, then merges the bus event stream with a 10-second heartbeat, encoding each frame as SSE text. The stream halts when the instance is disposed.

Parameters:
NameTypeDescription
busObject

Bus service used to subscribe to all events.

Returns:

Effect HttpServerResponse streaming text/event-stream output.

Type: 
Object

eventResponse() → {Object}

Builds a Server-Sent Events HTTP response that streams global bus events plus a periodic heartbeat, starting with a server.connected event and tearing down the bus listener when the client disconnects.

Returns:

An HttpServerResponse streaming the SSE-encoded event feed.

Type: 
Object

expand(text, cwd, shell) → {string}

Expand environment-variable and automatic-variable references in a token (${env:X}, $env:X, $HOME/$PWD/$PSHOME) and then expand ~.

Parameters:
NameTypeDescription
textstring

The token to expand.

cwdstring

Current working directory for PWD/relative expansion.

shellstring

Shell executable path for PSHOME.

Returns:

The expanded token.

Type: 
string

extract(messages) → {Set}

Collect the set of file paths already loaded into context via completed, non-compacted read tool calls (from each tool result's metadata.loaded).

Parameters:
NameTypeDescription
messagesArray

Session messages, each with a parts array.

Returns:

A set of string file paths already read.

Type: 
Set

(async) extractTextFromHTML(html) → {Promise.<string>}

Extracts visible text from an HTML document, stripping content inside script, style, noscript, iframe, object, and embed elements.

Parameters:
NameTypeDescription
htmlstring

The raw HTML source.

Returns:

The trimmed concatenated text content.

Type: 
Promise.<string>

filterCompacted(msgs) → {Array}

Trim a (newest-first) message list down to the active context after compaction: scans for the most recent completed compaction and drops the superseded history before its retained tail, keeping the summary and the preserved tail. Returns the result in chronological (oldest-first) order.

Parameters:
NameTypeDescription
msgsArray

Session messages in newest-first order.

Returns:

The compaction-filtered messages, oldest-first.

Type: 
Array

fixSelfReferencingComponents(spec) → {void}

Fix component schemas that are self-referencing $refs — an Effect OpenAPI generation bug where annotated union arms that share AST nodes with other endpoints produce {"$ref":"#components/schemas/X"} as the definition of X.

Resolves by finding the actual schema from a parent union's anyOf/oneOf that references the broken component, then inlining that schema.

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

flattenOptions(options) → {Array|undefined}

Flatten nested anyOf/oneOf unions into a single flat list of leaf option schemas.

Parameters:
NameTypeDescription
optionsArray | undefined

The union options to flatten.

Returns:

The flattened option list, or undefined when options is absent.

Type: 
Array | undefined

force(selection, backend) → {Object}

Override the selection to force a specific backend, marking the reason as "explicit" unless the forced backend already matches the current selection.

Parameters:
NameTypeDescription
selectionObject

The current backend selection.

backendstring

The backend to force.

Returns:

A new selection using the forced backend.

Type: 
Object

foreign(err) → {boolean}

Determines whether an error is a SQLite foreign-key constraint violation, unwrapping sequelize's wrapped driver error via original if needed.

Parameters:
NameTypeDescription
err*

The error to inspect.

Returns:

True if the error is (or wraps) a foreign-key constraint failure.

Type: 
boolean

fromError(e, ctx) → {Object}

Normalize an arbitrary thrown error into one of the named message error objects (Aborted/Auth/API/ContextOverflow/OutputLength/Unknown), classifying abort exceptions, socket resets, decompression failures, and provider API-call/stream errors (including context-overflow detection).

Parameters:
NameTypeDescription
e*

The caught error value.

ctxObject

Context { providerID, aborted } used during classification.

Returns:

A plain serialized named-error object.

Type: 
Object

get(input) → {Promise.<Object>}

Fetch a single message (with its parts) by id within a session. Throws NotFoundError when no matching message exists.

Parameters:
NameTypeDescription
inputObject

{ messageID, sessionID } identifying the message.

Returns:

Resolves to { info, parts }.

Type: 
Promise.<Object>

(async) getLastModel(sessionID) → {Promise.<*>}

Find the model most recently used by a user message in the session, scanning the message stream and returning the first user message that carries a model.

Parameters:
NameTypeDescription
sessionIDstring

The session whose messages to scan.

Returns:

The model of the latest user message, or undefined if none.

Type: 
Promise.<*>

getMimeType(filePath) → {string}

Looks up the MIME type for a file path, normalising the library's false to undefined.

Parameters:
NameTypeDescription
filePathstring

File path or name to inspect.

Returns:

The resolved MIME type, or undefined when unknown.

Type: 
string

getMimeType(filePath) → {string|undefined}

Look up the MIME type for a file path by extension.

Parameters:
NameTypeDescription
filePathstring

File path or name whose extension is inspected.

Returns:

The matched MIME type, or undefined if unknown.

Type: 
string | undefined

getWorkspaceRouteSessionID(url) → {SessionID}

Extract the session ID embedded in a /session/{id} route URL. Returns null for the /session/status route and for any URL without a session segment.

Parameters:
NameTypeDescription
urlURL

Absolute request URL.

Returns:

The parsed SessionID, or null when none is present.

Type: 
SessionID

grab(obj, field1, cb) → {*}

Reads a field from a partial-update object, optionally descending into a nested object via cb. Returns undefined when the field is absent, but throws if the field is present yet explicitly undefined (callers must pass null to clear a value).

Parameters:
NameTypeDescription
objObject

Source object (may be undefined).

field1string

Field name to read.

cbfunction

Optional callback applied to the value when it is an object.

Returns:

The field value (or callback result), or undefined when absent.

Type: 
*

hasTaskTool(agent) → {boolean}

Determines whether the given agent is allowed to use the task tool, used to decide which truncation hint to show (delegate to an explore agent vs. read directly).

Parameters:
NameTypeDescription
agentObject

The agent whose permission rules to evaluate; may be undefined.

Returns:

True if the agent has a non-deny task permission, otherwise false.

Type: 
boolean

hasToolCalls(messages) → {boolean}

Report whether any message contains tool-call or tool-result content, used to decide if a stub tool must be injected for LiteLLM-style proxy compatibility.

Parameters:
NameTypeDescription
messagesArray

Model messages whose content arrays are scanned.

Returns:

True if any part is a tool-call or tool-result.

Type: 
boolean

headers(input, extra) → {Headers}

Build a sanitized Headers object suitable for forwarding to an upstream target. Accepts either a Request (uses its headers) or a Headers/plain-object header source, removes hop-by-hop/internal headers, then applies any extra overrides.

Parameters:
NameTypeDescription
inputRequest | Headers | Object

A Request, a Headers instance, or a plain key/value header object.

extraRequest | Headers | Object

Optional additional headers to set after sanitization.

Returns:

The sanitized (and optionally augmented) Headers object.

Type: 
Headers

home(text) → {string}

Expand a leading ~ (home directory) in a path-like token.

Parameters:
NameTypeDescription
textstring

The token possibly beginning with ~.

Returns:

The token with ~ expanded to the home directory.

Type: 
string

http(client, url, extra, request) → {Effect}

Proxy an HTTP request to a target URL and stream the upstream response back to the client. Forwards the method, merged headers, and (for non-GET/HEAD) the request body stream; strips hop-specific content-encoding/content-length headers; aborts the upstream call when the client request is aborted; and converts errors into a plain-text 500 response.

Parameters:
NameTypeDescription
clientObject

The HTTP client used to execute the upstream request.

urlstring

The target URL to proxy to.

extra*

Extra headers to merge into the proxied request.

requestObject

The incoming HTTP server request to forward.

Returns:

An effect resolving to the streamed HTTP server response.

Type: 
Effect

(async) hydrate(rows) → {Promise.<Array>}

Attach parts to message rows: batch-loads all Part rows for the given messages (ordered), groups them by message, and returns { info, parts } objects.

Parameters:
NameTypeDescription
rowsArray

Plain message rows to hydrate.

Returns:

Resolves to an array of { info, parts } messages.

Type: 
Promise.<Array>

info(row) → {Object}

Reconstruct a message Info object from a stored message row, hoisting the id and session id out of the JSON data column.

Parameters:
NameTypeDescription
rowObject

A plain message row with data, id, and session_id.

Returns:

The message Info object.

Type: 
Object

init(info) → {Effect}

Initializes a defined tool, invoking its lazy init and merging the tool id into the resulting info record.

Parameters:
NameTypeDescription
infoObject

A defined-tool record produced by define(), with id and an init factory.

Returns:

An Effect yielding the fully initialized tool info including its id.

Type: 
Effect

initProjectors() → {void}

Register session projectors with the SyncEvent system, supplying a convertEvent hook that, for "session.updated" events, asynchronously loads the session row and emits its hydrated info. Other event types pass their data through unchanged.

Returns:
Type: 
void

isAllowedCorsOrigin(input, opts) → {boolean}

Determine whether a request Origin is allowed by CORS. Always allows a missing origin, http://localhost:* and http://127.0.0.1:* ports, and the vcc://renderer scheme; otherwise allows it only if listed in opts.cors.

Parameters:
NameTypeDescription
inputstring

The request Origin header value (may be empty/undefined).

optsObject

Options object; opts.cors is an array of explicitly allowed origins.

Returns:

True if the origin is allowed, false otherwise.

Type: 
boolean

isAuthRequired(config) → {boolean}

Determine whether authorization is enabled, i.e. a non-empty password is configured.

Parameters:
NameTypeDescription
configObject

The server auth config.

Returns:

True when a non-empty password is set.

Type: 
boolean

isBareArraySchema(schema) → {boolean}

Check whether a schema is a bare array type (no items or prefixItems).

Parameters:
NameTypeDescription
schemaObject

The schema to test.

Returns:

True for a bare array schema.

Type: 
boolean

isBareObjectSchema(schema) → {boolean}

Check whether a schema is a bare object type (no properties or additionalProperties).

Parameters:
NameTypeDescription
schemaObject

The schema to test.

Returns:

True for a bare object schema.

Type: 
boolean

isBuiltInErrorResponse(response, name) → {boolean}

Determine whether a response is one of Effect's built-in error responses for the given error name.

Parameters:
NameTypeDescription
responseObject

The OpenAPI response object.

namestring

The built-in error name (e.g. BadRequest, NotFound).

Returns:

True when the response is the built-in error (by description or $ref).

Type: 
boolean

isCredentialAuthorized(credential, config) → {boolean}

Check whether a credential matches the configured username and password.

Parameters:
NameTypeDescription
credentialObject

The decoded credential (password is a Redacted value).

configObject

The server auth config.

Returns:

True when the username and (revealed) password both match the configuration.

Type: 
boolean

isEmptyObjectUnion(schema) → {boolean}

Detect the degenerate "bare object OR bare array" union that Effect emits for an unconstrained record/array value.

Parameters:
NameTypeDescription
schemaObject

The schema to test.

Returns:

True when the schema is a two-arm union of a bare object and a bare array.

Type: 
boolean

isKind(value) → {boolean}

Whether the given value is one of the recognized shell kinds.

Parameters:
NameTypeDescription
valuestring

Candidate shell kind name.

Returns:

True if value is a known shell kind.

Type: 
boolean

isLocalWorkspaceRoute(method, path) → {boolean}

Decide whether a request path/method should be served locally rather than proxied, by matching it against the static RULES table. Rules may pin a method and match a path exactly or as a prefix; the first matching rule wins.

Parameters:
NameTypeDescription
methodstring

HTTP method of the request (e.g. "GET").

pathstring

Request URL pathname.

Returns:

True when the matched rule's action is "local"; false otherwise (including no match).

Type: 
boolean

isOverflow(input) → {Promise.<boolean>}

Promise wrapper around the compaction service's overflow check.

Parameters:
NameTypeDescription
inputObject

{ tokens, model } token counts and target model.

Returns:

Resolves true when token usage overflows usable context.

Type: 
Promise.<boolean>

isOverflow(input) → {boolean}

Decide whether current token usage exceeds the model's usable budget and should trigger compaction. Always false when auto-compaction is disabled or the model has no context limit.

Parameters:
NameTypeDescription
inputObject

{ cfg, model, tokens } where tokens carries total or input/output/cache counts.

Returns:

True when used tokens are at or above the usable budget.

Type: 
boolean

isPlainObject()

Detects plain objects (including objects with a null prototype).

isRefResponse(response, name) → {boolean}

Check whether a response's JSON schema is a $ref to the named component.

Parameters:
NameTypeDescription
responseObject

The OpenAPI response object.

namestring

The component name to test against.

Returns:

True when the response references #/components/schemas/<name>.

Type: 
boolean

jsonBody(schema) → {Object}

Build an OpenAPI requestBody object for an application/json endpoint.

Parameters:
NameTypeDescription
schema*

The Zod or JSON Schema describing the JSON body.

Returns:

A requestBody object with an application/json content entry.

Type: 
Object

(async) jsonRequest(name, req, res, effect) → {Promise.<void>}

Runs an Effect generator inside an OTel span built from the request, then writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

effectfunction

A function returning an Effect generator to run.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, gen) → {Promise.<void>}

Runs an Effect generator inside an OTel span built from the request, then writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

genfunction

The generator function passed to Effect.gen.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, fn) → {Promise.<void>}

Runs an Effect generator through runRequest and writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

fnfunction

A function returning an Effect generator to run.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, gen) → {Promise.<void>}

Runs an Effect generator inside a request span and JSON-encodes the resolved value onto the response.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

genfunction

The generator function passed to Effect.gen.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, effect) → {Promise.<void>}

Runs an Effect generator under an OTel span built from the request, then writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

effectfunction

A function returning an Effect generator to run.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, effect) → {Promise.<void>}

Runs an Effect generator inside an OTel span built from the request, then writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

effectfunction

A function returning an Effect generator to run.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, gen) → {Promise.<void>}

Runs an Effect generator inside a named span built from the request attributes, then serialises the result as JSON.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

resObject

The Express response object.

genfunction

The generator function passed to Effect.gen.

Returns:

Resolves once the response JSON has been written.

Type: 
Promise.<void>

(async) jsonRequest(name, req, res, gen) → {Promise.<void>}

Runs an Effect generator within a named span and writes the resolved value as JSON.

Parameters:
NameTypeDescription
namestring

Span name.

reqObject

Express request object.

resObject

Express response object.

genfunction

Generator function producing the Effect to run.

Returns:

Resolves once the JSON response has been written.

Type: 
Promise.<void>

jsonRequest(name, c, effect) → {Promise.<*>}

Run a request-producing effect within a span and serialize its result as a JSON response.

Parameters:
NameTypeDescription
namestring

The span name.

cObject

The request context; also used to build the JSON response.

effectfunction

A function receiving the context c and returning the effect to run.

Returns:

A promise resolving to the JSON response.

Type: 
Promise.<*>

(async) jsonRequestExpress(name, req, res, genFn) → {Promise.<void>}

Run an Effect generator within a traced span and write its result as the JSON response body.

Parameters:
NameTypeDescription
namestring

Span name.

reqObject

The Express request object.

resObject

The Express response object.

genFnfunction

A generator function consumed by Effect.gen producing the response value.

Returns:

Resolves once the JSON response has been sent.

Type: 
Promise.<void>

keybind(value, description) → {Schema}

Build a schema for one keybind field: an optional string that decodes to a default binding when omitted, annotated with a human-readable description.

Parameters:
NameTypeDescription
valuestring

The default key binding (e.g. "ctrl+x").

descriptionstring

Human-readable description of the action.

Returns:

The Effect Schema for the field.

Type: 
Schema

legacyErrorResponse(description, name) → {Object}

Build a legacy error response object that references a named error schema.

Parameters:
NameTypeDescription
descriptionstring

The response description.

namestring

The component schema name to reference.

Returns:

An OpenAPI response object with a JSON $ref schema.

Type: 
Object

levenshtein(a, b) → {number}

Levenshtein distance algorithm implementation: the minimum number of single-character edits (insertions, deletions, substitutions) needed to turn a into b.

Parameters:
NameTypeDescription
astring

First string.

bstring

Second string.

Returns:

The edit distance between a and b.

Type: 
number

(async) lines(filepath, opts) → {Promise.<Object>}

Stream a text file line by line, returning a window of lines starting at opts.offset (1-indexed) up to opts.limit lines. Individual lines longer than MAX_LINE_LENGTH are truncated, and the window is capped at MAX_BYTES; it also reports total line count and whether more content / a byte cut occurred.

Parameters:
NameTypeDescription
filepathstring

Absolute path of the file to read.

optsObject

Paging options: {offset: number, limit: number}.

Returns:

Resolves to {raw, count, cut, more, offset} where raw is the Array of selected lines, count is the total lines scanned, cut indicates a byte-budget cut, and more indicates additional unread lines.

Type: 
Promise.<Object>

(async) listen(app, opts, inject) → {Promise.<Object>}

Start an HTTP server for the given Express app and return a control handle. Disables per-request/header timeouts only for explicit loopback binds (so long agent loops are not aborted), tries port 4096 then a random port when opts.port is 0, and lets the optional injector hook the server before it listens (used to attach WebSocket upgrade handling).

Parameters:
NameTypeDescription
appObject

The Express application/request handler.

optsObject

Listen options: port (0 = auto) and hostname.

injectfunction

Optional callback invoked with the http.Server before it listens.

Returns:

Resolves to a handle with port and a stop(close) method.

Type: 
Promise.<Object>

load(ids) → {Promise.<Object>}

Load the current event sequence number for each aggregate.

Parameters:
NameTypeDescription
idsArray.<string>

Optional aggregate IDs to restrict the query to; loads all when omitted/empty.

Returns:

A map of aggregate_id to its current sequence number.

Type: 
Promise.<Object>

loaded(messages) → {Set}

Public helper returning the set of file paths already read into context.

Parameters:
NameTypeDescription
messagesArray

Session messages to inspect.

Returns:

A set of string file paths already loaded via read tool calls.

Type: 
Set

lock(filePath) → {Object}

Returns (creating if needed) the single-permit semaphore guarding edits to a given file.

Parameters:
NameTypeDescription
filePathstring

The file path to lock; resolved to a canonical key.

Returns:

An Effect Semaphore with one permit for that file.

Type: 
Object

makePropertiesNullable(properties) → {void}

Recursively wrap each property schema in a nullable union, with special handling for share.url (only the url made nullable) and time (recursed into).

Parameters:
NameTypeDescription
propertiesObject

The OpenAPI properties map to make nullable (mutated in place).

Returns:
Type: 
void

managedConfigDir() → {string}

Get the managed config directory, honoring the CLOSEDCODE_TEST_MANAGED_CONFIG_DIR test override before falling back to the system directory.

Returns:

The managed config directory path.

Type: 
string

mapNotFound(self) → {Effect}

Converts a storage NotFoundError (raised as either a typed failure or a defect) into an HttpApiError.NotFound, re-dying on any other defect.

Parameters:
NameTypeDescription
selfEffect

The Effect whose NotFoundError should be translated.

Returns:

The Effect with NotFound errors/defects mapped to HttpApiError.NotFound.

Type: 
Effect

mark(ctx) → {Effect}

Capture the services needed to dispose or reload an instance later.

Parameters:
NameTypeDescription
ctx*

The instance context to act on after the response.

Returns:

An effect resolving to { ctx, store, bridge }.

Type: 
Effect

matchLegacyOpenApi(input) → {Object}

Transform a freshly generated OpenAPI spec in place to match the legacy SDK surface. Fixes self-referencing components, strips optional-null union arms, normalizes/dedupes component names and descriptions, applies legacy schema overrides, removes built-in error/security schemas, injects instance query params, documents SSE event streams, and normalizes parameters/error responses.

Parameters:
NameTypeDescription
inputObject

The generated OpenAPI spec object (mutated in place).

Returns:

The same spec object, transformed.

Type: 
Object

maybeResolve(registry, schema) → {Object}

Resolve a schema that may be either a Zod schema or an already-built JSON Schema. Zod schemas (detected via _def/_zod) are converted; plain objects pass through.

Parameters:
NameTypeDescription
registryObject

The registry used when converting Zod schemas.

schema*

A Zod schema or plain JSON Schema object.

Returns:

The resolved JSON Schema fragment.

Type: 
Object

mergeEffectContractShape(paths) → {void}

Fill in missing parameters/requestBody on registry operations from the Effect httpapi contract for matching path+method pairs, mutating paths in place.

Parameters:
NameTypeDescription
pathsObject

The OpenAPI paths object to augment.

Returns:
Type: 
void

mergeOptions(target, source) → {Object}

Deep-merge a source options object into a target, treating a nullish source as an empty object.

Parameters:
NameTypeDescription
targetObject

Base options object.

sourceObject

Options to merge in (may be null/undefined).

Returns:

The deep-merged options object.

Type: 
Object

missingWorkspaceResponse(id) → {Object}

Build a 500 plain-text response indicating the requested workspace was not found.

Parameters:
NameTypeDescription
id*

The workspace ID that could not be resolved.

Returns:

An HTTP server response with status 500.

Type: 
Object

nextTuiRequest() → {Promise.<Object>}

Pulls the next pending TUI request from the request queue.

Returns:

Promise resolving to the next queued TUI request.

Type: 
Promise.<Object>

normalizeComponentDescriptions(spec) → {void}

Replace component descriptions with the curated legacy descriptions, deleting descriptions for all others.

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

normalizeComponentNames(spec) → {void}

Rename dotted component names to PascalCase type names, merging into an existing target when structurally equal or renaming otherwise, and rewriting all $refs accordingly.

Parameters:
NameTypeDescription
specObject

The OpenAPI spec object (mutated in place).

Returns:
Type: 
void

normalizeLegacyErrorResponses(operation) → {void}

Replace built-in 400/404 error responses on an operation with the legacy error response shapes.

Parameters:
NameTypeDescription
operationObject

The OpenAPI operation object (mutated in place).

Returns:
Type: 
void

normalizeLegacyOperation(operation, path, method) → {void}

Apply per-route legacy operation tweaks: drop spurious error responses on specific endpoints and give the message/command POST endpoints their explicit {info, parts} 200 response shape.

Parameters:
NameTypeDescription
operationObject

The OpenAPI operation object (mutated in place).

pathstring

The route path (e.g. /session/{sessionID}/message).

methodstring

The lowercase HTTP method (e.g. post).

Returns:
Type: 
void

normalizeLineEndings(text) → {string}

Converts all CRLF line endings in the text to LF.

Parameters:
NameTypeDescription
textstring

The text to normalize.

Returns:

The text with \r\n replaced by \n.

Type: 
string

normalizeParameter(param, route) → {void}

Normalize an operation parameter's schema for the legacy SDK: apply path/query schema overrides, coerce known number/boolean query params, and otherwise strip optional-null arms.

Parameters:
NameTypeDescription
paramObject

The OpenAPI parameter object (mutated in place).

routestring

The route key (e.g. GET /find/file) used to look up overrides.

Returns:
Type: 
void

normalizePath(path) → {string}

Normalize an Express route path to OpenAPI form: ":param" becomes "{param}" and a trailing slash is dropped except on the root path.

Parameters:
NameTypeDescription
pathstring

The Express-style route path.

Returns:

The normalized OpenAPI path.

Type: 
string

nullable(schema) → {Object}

Wrap a schema in an anyOf: [schema, {type:"null"}] union, unless it is already nullable.

Parameters:
NameTypeDescription
schemaObject

The schema to make nullable.

Returns:

The (possibly already-nullable) schema, made nullable.

Type: 
Object

older(row) → {Object}

Build a Sequelize WHERE clause selecting rows strictly older than a cursor, ordered by creation time then id (the keyset-pagination tiebreaker).

Parameters:
NameTypeDescription
rowObject

Cursor { time, id } to page before.

Returns:

A Sequelize Op.or condition.

Type: 
Object

openapi() → {Object}

Build a fresh Express app and return its OpenAPI spec, without listening.

Returns:

The built OpenAPI document.

Type: 
Object

page(input) → {Promise.<Object>}

Fetch one page of a session's messages (newest-first internally, returned oldest-first) using keyset pagination, hydrating each with its parts. Throws NotFoundError when the session does not exist and no rows are returned.

Parameters:
NameTypeDescription
inputObject

{ sessionID, limit, before } where before is an optional encoded cursor.

Returns:

Resolves to { items, more, cursor } (cursor present only when more pages exist).

Type: 
Promise.<Object>

paramToAttributeKey(key) → {string}

Map a route-param name to an OpenTelemetry attribute key: a "fooID" param becomes "foo.id", any other key becomes "closedcode.".

Parameters:
NameTypeDescription
keystring

The route parameter name.

Returns:

The corresponding span attribute key.

Type: 
string

paramToAttributeKey(key) → {string}

Normalises an Express route param name into an OTel attribute key: fooID becomes foo.id; any other param is namespaced under closedcode..

Parameters:
NameTypeDescription
keystring

The route param name.

Returns:

The normalised attribute key.

Type: 
string

paramToAttributeKey(key) → {string}

Normalises an Express route param name into an OTel attribute key: fooID becomes foo.id; any other param is namespaced under closedcode..

Parameters:
NameTypeDescription
keystring

The route param name.

Returns:

The normalised attribute key.

Type: 
string

paramToAttributeKey(key) → {string}

Normalises an Express route param name into an OTel attribute key: fooID becomes foo.id; any other param is namespaced under closedcode..

Parameters:
NameTypeDescription
keystring

The route param name.

Returns:

The normalised attribute key.

Type: 
string

paramToAttributeKey(key) → {string}

Normalises a route param name into an OTel span attribute key.

Parameters:
NameTypeDescription
keystring

Route param name (e.g. "sessionID", "directory").

Returns:

Attribute key: foo.id for fooID params, else closedcode.<key>.

Type: 
string

paramToAttributeKey(key) → {string}

Map a route param name to an OTel span attribute key. Names ending in ID become <lowercased-prefix>.id (e.g. sessionID -> session.id); all other names are namespaced under closedcode. to avoid colliding with standard conventions.

Parameters:
NameTypeDescription
keystring

The route parameter name.

Returns:

The corresponding OTel attribute key.

Type: 
string

parameterSchema(description) → {Object}

Build the shell tool's parameter schema (command, optional timeout, optional workdir, and a required description) using the supplied description text for the description field.

Parameters:
NameTypeDescription
descriptionstring

Annotation text describing the description parameter, tailored per shell.

Returns:

An Effect Schema.Struct for the shell tool parameters.

Type: 
Object

parse(headers) → {Object|undefined}

Parse the sync fence header into a sequence map. Returns undefined when the header is missing or invalid; otherwise keeps only entries with a string key and an integer sequence value.

Parameters:
NameTypeDescription
headersObject

A Headers-like object exposing get(name).

Returns:

A map of aggregate_id to integer seq, or undefined if unparseable.

Type: 
Object | undefined

parseBody(body) → {*}

Parses a JSON request body, defaulting an empty body to {}.

Parameters:
NameTypeDescription
bodystring

The raw request body text.

Returns:

The parsed value, or undefined if parsing fails.

Type: 
*

parseManagedPlist(json) → {string}

Strip MDM/plist metadata keys from a JSON-encoded managed plist, returning the remaining closedcode config as a JSON string.

Parameters:
NameTypeDescription
jsonstring

The plist contents as a JSON string.

Returns:

JSON string of the config with payload metadata removed.

Type: 
string

part(row) → {Object}

Reconstruct a message Part object from a stored part row, hoisting the id, session id, and message id out of the JSON data column.

Parameters:
NameTypeDescription
rowObject

A plain part row with data, id, session_id, and message_id.

Returns:

The message Part object.

Type: 
Object

parts(message_id) → {Promise.<Array>}

Load all parts of a single message in id order, reconstructed as Part objects.

Parameters:
NameTypeDescription
message_idstring

The message whose parts to load.

Returns:

Resolves to the message's Part objects.

Type: 
Promise.<Array>

parts(node) → {Array}

Extract the meaningful tokens (command name and argument-like elements) of a tree-sitter command node, skipping separators and redirections.

Parameters:
NameTypeDescription
nodeObject

A tree-sitter command syntax node.

Returns:

An Array of {type, text} token objects.

Type: 
Array

pathArgs(list, ps, cmd) → {Array}

Extract the path-like arguments from a command's token list, skipping the command name, flags/switches, and special leading characters. For PowerShell it also follows value-taking parameters (e.g. -Path) to grab their value.

Parameters:
NameTypeDefaultDescription
listArray

The command's tokens (first entry is the command name).

psboolean

Whether the active shell is PowerShell.

cmdbooleanfalse

Whether the active shell is cmd.exe (affects /-flag handling).

Returns:

An Array of path argument strings.

Type: 
Array

pathParameterSchema(route, name) → {Object|undefined}

Resolve the override schema for a path parameter by name, with route-specific patterns for id/requestID on workspace, permission, and question routes.

Parameters:
NameTypeDescription
routestring

The route key (e.g. DELETE /experimental/workspace/...).

namestring

The path parameter name.

Returns:

The override schema, or undefined when there is no override.

Type: 
Object | undefined

payloads() → {Array.<Object>}

Build Zod object schemas for every registered event, each annotated with an Event.<type> ref.

Returns:

Array of Zod object schemas, one per registered event type.

Type: 
Array.<Object>

plain(row) → {Object}

Convert a Sequelize model row to a plain object, or undefined when the row is null/undefined.

Parameters:
NameTypeDescription
rowObject

A Sequelize model instance, or null/undefined.

Returns:

The plain object representation, or undefined.

Type: 
Object

plain(row) → {Object}

Convert a Sequelize model instance to a plain object, or undefined when null.

Parameters:
NameTypeDescription
rowObject

A Sequelize model instance, or null/undefined.

Returns:

The plain row object, or undefined.

Type: 
Object

planRequest(request, sessionWorkspaceID) → {Effect}

Compute the routing plan for a request, accounting for the env-pinned workspace, the selected workspace (session or query param), missing workspaces, and control-plane-only routes.

Parameters:
NameTypeDescription
requestObject

The incoming HTTP server request.

sessionWorkspaceID*

The workspace ID from the request's session, if any.

Returns:

An effect resolving to a RequestPlan (Local, Remote, or MissingWorkspace).

Type: 
Effect

planWorkspaceRequest(request, url, workspace) → {Effect}

Build a request plan for a resolved workspace: Remote when the target is remote (proxy), otherwise Local.

Parameters:
NameTypeDescription
requestObject

The incoming HTTP server request.

urlURL

The parsed request URL.

workspaceObject

The resolved workspace.

Returns:

An effect resolving to a RequestPlan value.

Type: 
Effect

policy(opts) → {*}

Builds an Effect Schedule that retries while retryable returns a reason, waiting the computed delay between attempts and reporting progress.

Parameters:
NameTypeDescription
optsObject

Policy hooks.

Properties
NameTypeDescription
parsefunction

Maps a raw stream error to the classified error consumed by retryable.

setfunction

Called per attempt with {attempt, message, next} to report retry status.

Returns:

An Effect Schedule usable with Effect.retry.

Type: 
*

powershellCommandSection(name, chain, pathSep, limits) → {string}

Build the PowerShell-specific "command section" of the tool description, covering notes, directory verification, quoting, output limits, and chaining.

Parameters:
NameTypeDescription
namestring

PowerShell variant name ("pwsh" or "powershell").

chainstring

The chaining guidance sentence to embed.

pathSepstring

Path separator to use in examples ("\" or "/").

limitsObject

Output limits with maxLines and maxBytes.

Returns:

The rendered PowerShell command-section text.

Type: 
string

powershellNotes(name) → {string}

Return the PowerShell-specific usage notes block for the given PowerShell variant (pwsh 7+ or Windows PowerShell 5.1); empty for other shells.

Parameters:
NameTypeDescription
namestring

Shell name ("pwsh" or "powershell").

Returns:

The notes markdown block, or an empty string.

Type: 
string

prefix(text) → {string}

Return the literal (non-glob) prefix of a token up to the first glob metacharacter (?, *, [); returns undefined if the token begins with a glob character.

Parameters:
NameTypeDescription
textstring

The token to inspect.

Returns:

The literal prefix, or undefined if it starts with a glob char.

Type: 
string

preserveRecentBudget(input) → {number}

Compute the token budget reserved for preserving recent turns: the configured value if set, otherwise 25% of usable context clamped to the min/max bounds.

Parameters:
NameTypeDescription
inputObject

{ cfg, model } config and model used to size the budget.

Returns:

The token budget for recent-turn preservation.

Type: 
number

preview(text) → {string}

Produce a metadata-sized preview of output, keeping the tail and prefixing "..." when the text exceeds MAX_METADATA_LENGTH.

Parameters:
NameTypeDescription
textstring

The output text to preview.

Returns:

The original text or a truncated tail preview.

Type: 
string

profile(name, platform, limits) → {Object}

Assemble the full set of prompt fragments (intro, workdir section, command section, git/PR guidance, parameter description) for the given shell and platform.

Parameters:
NameTypeDescription
namestring

Shell name ("bash", "pwsh", "powershell", or "cmd").

platformstring

Node platform string (e.g. "win32").

limitsObject

Output limits with maxLines and maxBytes.

Returns:

A profile object of prompt fragment strings.

Type: 
Object

provideInstanceContext(effect, store) → {Effect}

Provide the instance context for effect based on the current workspace route. Reads the route's directory (URI-decoded) and workspace ID, then runs effect inside the corresponding instance from the store with the workspace ref provided.

Parameters:
NameTypeDescription
effectEffect

The handler effect to run within the instance context.

storeObject

The InstanceStore service used to provide the instance.

Returns:

The effect run within the resolved instance and workspace context.

Type: 
Effect

provideLocal(req, res, next, workspaceID, directory) → {Promise.<*>}

Run downstream handlers inside WorkspaceContext.provide -> WithInstance.provide so that Effect services resolve against the given workspace and directory. The wrapped promise settles when the response finishes or errors.

Parameters:
NameTypeDescription
reqObject

The Express request.

resObject

The Express response.

nextfunction

Invokes the downstream handler chain.

workspaceIDstring

The workspace to provide as context.

directorystring

The resolved project directory.

Returns:

The result of the provided Effect/promise.

Type: 
Promise.<*>

provider(model) → {Array.<string>}

Selects the base system prompt(s) appropriate for the given model, choosing a Trinity- or Kimi-specific prompt by model id and otherwise the default.

Parameters:
NameTypeDescription
modelObject

Model descriptor with an api.id string.

Returns:

A single-element array containing the chosen prompt text.

Type: 
Array.<string>

provider(text) → {string}

Strip a PowerShell provider qualifier from a path, returning the bare path only for the filesystem provider. Returns undefined for non-filesystem providers (e.g. Env:) and leaves drive-letter paths (C:) untouched.

Parameters:
NameTypeDescription
textstring

The possibly provider-qualified path token.

Returns:

The filesystem path, or undefined if not a filesystem path.

Type: 
string

providerMeta(metadata) → {Object}

Strip the internal providerExecuted flag from part metadata, returning the remaining provider metadata or undefined when nothing is left.

Parameters:
NameTypeDescription
metadataObject

Part metadata, possibly including providerExecuted.

Returns:

The cleaned metadata object, or undefined.

Type: 
Object

(async) proxyRemote(req, res, workspace, target, url) → {Promise.<void>}

Proxy a request to a remote workspace's upstream target. Verifies the workspace is syncing (else 503), forwards method/headers/body faithfully, strips hop-by-hop headers, honors the sync fence (waiting for local catch-up), and streams the upstream body back to the client.

Parameters:
NameTypeDescription
reqObject

The incoming Express request.

resObject

The Express response to write the proxied result to.

workspaceObject

The target workspace.

targetObject

The upstream target's base URL and headers.

urlURL

The original request URL used to derive the upstream path.

Returns:

Resolves once the upstream response has been streamed or the request errored.

Type: 
Promise.<void>

proxyRemote(client, request, workspace, target, url) → {Effect}

Proxy a request to a remote workspace target, returning a 503 when the workspace's sync connection is broken. Routes WebSocket upgrades through the WebSocket proxy; otherwise proxies over HTTP, then honors any sync fence header in the response by waiting for the workspace to catch up (returning 503 on sync failure).

Parameters:
NameTypeDescription
clientObject

The HTTP client used for proxying.

requestObject

The incoming HTTP server request.

workspaceObject

The remote workspace being proxied to.

targetObject

The resolved remote target (url, headers).

urlURL

The parsed request URL.

Returns:

An effect resolving to the proxied (or error) HTTP response.

Type: 
Effect

prune(input) → {Promise.<void>}

Promise wrapper around the compaction service's prune operation.

Parameters:
NameTypeDescription
inputObject

{ sessionID } the session to prune.

Returns:

Resolves when pruning completes.

Type: 
Promise.<void>

publish(port, domain) → {void}

Publish an mDNS/Bonjour "http" service advertising the server on the local network. No-op if the same port is already published; tears down any prior advertisement first.

Parameters:
NameTypeDescription
portnumber

TCP port the server is listening on.

domainstring

Optional mDNS host name to advertise (defaults to "closedcode.local").

Returns:
Type: 
void

queryBoolean(value) → {boolean}

Coerce a query-string boolean ("true"/"false" or an actual boolean) into a boolean.

Parameters:
NameTypeDescription
value*

The raw query value (string, boolean, or undefined).

Returns:

True for true/"true", false for other defined values, or undefined when the input is undefined.

Type: 
boolean

queryBoolean(value) → {boolean}

Coerces a query-string boolean into a real boolean.

Parameters:
NameTypeDescription
value*

Raw query value (true/false boolean, "true"/"false" string, or undefined).

Returns:

True when the value is true or the string "true"; undefined when value is undefined.

Type: 
boolean

raceAbort(effect, signal) → {Effect}

Race an effect against an abort signal, interrupting the effect when the signal fires.

Parameters:
NameTypeDescription
effectEffect

The effect to run.

signalAbortSignal | undefined

The abort signal; when absent effect is returned unchanged.

Returns:

The original effect, optionally raced against abort.

Type: 
Effect

readManagedPreferences() → {Promise.<(Object|undefined)>}

On macOS, read MDM-deployed managed preferences for the closedcode domain by locating the managed .plist, converting it to JSON via plutil, and stripping payload metadata. No-op on non-macOS platforms.

Returns:

A {source, text} object when a managed plist is found, otherwise undefined.

Type: 
Promise.<(Object|undefined)>

registerOperation(registry, method, path, describe) → {void}

Register a single OpenAPI operation for method path in the registry, resolving any Zod schemas in responses/requestBody to JSON Schema.

Parameters:
NameTypeDescription
registryObject

The registry to push the operation into.

methodstring

The HTTP method (case-insensitive).

pathstring

The Express-style route path (normalized to OpenAPI form).

describeObject

Operation metadata (summary, description, operationId, responses, requestBody, parameters).

Returns:
Type: 
void

render(name, platform, limits) → {Object}

Render the complete shell tool definition for a given shell and platform: substitutes the profile fragments into the description template and builds the matching parameter schema.

Parameters:
NameTypeDescription
namestring

Shell name ("bash", "pwsh", "powershell", or "cmd").

platformstring

Node platform string (e.g. "win32").

limitsObject

Output limits with maxLines and maxBytes.

Returns:

An object with description (string) and parameters (Schema).

Type: 
Object

renderPrompt(template, values) → {string}

Substitute ${key} placeholders in a template with the matching value, throwing if any referenced key is missing.

Parameters:
NameTypeDescription
templatestring

Template string containing ${key} placeholders.

valuesObject

Map of placeholder keys to replacement strings.

Returns:

The rendered string with all placeholders substituted.

Type: 
string

replace(content, oldString, newString, replaceAll) → {string}

Replaces an occurrence of oldString with newString in content, trying each replacer strategy in order until one finds a match. Throws if oldString equals newString, if no replacer locates the text, or (when not replacing all) if the located text is ambiguous (multiple occurrences).

Parameters:
NameTypeDescription
contentstring

The original file content.

oldStringstring

The text to find (matched via the replacer cascade).

newStringstring

The replacement text.

replaceAllboolean

When true, replaces every occurrence; otherwise requires a unique match.

Returns:

The content with the replacement applied.

Type: 
string

reportValidation(req, res, next) → {*}

Middleware that reports express-validator field-chain failures using the same 400 envelope as the Zod validator; passes through when there are no errors.

Parameters:
NameTypeDescription
reqObject

The Express request.

resObject

The Express response.

nextfunction

Passes control on when validation passed.

Returns:

The 400 JSON response on failure, otherwise the result of next().

Type: 
*

requestAttributes(req) → {Object}

Build OpenTelemetry span attributes from an Express request (HTTP method/path plus matched route params).

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A map of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Build OpenTelemetry span attributes from an Express request (HTTP method/path plus matched route params).

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A map of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, mounted path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, mounted path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds OTel span attributes from an Express request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
reqObject

The Express request object.

Returns:

A flat record of span attribute keys to values.

Type: 
Object

requestAttributes(req) → {Object}

Builds the OTel span attributes for an Express request (method, path, and route params).

Parameters:
NameTypeDescription
reqObject

Express request object.

Returns:

Attribute map keyed by OTel attribute names.

Type: 
Object

requestAttributes(c) → {Object}

Build the base span attributes for an HTTP request: HTTP method, path, and every matched route param.

Parameters:
NameTypeDescription
cObject

The request context (Hono-style context exposing c.req).

Returns:

A map of OTel attribute keys to string values.

Type: 
Object

requestURL(req) → {URL}

Build an absolute URL for a request, used for workspace routing decisions.

Parameters:
NameTypeDescription
reqObject

The Express request (uses originalUrl/url).

Returns:

The request URL resolved against http://localhost.

Type: 
URL

requestURL(request) → {URL}

Parse a request URL into a URL, using a localhost base for relative request URLs.

Parameters:
NameTypeDescription
requestObject

The HTTP server request.

Returns:

The parsed request URL.

Type: 
URL

resolve(registry, zodSchema) → {Object}

Convert a Zod schema to a JSON Schema fragment for OpenAPI. If the schema carries a ref via .meta({ref}), it is registered under components/schemas and a $ref is returned instead of the inline schema.

Parameters:
NameTypeDescription
registryObject

The registry to record named schemas in.

zodSchema*

The Zod schema to convert.

Returns:

A JSON Schema fragment, or a {$ref} pointing at the registered component.

Type: 
Object

resolveRequestBody(registry, requestBody) → {Object}

Resolve every content schema inside an OpenAPI requestBody, converting Zod schemas to JSON Schema.

Parameters:
NameTypeDescription
registryObject

The registry used for schema conversion.

requestBodyObject

The requestBody object whose content schemas are resolved.

Returns:

A new requestBody with resolved content schemas.

Type: 
Object

resolveTarget(workspace) → {Effect}

Resolve the routing target for a workspace via its project/type adapter (e.g. local directory or remote URL).

Parameters:
NameTypeDescription
workspaceObject

The workspace whose target is being resolved.

Returns:

An effect resolving to the adapter's target descriptor.

Type: 
Effect

resolveTools(input) → {Object}

Filter the available tools down to those allowed for this request: drops tools disabled by merged agent/request permissions and tools the user message explicitly turned off.

Parameters:
NameTypeDescription
inputObject

Request inputs with tools, agent.permission, permission, and user.tools.

Returns:

The filtered tool map.

Type: 
Object

resolveWasm(asset) → {string}

Resolve a tree-sitter wasm asset reference to a plain filesystem path, accepting file:// URLs, absolute paths, and module-relative references.

Parameters:
NameTypeDescription
assetstring

The asset reference (URL, absolute, or relative path).

Returns:

The resolved filesystem path.

Type: 
string

resolveWorkspace(id, envWorkspaceID) → {Effect}

Look up a workspace by ID unless routing is pinned by an env workspace ID.

Parameters:
NameTypeDescription
id*

The workspace ID to resolve, if any.

envWorkspaceID*

The env-pinned workspace ID; when set, resolution is skipped.

Returns:

An effect resolving to the workspace, or void when no lookup is needed.

Type: 
Effect

resolveWorkspaceRoute(url, method, envWorkspaceID) → {Promise.<Object>}

Resolve the effective workspace + adapter target for an incoming request URL, mirroring InstanceMiddleware / planRequest. Pure resolution only — performs no proxying and no response writes. Used by both the HTTP middleware and the WebSocket upgrade handler so the selection logic lives in one place.

Parameters:
NameTypeDescription
urlURL

absolute request URL (built by caller)

methodstring

HTTP method (for isLocalWorkspaceRoute)

envWorkspaceIDWorkspaceID | undefined

Flag.CLOSEDCODE_WORKSPACE_ID (already WorkspaceID.make'd) or undefined

Returns:

A workspace-route resolution, one of three shapes discriminated by kind:

  • { kind: "local", workspaceID, directory? } — serve locally
  • { kind: "missing", workspaceID } — known workspace, not resolvable here
  • { kind: "remote", workspace, target, workspaceID } — proxy to target
Type: 
Promise.<Object>

responseDescription(description) → {Object}

Build an OpenAPI annotation that overrides the description of an endpoint's 200 response.

Parameters:
NameTypeDescription
descriptionstring

The description to set on the operation's "200" response.

Returns:

An OpenApi annotations object with a transform that rewrites the 200 response description.

Type: 
Object

retryable(error) → {string|undefined}

Decides whether an error should be retried and, if so, the human-readable reason. Treats 5xx and rate-limit-style errors (via status code, message heuristics, or parsed JSON error codes) as retryable; context overflow is not.

Parameters:
NameTypeDescription
error*

Parsed error to classify.

Returns:

A retry reason message when retryable, otherwise undefined.

Type: 
string | undefined

rewriteRefs(input, from, to) → {void}

Recursively rewrite every $ref pointing at the from component to point at the to component.

Parameters:
NameTypeDescription
input*

The spec value (object/array) to traverse (mutated in place).

fromstring

The source component name.

tostring

The target component name.

Returns:
Type: 
void

routeHttpApiWorkspace(client, effect) → {Effect}

Route an HttpApi request by resolving the session's workspace (when a session is referenced), planning the request, and executing the plan.

Parameters:
NameTypeDescription
clientObject

The HTTP client used for remote proxying.

effectEffect

The local handler effect to run for Local plans.

Returns:

An effect resolving to the resulting HTTP response.

Type: 
Effect

routeWorkspace(client, effect, plan) → {Effect}

Execute a request plan: respond with a not-found error, proxy to the remote target, or run the local handler effect with the WorkspaceRouteContext provided.

Parameters:
NameTypeDescription
clientObject

The HTTP client used for remote proxying.

effectEffect

The local handler effect to run for Local plans.

plan*

The RequestPlan produced by planRequest.

Returns:

An effect resolving to the resulting HTTP response.

Type: 
Effect

runEffect(name, req, effect) → {Promise}

Run an Effect inside a named tracing span carrying the request's attributes.

Parameters:
NameTypeDescription
namestring

Span name.

reqObject

The Express request object (used to derive span attributes).

effectEffect

The Effect to execute within the span.

Returns:

A promise resolving to the Effect's success value.

Type: 
Promise

runRequest(name, req, effect) → {Promise.<*>}

Wraps an Effect in a span carrying the request attributes and runs it through AppRuntime.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

effectEffect

The Effect to run inside the span.

Returns:

A promise resolving to the Effect's result.

Type: 
Promise.<*>

runRequest(name, req, effect) → {Promise.<*>}

Runs an Effect inside a named span carrying the request attributes.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

effectEffect

The Effect to run inside the span.

Returns:

A promise resolving to the Effect's result.

Type: 
Promise.<*>

runRequest(name, req, effect) → {Promise.<*>}

Runs an Effect inside a named span carrying the request attributes.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

effectEffect

The Effect to run inside the span.

Returns:

A promise resolving to the Effect's result.

Type: 
Promise.<*>

runRequest(name, req, effect) → {Promise.<*>}

Runs an Effect inside an OTel span built from the request.

Parameters:
NameTypeDescription
namestring

The span name.

reqObject

The Express request object.

effectEffect

The Effect to run inside the span.

Returns:

A promise resolving to the Effect's result.

Type: 
Promise.<*>

runRequest(name, req, effect) → {Promise.<*>}

Runs an Effect inside a named OTel span carrying the request attributes.

Parameters:
NameTypeDescription
namestring

Span name.

reqObject

Express request object (source of span attributes).

effectEffect

The Effect to run within the span.

Returns:

Promise resolving to the Effect's result.

Type: 
Promise.<*>

runRequest(name, c, effect) → {Promise.<*>}

Run an effect as a traced HTTP request, wrapping it in a span named name with the request's attributes.

Parameters:
NameTypeDescription
namestring

The span name.

cObject

The request context used to derive span attributes.

effectEffect

The effect to execute within the span.

Returns:

A promise that resolves to the effect's result.

Type: 
Promise.<*>

runRequestExpress(name, req, effect) → {Promise}

Run an Effect inside a named tracing span carrying the request's attributes.

Parameters:
NameTypeDescription
namestring

Span name.

reqObject

The Express request object (used to derive span attributes).

effectEffect

The Effect to execute within the span.

Returns:

A promise resolving to the Effect's success value.

Type: 
Promise

sanitize(out) → {void}

Remove hop-by-hop and internal routing headers from a Headers object in place. Strips the hop-by-hop set plus accept-encoding and the x-closedcode/x-opencode directory/workspace headers.

Parameters:
NameTypeDescription
outHeaders

The Headers object to mutate.

Returns:
Type: 
void

select() → {Object}

Select the server backend to use.

Returns:

The chosen backend and the reason it was selected.

Type: 
Object

selectedWorkspaceID(url, sessionWorkspaceID) → {*}

Determine the workspace ID selected for a request, preferring the session's workspace over the workspace query param.

Parameters:
NameTypeDescription
urlURL

The parsed request URL.

sessionWorkspaceID*

The workspace ID associated with the request's session, if any.

Returns:

The selected WorkspaceID, or undefined when none is specified.

Type: 
*

serializeSearchParams()

Turns URLSearchParams into a sorted JSON object for deterministic keys.

serveDocs(app, mountPath, spec) → {void}

Mount the swagger-ui docs UI on the Express app at the given path, serving the built spec.

Parameters:
NameTypeDescription
appObject

The Express application.

mountPathstring

The path to mount the docs UI at (e.g. "/docs").

specObject

The built OpenAPI document to serve.

Returns:
Type: 
void

(async) serveUI(req, res) → {Promise.<Object>}

Serves the embedded web UI asset matching the request path (falling back to index.html). Sets the content type and, for HTML, the default CSP header.

Parameters:
NameTypeDescription
reqObject

Express request object (uses req.path).

resObject

Express response object.

Returns:

Promise resolving to the Express response (200 with asset, 404 when missing, 503 when no bundle).

Type: 
Promise.<Object>

serveUIEffect(request, services) → {Effect}

Serve a static file from the embedded web UI bundle for the given request. Resolves the request path against the embedded manifest (falling back to index.html), reads the matched file, and returns it with the appropriate content-type and CSP headers. Returns 404 when the asset is missing and 503 when the build has no embedded web UI.

Parameters:
NameTypeDescription
requestObject

HTTP request whose url is matched against the bundle.

servicesObject

Service bag providing fs.existsSafe and fs.readFile.

Returns:

An Effect yielding the HttpServerResponse to send.

Type: 
Effect

shellDisplayName(name) → {string}

Map an internal shell name to a human-readable display name.

Parameters:
NameTypeDescription
namestring

Internal shell name (e.g. "pwsh", "powershell", "cmd").

Returns:

The display name, or the input unchanged if unrecognized.

Type: 
string

shouldStayOnControlPlane(request, url) → {boolean}

Decide whether a request must be handled on the control plane regardless of workspace selection (local workspace routes and /console paths).

Parameters:
NameTypeDescription
requestObject

The HTTP server request.

urlURL

The parsed request URL.

Returns:

True when the request should stay on the control plane.

Type: 
boolean

sliceAfterMatch(filePath, searchRoots) → {string|undefined}

Return the portion of a (forward-slash-normalized) path that follows the first matching search root, or undefined when no root matches.

Parameters:
NameTypeDescription
filePathstring

The file path to inspect (Windows or POSIX separators).

searchRootsArray.<string>

Root substrings to match against, in priority order.

Returns:

The path slice after the matched root, or undefined.

Type: 
string | undefined

source(node) → {string}

Return the trimmed source text of a command node, preferring the enclosing redirected statement so redirections are included in the captured command.

Parameters:
NameTypeDescription
nodeObject

A tree-sitter command syntax node.

Returns:

The command's source text.

Type: 
string

source(input) → {string}

Resolve the source identifier (used for error reporting) of a substitution input.

Parameters:
NameTypeDescription
inputObject

Either a {type: "path", path} input or one carrying its own source.

Returns:

The config file path when type is "path", otherwise the provided source string.

Type: 
string

splitTurn(input) → {Effect}

Find the earliest split point inside a single turn whose suffix [start, turn.end) fits within the remaining token budget, so part of an oversized turn can still be preserved in the tail.

Parameters:
NameTypeDescription
inputObject

{ turn, messages, model, budget, estimate } with the turn to split, full message list, model, remaining token budget, and an estimate Effect-fn.

Returns:

An Effect yielding { start, id } for the chosen split, or undefined if none fits.

Type: 
Effect

(async) sqlite(h, sessionID) → {Promise.<Object>}

Builds a synchronous SessionMessageUpdater adapter backed by sequelize. It pre-loads the assistant/compaction/shell messages for the session, exposes getters/setters the updater can call synchronously, and queues all writes so they can be flushed (in order) after the updater finishes.

Parameters:
NameTypeDescription
hObject

Sequelize handle { models, sequelize, tx }.

sessionIDstring

Session whose messages are being projected.

Returns:

A promise of { adapter, flush } where adapter is the synchronous updater interface and flush runs the queued writes.

Type: 
Promise.<Object>

stableSchema(input, schemas) → {string}

Produce a stable, comparable string for a schema by canonicalizing it (sorted keys, descriptions dropped, refs canonicalized).

Parameters:
NameTypeDescription
input*

The schema (or schema fragment) to serialize.

schemasObject

The component schemas map used to canonicalize $refs.

Returns:

A deterministic JSON string for structural comparison.

Type: 
string

stop(close) → {Promise.<void>}

Stop the server, resolving once it has fully closed. Idempotent.

Parameters:
NameTypeDescription
closeboolean

When true, also forcibly close all (idle and active) connections.

Returns:

Resolves when the server has closed.

Type: 
Promise.<void>

stream(sessionID) → {AsyncGenerator}

Async-iterate all messages of a session in chronological (oldest-first) order, paging through the database in fixed-size batches.

Parameters:
NameTypeDescription
sessionIDstring

The session whose messages to stream.

Returns:

Yields each { info, parts } message in order.

Type: 
AsyncGenerator

streamEvents(res, req, subscribe) → {void}

Streams server-sent events to the client: sets SSE headers, sends an initial connected event plus periodic heartbeats, pumps an AsyncQueue to the response, and tears everything down when the request closes.

Parameters:
NameTypeDescription
resObject

The Express response object.

reqObject

The Express request object.

subscribefunction

Called with the AsyncQueue; should push events onto it and return an unsubscribe function.

Returns:
Type: 
void

stripOptionalNull(schema) → {Object}

Strip {type:"null"} arms that Effect's Schema.optional adds to OpenAPI unions, recursing into allOf/anyOf/oneOf, items, properties, and additionalProperties, and collapsing single-arm unions.

Parameters:
NameTypeDescription
schemaObject

The schema to normalize (mutated and returned).

Returns:

The schema with optional-null arms removed.

Type: 
Object

submitTuiRequest(body) → {void}

Enqueues a TUI request for a connected TUI to pull.

Parameters:
NameTypeDescription
bodyObject

The TUI request to enqueue ({path, body}).

Returns:
Type: 
void

submitTuiResponse(body) → {void}

Enqueues a TUI response for the originating caller waiting in callTui.

Parameters:
NameTypeDescription
body*

The response payload to enqueue.

Returns:
Type: 
void

substitute(input) → {Promise.<string>}

Apply {env:VAR} and {file:path} substitutions to config text. {env:VAR} is replaced by the environment variable's value (empty string if unset). {file:path} is replaced by the JSON-escaped trimmed contents of the referenced file; relative paths resolve against the config directory, ~/ expands to the home directory, and tokens on lines starting with // are left untouched. Missing files either throw an InvalidError or expand to empty depending on input.missing.

Parameters:
NameTypeDescription
inputObject

Substitution input.

Properties
NameTypeDescription
textstring

The raw config text to process.

missingstring

How to handle missing files: "error" (default, throw) or "empty".

typestring

Discriminator; "path" means input.path is used for dir/source.

pathstring

Config file path (when type is "path").

dirstring

Base directory for relative references (when not type "path").

sourcestring

Source identifier for error messages (when not type "path").

Returns:

The text with all env and file tokens expanded.

Type: 
Promise.<string>

summaryText(message) → {string}

Concatenate the trimmed text parts of a message into a single summary string.

Parameters:
NameTypeDescription
messageObject

A message with a parts array.

Returns:

The joined non-empty text, or undefined when there is none.

Type: 
string

systemManagedConfigDir() → {string}

Resolve the OS-specific system directory for managed (MDM-deployed) closedcode config.

Returns:

The managed config directory path for the current platform.

Type: 
string

tail(text, maxLines, maxBytes) → {Object}

Keep only the tail of the output within the given line and byte budgets, truncating a final overlong line mid-character on a UTF-8 boundary.

Parameters:
NameTypeDescription
textstring

The full output text.

maxLinesnumber

Maximum number of trailing lines to keep.

maxBytesnumber

Maximum byte budget for the kept text.

Returns:

An object {text, cut} where cut indicates truncation occurred.

Type: 
Object

toKind(value) → {string}

Normalize an arbitrary shell name to a known kind, falling back to "bash".

Parameters:
NameTypeDescription
valuestring

Shell name to classify.

Returns:

A recognized shell kind ("bash", "pwsh", "powershell", or "cmd").

Type: 
string

toModelMessages(input, model, options) → {Promise.<Array>}

Promise wrapper around toModelMessagesEffect that runs it with the logger layer.

Parameters:
NameTypeDescription
inputArray

Stored messages, each { info, parts }.

modelObject

Target model { id, providerID }.

optionsObject

Optional { stripMedia, toolOutputMaxChars } controls.

Returns:

Resolves to the array of provider model messages.

Type: 
Promise.<Array>

toPartialRow(info) → {Object}

Maps a partial session-update info object to a partial sqlite row, flattening nested share/summary/time fields to their column names and dropping any keys whose value resolved to undefined (so absent fields aren't overwritten).

Parameters:
NameTypeDescription
infoObject

Partial session update info.

Returns:

A partial row object containing only the columns to update.

Type: 
Object

traceContext(req) → {Object}

Adapts an Express request into the minimal context shape trace.js expects.

Parameters:
NameTypeDescription
reqObject

Express request object.

Returns:

Context with req.method, req.url, and a req.param() accessor.

Type: 
Object

trimDiff(diff) → {string}

Removes the common leading indentation shared by all content lines (+/-/space) of a unified diff, leaving the +/-/space prefixes and the ---/+++ header lines untouched, so the diff renders without a large uniform indent.

Parameters:
NameTypeDescription
diffstring

A unified diff string.

Returns:

The diff with shared content-line indentation stripped (unchanged if there is none).

Type: 
string

truncateToolOutput(text, maxChars) → {string}

Truncate tool output to a maximum character count for compaction, appending a marker noting how many characters were omitted. Returns the text unchanged when maxChars is falsy or the text already fits.

Parameters:
NameTypeDescription
textstring

The tool output text.

maxCharsnumber

Maximum allowed length, or 0/undefined for no limit.

Returns:

The (possibly truncated) text.

Type: 
string

turns(messages) → {Array}

Split a message list into conversational turns, where each turn starts at a non-compaction user message and ends at the next turn's start (or list end).

Parameters:
NameTypeDescription
messagesArray

Ordered session messages, each { info, parts }.

Returns:

Turn descriptors { start, end, id } (half-open [start, end) indices).

Type: 
Array

unpublish() → {void}

Tear down the active mDNS/Bonjour advertisement (if any) and reset internal state.

Returns:
Type: 
void

unquote(text) → {string}

Strip a single matching pair of surrounding single or double quotes.

Parameters:
NameTypeDescription
textstring

The possibly-quoted token text.

Returns:

The unquoted text, or the input unchanged if not quoted.

Type: 
string

unquoteGitPath(input) → {string}

Decodes a git "C-quoted" path (a path git wraps in double quotes with backslash/octal escapes) back into its real UTF-8 form. Returns the input unchanged when it is not a quoted path.

Parameters:
NameTypeDescription
inputstring

A path as emitted by git, possibly double-quoted with escape sequences.

Returns:

The decoded path, or the original input if it was not quoted.

Type: 
string

(async) update(h, event) → {Promise.<void>}

Applies a single session-message event to the store: builds the adapter, runs the synchronous updater against it, then flushes the queued writes.

Parameters:
NameTypeDescription
hObject

Sequelize handle { models, sequelize, tx }.

eventObject

The session-message event { id, type, data } to project.

Returns:

Resolves once the projection is persisted.

Type: 
Promise.<void>

usable(input) → {number}

Compute the usable input-token budget for a model, reserving headroom for the response. Uses the model's explicit input limit minus a reserved buffer when available, otherwise the context window minus max output tokens.

Parameters:
NameTypeDescription
inputObject

{ model, cfg } with the model's limits and config (compaction.reserved).

Returns:

The usable input-token budget (0 when context is 0).

Type: 
number

validateCredential(effect, credential, config) → {Effect}

Run effect only if auth is not required or the credential is authorized; otherwise fail with an Unauthorized HttpApi error.

Parameters:
NameTypeDescription
effectEffect

The protected handler effect to run on success.

credentialObject

The decoded credential (password is a Redacted value).

configObject

The server auth config (username, password).

Returns:

An effect that runs effect or fails with HttpApiError.Unauthorized.

Type: 
Effect

validateRawCredential(effect, credential, config) → {Effect}

Router-level credential check: pass through effect when auth is not required or the credential is authorized, otherwise short-circuit with an empty 401 response.

Parameters:
NameTypeDescription
effectEffect

The protected handler effect to run on success.

credentialObject

The decoded credential (password is a Redacted value).

configObject

The server auth config.

Returns:

Either effect or an effect succeeding with an empty 401 response.

Type: 
Effect

validator(target, zodSchema) → {function}

Build middleware that validates the chosen request segment against a Zod schema. On success the parsed value is stored on req.valid[target]; on failure it responds 400 with { data, errors, success: false }.

Parameters:
NameTypeDescription
targetstring

Which segment to validate: "json", "param", or "query".

zodSchema*

The Zod schema whose safeParse performs the validation.

Returns:

An Express middleware (req, res, next).

Type: 
function

wait(workspaceID, state, signal) → {Promise.<void>}

Run waitEffect on the app runtime, blocking until the workspace reaches the target state.

Parameters:
NameTypeDescription
workspaceIDstring

The workspace to wait on.

stateObject

The target sequence map (aggregate_id to seq) to wait for.

signal*

Optional AbortSignal to cancel the wait.

Returns:

Resolves once the workspace is fully synced.

Type: 
Promise.<void>

waitEffect(workspaceID, state, signal) → {Effect}

Build an Effect that blocks until the given workspace has synced to the target state.

Parameters:
NameTypeDescription
workspaceIDstring

The workspace to wait on.

stateObject

The target sequence map (aggregate_id to seq) to wait for.

signal*

Optional AbortSignal to cancel the wait.

Returns:

An Effect that resolves once the workspace is fully synced.

Type: 
Effect

waitForAbort(signal) → {Effect}

Build an effect that interrupts when the given abort signal fires.

Parameters:
NameTypeDescription
signalAbortSignal | undefined

The abort signal to observe; when absent the effect never completes.

Returns:

An effect that interrupts on abort (immediately if already aborted, or never if no signal).

Type: 
Effect

webHandler(corsOptions) → {function}

Get a web (Fetch-style) request handler for the server. Returns the memoized default handler when no CORS options are supplied; otherwise builds a fresh handler with the given CORS options (using a non-shared memo map so the default route memoization is not reused).

Parameters:
NameTypeDescription
corsOptions*

Optional server CORS configuration; when its cors list is empty/absent the default handler is used.

Returns:

A web request handler function.

Type: 
function

webSource(request) → {Request|undefined}

Extract the underlying web Request from a server request, if present.

Parameters:
NameTypeDescription
requestObject

The HTTP server request.

Returns:

The native Request source, or undefined when not a web Request.

Type: 
Request | undefined

websocket(request, target) → {Effect}

Proxy a WebSocket upgrade request to a target URL, bidirectionally piping messages between client and target. Forwards close events in both directions and translates socket errors into close frames.

Parameters:
NameTypeDescription
requestObject

The incoming HTTP server request (must support upgrade).

targetstring

The target URL to open the upstream WebSocket against.

Returns:

An effect resolving to an empty HTTP response once the upgrade is established.

Type: 
Effect

websocketProtocols(input) → {Array}

Parse the requested WebSocket subprotocols from the sec-websocket-protocol header.

Parameters:
NameTypeDescription
inputRequest | Object

A Request, or a plain object exposing the "sec-websocket-protocol" header.

Returns:

An array of trimmed, non-empty protocol names (empty when the header is absent).

Type: 
Array

websocketTargetURL(url) → {string}

Convert an http(s) URL into its WebSocket (ws/wss) equivalent for proxying.

Parameters:
NameTypeDescription
urlstring

The source URL (typically http: or https:).

Returns:

The URL string with the protocol mapped to ws: or wss: as appropriate.

Type: 
string

workspaceProxyURL(target, requestURL) → {URL}

Build the upstream URL used to proxy a request to a remote workspace target. Joins the target's base path with the request pathname, carries over the request search/hash, and strips the internal workspace query parameter.

Parameters:
NameTypeDescription
targetstring

Base URL of the remote workspace adapter.

requestURLURL

The incoming request URL being proxied.

Returns:

The fully-qualified proxy destination URL.

Type: 
URL

wrap(id, init, truncate, agents) → {function}

Wraps a tool's resolved info so its execute() decodes/validates arguments against the tool's parameter schema, applies output truncation (unless the result already reports a truncation state), and records a tracing span.

Parameters:
NameTypeDescription
idstring

The tool identifier (used in error messages and span attributes).

initObject | function

The resolved tool info, or a function returning it; either form provides parameters, execute, and optional formatValidationError.

truncateObject

The Truncate service used to cap oversized tool output and persist the full content to disk.

agentsObject

The Agent service used to look up the current agent (to tailor the truncation hint).

Returns:

A zero-arg function that lazily produces the tool info with its execute() wrapped.

Type: 
function