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).
- 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.
- number
(constant) DefaultSessionsLimit :number
Default number of sessions returned per page when no limit is supplied.
- 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").
- Object
(constant) Event
Bus event definitions for session status changes.
| Name | Type | Description |
|---|---|---|
Status | Object | Published whenever a session's status changes; carries sessionID and the new status. |
Idle | Object | Deprecated; published when a session becomes idle; carries only sessionID. |
(constant) Event
Bus event definitions for the todo list.
| Name | Type | Description |
|---|---|---|
Updated | Object | 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.
- 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.
- Object
(constant) Parameters :Object
Parameter schema for the question tool: a mutable array of question prompts.
- 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.
- Object
(constant) Parameters :Object
Default shell tool parameter schema, using the bash description text.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Object
(constant) commandAliases :Object
Maps legacy TUI command names to their current canonical command ids.
- 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.
- 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.
- 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.
- 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.
- 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.).
- 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.
- 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.
- 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.
- Object
(constant) fileHandlers :Object
Registers the handlers for the "file" HTTP API group on the instance API.
- 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.
- Object
(constant) globalHandlers :Object
Registers the handlers for the "global" HTTP API group on the root API.
- Object
(constant) gofmt :Object
gofmt formatter for Go files. Enabled when gofmt is on PATH. enabled() returns the command array or false.
- Object
(constant) hop :Set.<string>
Set of hop-by-hop header names that must not be forwarded to an upstream target.
- Set.<string>
(constant) htmlbeautifier :Object
htmlbeautifier formatter for ERB/HTML-ERB files. Enabled when htmlbeautifier is on PATH.
- 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.
- 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.
- Object
(constant) latexindent :Object
latexindent formatter for LaTeX files. Enabled when latexindent is on PATH.
- 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.
- 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.
- 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.
- Object
(constant) mix :Object
mix formatter for Elixir files. Enabled when mix is on PATH.
- Object
mode
- Deprecated
- Yes
(constant) nixfmt :Object
nixfmt formatter for Nix files. Enabled when nixfmt is on PATH.
- Object
(constant) ocamlformat :Object
ocamlformat formatter for OCaml files. enabled(context) requires ocamlformat on PATH and a .ocamlformat config up the tree.
- 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.
- 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.
- 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.
- Object
(constant) pint :Object
Laravel Pint formatter for PHP files. enabled(context) requires laravel/pint listed in a composer.json up the tree.
- 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.
- Object
(constant) projectHandlers :Object
Registers the handlers for the "project" HTTP API group on the instance API.
- Object
(constant) providerHandlers :Object
Registers the handlers for the "provider" HTTP API group on the instance API.
- 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.
- Object
(constant) ptyHandlers :Object
Builds the "pty" HTTP API handler group: shells/list/create/get/update/remove endpoints backed by the Pty service.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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).
- 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.
- Object
(constant) sessionHandlers :Object
Builds the "v2.session" HTTP API handler group: sessions (paginated list), prompt, compact, wait, and context endpoints.
- Object
(constant) shfmt :Object
shfmt formatter for shell scripts. Enabled when shfmt is on PATH.
- 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.
- 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.
- Object
(constant) terraform :Object
terraform formatter for Terraform files. Enabled when terraform is on PATH.
- 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.
- 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.
- Object
(constant) v2Handlers :Object
Combined v2 handlers layer: merges the v2 session and message handler groups and provides the SessionV2 default layer.
- Object
(constant) workspaceHandlers :Object
Builds the "workspace" HTTP API handler group: adapters/list/create/status/remove/sessionRestore endpoints.
- 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.
- Object
Methods
ConfigRoutes(registry) → {express.Router}
Build the Express router for the "/config" route group (GET/PATCH "/" and GET "/providers").
| Name | Type | Description |
|---|---|---|
registry | Object | Optional OpenAPI registry to record operation metadata against; falsy disables registration. |
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").
| Name | Type | Description |
|---|---|---|
registry | Object | Optional OpenAPI registry to record operation metadata against; also used to build the /doc spec. |
The configured Express router.
- Type:
- express.
Router
CorsMiddleware(opts) → {function}
Build CORS middleware whose origin callback delegates to isAllowedCorsOrigin(opts).
| Name | Type | Description |
|---|---|---|
opts | Object | Options forwarded to the origin check (opts.cors allow-list). |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | Optional OpenAPI registry to record operation metadata against; falsy disables registration. |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | Optional OpenAPI registry to record operation metadata against; falsy disables registration. |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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.
| Name | Type | Description |
|---|---|---|
envWorkspaceID | string | Optional workspace ID from the environment/flag to bias resolution. |
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.
| Name | Type | Description |
|---|---|---|
workspaceID | string | The workspace identifier to bind for the request. |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
upgradeWebSocket | function | Adapter factory that produces WebSocket-upgrade middleware (forwarded to PtyRoutes). |
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.
| Name | Type | Description |
|---|---|---|
backendAttributes | Object | Backend attributes merged into every log entry. |
An Express middleware (req, res, next).
- Type:
- function
McpRequest(args) → {Object}
Builds the JSON-RPC tools/call request schema for a given arguments schema.
| Name | Type | Description |
|---|---|---|
args | Object | The Effect Schema describing the tool's |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
upgradeWebSocket | function | Adapter factory that produces WebSocket-upgrade middleware for the connect route. |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | The OpenAPI registry used to register route metadata (may be falsy to skip). |
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.).
| Name | Type | Description |
|---|---|---|
registry | Object | OpenAPI operation registry; route metadata is registered against it when present. |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | OpenAPI operation registry; route metadata is registered against it when present. |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | OpenAPI operation registry; route metadata is registered against it when present. |
Configured Express Router.
- Type:
- Object
UIRoutes(registry) → {Object}
Builds the Express router that serves the embedded web UI via a catch-all route.
| Name | Type | Description |
|---|---|---|
registry | Object | OpenAPI operation registry (unused here; this route registers no metadata). |
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).
| Name | Type | Description |
|---|---|---|
registry | Object | Optional OpenAPI registry to record operation metadata against; falsy disables registration. |
The configured Express router.
- Type:
- express.
Router
addLegacyErrorSchemas(spec) → {void}
Add the legacy BadRequestError and NotFoundError component schemas the old SDK expected.
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- 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).
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- 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.
| Name | Type | Description |
|---|---|---|
ctx | Object | Tool execution context exposing the |
target | string | The absolute path the tool intends to access. |
options | Object | Optional behavior flags ( |
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.
| Name | Type | Description |
|---|---|---|
selection | Object | The backend selection to describe. |
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).
| Name | Type | Description |
|---|---|---|
key | string | The variable name (case-insensitive). |
cwd | string | The current working directory (value for PWD). |
shell | string | The shell executable path (PSHOME is its directory). |
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.
| Name | Type | Description |
|---|---|---|
chain | string | The chaining guidance sentence to embed. |
limits | Object | Output limits with |
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.
| Name | Type | Description |
|---|---|---|
inbound | Object | The upgraded inbound |
wsURL | string | The remote WebSocket target URL. |
protocols | Array.<string> | WebSocket subprotocols to request (empty = none). |
headers | Object | Outbound handshake headers (sanitized + target auth). |
- 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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
registry | Object | The registry of collected operations and schemas. |
documentation | Object | Top-level overrides (openapi version, info). |
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.
| Name | Type | Description |
|---|---|---|
ctx | Object | Request context exposing |
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.
| Name | Type | Description |
|---|---|---|
ref | string | The original |
schemas | Object | The component schemas map used to detect base names. |
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.
| Name | Type | Description |
|---|---|---|
input | * | The schema (or fragment) to canonicalize. |
schemas | Object | The component schemas map used to canonicalize |
The canonicalized schema value.
- Type:
- *
cap(ms) → {number}
Clamps a delay so it never exceeds the maximum safe setTimeout value.
| Name | Type | Description |
|---|---|---|
ms | number | Proposed delay in milliseconds. |
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).
| Name | Type | Description |
|---|---|---|
name | string | Shell name. |
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.
| Name | Type | Description |
|---|---|---|
shell | string | The shell executable path. |
command | string | The command string to execute. |
cwd | string | The working directory. |
env | Object | The environment variables. |
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.
| Name | Type | Description |
|---|---|---|
chain | string | The chaining guidance sentence to embed. |
limits | Object | Output limits with |
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.
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- Type:
- void
commands(node) → {Array}
Collect all command descendant nodes within a parse tree node.
| Name | Type | Description |
|---|---|---|
node | Object | A tree-sitter syntax node (typically the root). |
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.
| Name | Type | Description |
|---|---|---|
messages | Array | Ordered session messages, each |
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.
| Name | Type | Description |
|---|---|---|
name | string | The component name (possibly dotted, e.g. |
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.
| Name | Type | Description |
|---|---|---|
filePath | string | The config file path. |
searchRoots | Array.<string> | Root substrings used to make the name relative. |
The extension-less entry name.
- Type:
- string
configuredWorkspaceID() → {*}
Read the workspace ID pinned via the CLOSEDCODE_WORKSPACE_ID flag, if any.
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.
| Name | Type | Description |
|---|---|---|
html | string | The raw HTML source. |
The Markdown rendering of the HTML.
- Type:
- string
convertToLineEnding(text, ending) → {string}
Converts LF line endings in the text to the requested ending.
| Name | Type | Description |
|---|---|---|
text | string | LF-normalized text. |
ending | string | The target line ending ("\n" leaves the text unchanged, otherwise CRLF is used). |
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.
| Name | Type | Description |
|---|---|---|
corsOptions | * | The server CORS configuration consulted by the allowed-origin check. |
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.
| Name | Type | Description |
|---|---|---|
opts | Object | Server options (e.g. opts.cors allow-list) passed to CorsMiddleware. |
selection | Object | The backend selection; defaults to ServerBackend.select(). |
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.
| Name | Type | Description |
|---|---|---|
expressApp | Object | The Express application to wrap. |
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.
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).
| Name | Type | Description |
|---|---|---|
corsOptions | * | The server CORS configuration applied to the global CORS middleware. |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
An object with upgradeWebSocket and injectWebSocket.
- Type:
- Object
decode(input) → {string}
URI-decode a value, returning the original input unchanged if decoding throws.
| Name | Type | Description |
|---|---|---|
input | string | The possibly URI-encoded string. |
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.
| Name | Type | Description |
|---|---|---|
input | string | The Base64-encoded |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request (uses query.directory and directory headers). |
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.
| Name | Type | Description |
|---|---|---|
request | Object | The HTTP server request. |
url | URL | The parsed request URL. |
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).
| Name | Type | Description |
|---|---|---|
id | string | The tool identifier. |
init | Effect | An Effect that resolves the tool's base info (description, parameters, execute). |
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.
| Name | Type | Description |
|---|---|---|
type | string | Unique event type identifier (e.g. "server.instance.disposed"). |
properties | * | Effect Schema describing the event's |
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.
| Name | Type | Description |
|---|---|---|
attempt | number | 1-based attempt number. |
error | * | Optional APIError-like value carrying |
Delay in milliseconds before retrying.
- Type:
- number
described(schema, description) → {Object}
Annotate a schema with a human-readable description for OpenAPI documentation.
| Name | Type | Description |
|---|---|---|
schema | Object | The Effect schema to annotate. |
description | string | The description to attach to the schema. |
A new schema carrying the description annotation.
- Type:
- Object
detectLineEnding(text) → {string}
Detects the dominant line ending of a text.
| Name | Type | Description |
|---|---|---|
text | string | The text to inspect. |
"\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.
| Name | Type | Description |
|---|---|---|
prev | Object | Sequence map (aggregate_id to seq) captured before the change. |
next | Object | Sequence map (aggregate_id to seq) captured after the change. |
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.
| Name | Type | Description |
|---|---|---|
input | Object | Either a |
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.
| Name | Type | Description |
|---|---|---|
text | string | The token to inspect. |
ps | boolean | Whether the active shell is PowerShell. |
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.
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.
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.
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.
| Name | Type | Description |
|---|---|---|
value | * | Arbitrary value, array, or object to encode. |
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).
| Name | Type | Description |
|---|---|---|
value | * | The message data to encode. |
The storage-ready encoded value.
- Type:
- *
envValue(key) → {string}
Look up an environment variable, matching case-insensitively on Windows.
| Name | Type | Description |
|---|---|---|
key | string | The environment variable name. |
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)).
| Name | Type | Attributes | Description |
|---|---|---|---|
codes | number | <repeatable> | One or more status codes present in ERRORS (400, 404). |
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.
| Name | Type | Description |
|---|---|---|
data | Object | The event payload to serialise. |
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.
| Name | Type | Description |
|---|---|---|
data | * | The payload to serialize into the event's data field. |
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.
| Name | Type | Description |
|---|---|---|
bus | Object | Bus service used to subscribe to all events. |
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.
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 ~.
| Name | Type | Description |
|---|---|---|
text | string | The token to expand. |
cwd | string | Current working directory for PWD/relative expansion. |
shell | string | Shell executable path for PSHOME. |
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).
| Name | Type | Description |
|---|---|---|
messages | Array | Session messages, each with a |
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.
| Name | Type | Description |
|---|---|---|
html | string | The raw HTML source. |
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.
| Name | Type | Description |
|---|---|---|
msgs | Array | Session messages in newest-first order. |
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.
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- Type:
- void
flattenOptions(options) → {Array|undefined}
Flatten nested anyOf/oneOf unions into a single flat list of leaf option schemas.
| Name | Type | Description |
|---|---|---|
options | Array | | The union options to flatten. |
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.
| Name | Type | Description |
|---|---|---|
selection | Object | The current backend selection. |
backend | string | The backend to force. |
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.
| Name | Type | Description |
|---|---|---|
err | * | The error to inspect. |
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).
| Name | Type | Description |
|---|---|---|
e | * | The caught error value. |
ctx | Object | Context |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
sessionID | string | The session whose messages to scan. |
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.
| Name | Type | Description |
|---|---|---|
filePath | string | File path or name to inspect. |
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.
| Name | Type | Description |
|---|---|---|
filePath | string | File path or name whose extension is inspected. |
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.
| Name | Type | Description |
|---|---|---|
url | URL | Absolute request URL. |
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).
| Name | Type | Description |
|---|---|---|
obj | Object | Source object (may be undefined). |
field1 | string | Field name to read. |
cb | function | Optional callback applied to the value when it is an object. |
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).
| Name | Type | Description |
|---|---|---|
agent | Object | The agent whose permission rules to evaluate; may be undefined. |
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.
| Name | Type | Description |
|---|---|---|
messages | Array | Model messages whose |
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.
| Name | Type | Description |
|---|---|---|
input | Request | | A Request, a Headers instance, or a plain key/value header object. |
extra | Request | | Optional additional headers to set after sanitization. |
The sanitized (and optionally augmented) Headers object.
- Type:
- Headers
home(text) → {string}
Expand a leading ~ (home directory) in a path-like token.
| Name | Type | Description |
|---|---|---|
text | string | The token possibly beginning with |
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.
| Name | Type | Description |
|---|---|---|
client | Object | The HTTP client used to execute the upstream request. |
url | string | The target URL to proxy to. |
extra | * | Extra headers to merge into the proxied request. |
request | Object | The incoming HTTP server request to forward. |
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.
| Name | Type | Description |
|---|---|---|
rows | Array | Plain message rows to hydrate. |
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.
| Name | Type | Description |
|---|---|---|
row | Object | A plain message row with |
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.
| Name | Type | Description |
|---|---|---|
info | Object | A defined-tool record produced by define(), with |
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.
- 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.
| Name | Type | Description |
|---|---|---|
input | string | The request Origin header value (may be empty/undefined). |
opts | Object | Options object; opts.cors is an array of explicitly allowed origins. |
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.
| Name | Type | Description |
|---|---|---|
config | Object | The server auth config. |
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).
| Name | Type | Description |
|---|---|---|
schema | Object | The schema to test. |
True for a bare array schema.
- Type:
- boolean
isBareObjectSchema(schema) → {boolean}
Check whether a schema is a bare object type (no properties or additionalProperties).
| Name | Type | Description |
|---|---|---|
schema | Object | The schema to test. |
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.
| Name | Type | Description |
|---|---|---|
response | Object | The OpenAPI response object. |
name | string | The built-in error name (e.g. |
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.
| Name | Type | Description |
|---|---|---|
credential | Object | The decoded credential (password is a Redacted value). |
config | Object | The server auth config. |
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.
| Name | Type | Description |
|---|---|---|
schema | Object | The schema to test. |
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.
| Name | Type | Description |
|---|---|---|
value | string | Candidate shell kind name. |
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.
| Name | Type | Description |
|---|---|---|
method | string | HTTP method of the request (e.g. "GET"). |
path | string | Request URL pathname. |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
response | Object | The OpenAPI response object. |
name | string | The component name to test against. |
True when the response references #/components/schemas/<name>.
- Type:
- boolean
jsonBody(schema) → {Object}
Build an OpenAPI requestBody object for an application/json endpoint.
| Name | Type | Description |
|---|---|---|
schema | * | The Zod or JSON Schema describing the JSON body. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
effect | function | A function returning an Effect generator to run. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
gen | function | The generator function passed to Effect.gen. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
fn | function | A function returning an Effect generator to run. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
gen | function | The generator function passed to Effect.gen. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
effect | function | A function returning an Effect generator to run. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
effect | function | A function returning an Effect generator to run. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
gen | function | The generator function passed to Effect.gen. |
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.
| Name | Type | Description |
|---|---|---|
name | string | Span name. |
req | Object | Express request object. |
res | Object | Express response object. |
gen | function | Generator function producing the Effect to run. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
c | Object | The request context; also used to build the JSON response. |
effect | function | A function receiving the context |
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.
| Name | Type | Description |
|---|---|---|
name | string | Span name. |
req | Object | The Express request object. |
res | Object | The Express response object. |
genFn | function | A generator function consumed by Effect.gen producing the response value. |
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.
| Name | Type | Description |
|---|---|---|
value | string | The default key binding (e.g. "ctrl+x"). |
description | string | Human-readable description of the action. |
The Effect Schema for the field.
- Type:
- Schema
legacyErrorResponse(description, name) → {Object}
Build a legacy error response object that references a named error schema.
| Name | Type | Description |
|---|---|---|
description | string | The response description. |
name | string | The component schema name to reference. |
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.
| Name | Type | Description |
|---|---|---|
a | string | First string. |
b | string | Second string. |
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.
| Name | Type | Description |
|---|---|---|
filepath | string | Absolute path of the file to read. |
opts | Object | Paging options: {offset: number, limit: number}. |
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).
| Name | Type | Description |
|---|---|---|
app | Object | The Express application/request handler. |
opts | Object | Listen options: |
inject | function | Optional callback invoked with the http.Server before it listens. |
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.
| Name | Type | Description |
|---|---|---|
ids | Array.<string> | Optional aggregate IDs to restrict the query to; loads all when omitted/empty. |
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.
| Name | Type | Description |
|---|---|---|
messages | Array | Session messages to inspect. |
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.
| Name | Type | Description |
|---|---|---|
filePath | string | The file path to lock; resolved to a canonical key. |
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).
| Name | Type | Description |
|---|---|---|
properties | Object | The OpenAPI |
- 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.
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.
| Name | Type | Description |
|---|---|---|
self | Effect | The Effect whose NotFoundError should be translated. |
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.
| Name | Type | Description |
|---|---|---|
ctx | * | The instance context to act on after the response. |
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.
| Name | Type | Description |
|---|---|---|
input | Object | The generated OpenAPI spec object (mutated in place). |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | The registry used when converting Zod schemas. |
schema | * | A Zod schema or plain JSON Schema object. |
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.
| Name | Type | Description |
|---|---|---|
paths | Object | The OpenAPI paths object to augment. |
- Type:
- void
mergeOptions(target, source) → {Object}
Deep-merge a source options object into a target, treating a nullish source as an empty object.
| Name | Type | Description |
|---|---|---|
target | Object | Base options object. |
source | Object | Options to merge in (may be null/undefined). |
The deep-merged options object.
- Type:
- Object
missingWorkspaceResponse(id) → {Object}
Build a 500 plain-text response indicating the requested workspace was not found.
| Name | Type | Description |
|---|---|---|
id | * | The workspace ID that could not be resolved. |
An HTTP server response with status 500.
- Type:
- Object
nextTuiRequest() → {Promise.<Object>}
Pulls the next pending TUI request from the request queue.
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.
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- 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.
| Name | Type | Description |
|---|---|---|
spec | Object | The OpenAPI spec object (mutated in place). |
- Type:
- void
normalizeLegacyErrorResponses(operation) → {void}
Replace built-in 400/404 error responses on an operation with the legacy error response shapes.
| Name | Type | Description |
|---|---|---|
operation | Object | The OpenAPI operation object (mutated in place). |
- 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.
| Name | Type | Description |
|---|---|---|
operation | Object | The OpenAPI operation object (mutated in place). |
path | string | The route path (e.g. |
method | string | The lowercase HTTP method (e.g. |
- Type:
- void
normalizeLineEndings(text) → {string}
Converts all CRLF line endings in the text to LF.
| Name | Type | Description |
|---|---|---|
text | string | The text to normalize. |
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.
| Name | Type | Description |
|---|---|---|
param | Object | The OpenAPI parameter object (mutated in place). |
route | string | The route key (e.g. |
- 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.
| Name | Type | Description |
|---|---|---|
path | string | The Express-style route path. |
The normalized OpenAPI path.
- Type:
- string
nullable(schema) → {Object}
Wrap a schema in an anyOf: [schema, {type:"null"}] union, unless it is already nullable.
| Name | Type | Description |
|---|---|---|
schema | Object | The schema to make nullable. |
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).
| Name | Type | Description |
|---|---|---|
row | Object | Cursor |
A Sequelize Op.or condition.
- Type:
- Object
openapi() → {Object}
Build a fresh Express app and return its OpenAPI spec, without listening.
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
key | string | The route parameter name. |
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..
| Name | Type | Description |
|---|---|---|
key | string | The route param name. |
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..
| Name | Type | Description |
|---|---|---|
key | string | The route param name. |
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..
| Name | Type | Description |
|---|---|---|
key | string | The route param name. |
The normalised attribute key.
- Type:
- string
paramToAttributeKey(key) → {string}
Normalises a route param name into an OTel span attribute key.
| Name | Type | Description |
|---|---|---|
key | string | Route param name (e.g. "sessionID", "directory"). |
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.
| Name | Type | Description |
|---|---|---|
key | string | The route parameter name. |
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.
| Name | Type | Description |
|---|---|---|
description | string | Annotation text describing the |
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.
| Name | Type | Description |
|---|---|---|
headers | Object | A Headers-like object exposing get(name). |
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 {}.
| Name | Type | Description |
|---|---|---|
body | string | The raw request body text. |
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.
| Name | Type | Description |
|---|---|---|
json | string | The plist contents as a JSON string. |
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.
| Name | Type | Description |
|---|---|---|
row | Object | A plain part row with |
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.
| Name | Type | Description |
|---|---|---|
message_id | string | The message whose parts to load. |
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.
| Name | Type | Description |
|---|---|---|
node | Object | A tree-sitter command syntax node. |
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.
| Name | Type | Default | Description |
|---|---|---|---|
list | Array | The command's tokens (first entry is the command name). | |
ps | boolean | Whether the active shell is PowerShell. | |
cmd | boolean | false | Whether the active shell is cmd.exe (affects |
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.
| Name | Type | Description |
|---|---|---|
route | string | The route key (e.g. |
name | string | The path parameter name. |
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.
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.
| Name | Type | Description |
|---|---|---|
row | Object | A Sequelize model instance, or null/undefined. |
The plain object representation, or undefined.
- Type:
- Object
plain(row) → {Object}
Convert a Sequelize model instance to a plain object, or undefined when null.
| Name | Type | Description |
|---|---|---|
row | Object | A Sequelize model instance, or null/undefined. |
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.
| Name | Type | Description |
|---|---|---|
request | Object | The incoming HTTP server request. |
sessionWorkspaceID | * | The workspace ID from the request's session, if any. |
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.
| Name | Type | Description |
|---|---|---|
request | Object | The incoming HTTP server request. |
url | URL | The parsed request URL. |
workspace | Object | The resolved workspace. |
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.
| Name | Type | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
opts | Object | Policy hooks. Properties
|
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.
| Name | Type | Description |
|---|---|---|
name | string | PowerShell variant name ("pwsh" or "powershell"). |
chain | string | The chaining guidance sentence to embed. |
pathSep | string | Path separator to use in examples ("\" or "/"). |
limits | Object | Output limits with |
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.
| Name | Type | Description |
|---|---|---|
name | string | Shell name ("pwsh" or "powershell"). |
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.
| Name | Type | Description |
|---|---|---|
text | string | The token to inspect. |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
text | string | The output text to preview. |
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.
| Name | Type | Description |
|---|---|---|
name | string | Shell name ("bash", "pwsh", "powershell", or "cmd"). |
platform | string | Node platform string (e.g. "win32"). |
limits | Object | Output limits with |
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.
| Name | Type | Description |
|---|---|---|
effect | Effect | The handler effect to run within the instance context. |
store | Object | The |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request. |
res | Object | The Express response. |
next | function | Invokes the downstream handler chain. |
workspaceID | string | The workspace to provide as context. |
directory | string | The resolved project directory. |
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.
| Name | Type | Description |
|---|---|---|
model | Object | Model descriptor with an |
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.
| Name | Type | Description |
|---|---|---|
text | string | The possibly provider-qualified path token. |
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.
| Name | Type | Description |
|---|---|---|
metadata | Object | Part metadata, possibly including providerExecuted. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The incoming Express request. |
res | Object | The Express response to write the proxied result to. |
workspace | Object | The target workspace. |
target | Object | The upstream target's base URL and headers. |
url | URL | The original request URL used to derive the upstream path. |
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).
| Name | Type | Description |
|---|---|---|
client | Object | The HTTP client used for proxying. |
request | Object | The incoming HTTP server request. |
workspace | Object | The remote workspace being proxied to. |
target | Object | The resolved remote target ( |
url | URL | The parsed request URL. |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
port | number | TCP port the server is listening on. |
domain | string | Optional mDNS host name to advertise (defaults to "closedcode.local"). |
- Type:
- void
queryBoolean(value) → {boolean}
Coerce a query-string boolean ("true"/"false" or an actual boolean) into a boolean.
| Name | Type | Description |
|---|---|---|
value | * | The raw query value (string, boolean, or undefined). |
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.
| Name | Type | Description |
|---|---|---|
value | * | Raw query value ( |
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.
| Name | Type | Description |
|---|---|---|
effect | Effect | The effect to run. |
signal | AbortSignal | | The abort signal; when absent |
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.
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.
| Name | Type | Description |
|---|---|---|
registry | Object | The registry to push the operation into. |
method | string | The HTTP method (case-insensitive). |
path | string | The Express-style route path (normalized to OpenAPI form). |
describe | Object | Operation metadata (summary, description, operationId, responses, requestBody, parameters). |
- 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.
| Name | Type | Description |
|---|---|---|
name | string | Shell name ("bash", "pwsh", "powershell", or "cmd"). |
platform | string | Node platform string (e.g. "win32"). |
limits | Object | Output limits with |
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.
| Name | Type | Description |
|---|---|---|
template | string | Template string containing |
values | Object | Map of placeholder keys to replacement strings. |
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).
| Name | Type | Description |
|---|---|---|
content | string | The original file content. |
oldString | string | The text to find (matched via the replacer cascade). |
newString | string | The replacement text. |
replaceAll | boolean | When true, replaces every occurrence; otherwise requires a unique match. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request. |
res | Object | The Express response. |
next | function | Passes control on when validation passed. |
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).
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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).
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request object. |
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).
| Name | Type | Description |
|---|---|---|
req | Object | Express request object. |
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.
| Name | Type | Description |
|---|---|---|
c | Object | The request context (Hono-style context exposing |
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.
| Name | Type | Description |
|---|---|---|
req | Object | The Express request (uses originalUrl/url). |
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.
| Name | Type | Description |
|---|---|---|
request | Object | The HTTP server request. |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | The registry to record named schemas in. |
zodSchema | * | The Zod schema to convert. |
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.
| Name | Type | Description |
|---|---|---|
registry | Object | The registry used for schema conversion. |
requestBody | Object | The requestBody object whose content schemas are resolved. |
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).
| Name | Type | Description |
|---|---|---|
workspace | Object | The workspace whose target is being resolved. |
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.
| Name | Type | Description |
|---|---|---|
input | Object | Request inputs with |
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.
| Name | Type | Description |
|---|---|---|
asset | string | The asset reference (URL, absolute, or relative path). |
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.
| Name | Type | Description |
|---|---|---|
id | * | The workspace ID to resolve, if any. |
envWorkspaceID | * | The env-pinned workspace ID; when set, resolution is skipped. |
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.
| Name | Type | Description |
|---|---|---|
url | URL | absolute request URL (built by caller) |
method | string | HTTP method (for isLocalWorkspaceRoute) |
envWorkspaceID | WorkspaceID | | Flag.CLOSEDCODE_WORKSPACE_ID (already WorkspaceID.make'd) or undefined |
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 totarget
- Type:
- Promise.<Object>
responseDescription(description) → {Object}
Build an OpenAPI annotation that overrides the description of an endpoint's 200 response.
| Name | Type | Description |
|---|---|---|
description | string | The description to set on the operation's "200" response. |
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.
| Name | Type | Description |
|---|---|---|
error | * | Parsed error to classify. |
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.
| Name | Type | Description |
|---|---|---|
input | * | The spec value (object/array) to traverse (mutated in place). |
from | string | The source component name. |
to | string | The target component name. |
- 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.
| Name | Type | Description |
|---|---|---|
client | Object | The HTTP client used for remote proxying. |
effect | Effect | The local handler effect to run for |
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.
| Name | Type | Description |
|---|---|---|
client | Object | The HTTP client used for remote proxying. |
effect | Effect | The local handler effect to run for |
plan | * | The |
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.
| Name | Type | Description |
|---|---|---|
name | string | Span name. |
req | Object | The Express request object (used to derive span attributes). |
effect | Effect | The Effect to execute within the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
effect | Effect | The Effect to run inside the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
effect | Effect | The Effect to run inside the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
effect | Effect | The Effect to run inside the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
req | Object | The Express request object. |
effect | Effect | The Effect to run inside the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | Span name. |
req | Object | Express request object (source of span attributes). |
effect | Effect | The Effect to run within the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | The span name. |
c | Object | The request context used to derive span attributes. |
effect | Effect | The effect to execute within the span. |
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.
| Name | Type | Description |
|---|---|---|
name | string | Span name. |
req | Object | The Express request object (used to derive span attributes). |
effect | Effect | The Effect to execute within the span. |
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.
| Name | Type | Description |
|---|---|---|
out | Headers | The Headers object to mutate. |
- Type:
- void
select() → {Object}
Select the server backend to use.
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.
| Name | Type | Description |
|---|---|---|
url | URL | The parsed request URL. |
sessionWorkspaceID | * | The workspace ID associated with the request's session, if any. |
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.
| Name | Type | Description |
|---|---|---|
app | Object | The Express application. |
mountPath | string | The path to mount the docs UI at (e.g. "/docs"). |
spec | Object | The built OpenAPI document to serve. |
- 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.
| Name | Type | Description |
|---|---|---|
req | Object | Express request object (uses |
res | Object | Express response object. |
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.
| Name | Type | Description |
|---|---|---|
request | Object | HTTP request whose url is matched against the bundle. |
services | Object | Service bag providing fs.existsSafe and fs.readFile. |
An Effect yielding the HttpServerResponse to send.
- Type:
- Effect
shellDisplayName(name) → {string}
Map an internal shell name to a human-readable display name.
| Name | Type | Description |
|---|---|---|
name | string | Internal shell name (e.g. "pwsh", "powershell", "cmd"). |
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).
| Name | Type | Description |
|---|---|---|
request | Object | The HTTP server request. |
url | URL | The parsed request URL. |
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.
| Name | Type | Description |
|---|---|---|
filePath | string | The file path to inspect (Windows or POSIX separators). |
searchRoots | Array.<string> | Root substrings to match against, in priority order. |
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.
| Name | Type | Description |
|---|---|---|
node | Object | A tree-sitter command syntax node. |
The command's source text.
- Type:
- string
source(input) → {string}
Resolve the source identifier (used for error reporting) of a substitution input.
| Name | Type | Description |
|---|---|---|
input | Object | Either a |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
h | Object | Sequelize handle |
sessionID | string | Session whose messages are being projected. |
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).
| Name | Type | Description |
|---|---|---|
input | * | The schema (or schema fragment) to serialize. |
schemas | Object | The component schemas map used to canonicalize |
A deterministic JSON string for structural comparison.
- Type:
- string
stop(close) → {Promise.<void>}
Stop the server, resolving once it has fully closed. Idempotent.
| Name | Type | Description |
|---|---|---|
close | boolean | When true, also forcibly close all (idle and active) connections. |
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.
| Name | Type | Description |
|---|---|---|
sessionID | string | The session whose messages to stream. |
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.
| Name | Type | Description |
|---|---|---|
res | Object | The Express response object. |
req | Object | The Express request object. |
subscribe | function | Called with the AsyncQueue; should push events onto it and return an unsubscribe function. |
- 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.
| Name | Type | Description |
|---|---|---|
schema | Object | The schema to normalize (mutated and returned). |
The schema with optional-null arms removed.
- Type:
- Object
submitTuiRequest(body) → {void}
Enqueues a TUI request for a connected TUI to pull.
| Name | Type | Description |
|---|---|---|
body | Object | The TUI request to enqueue ( |
- Type:
- void
submitTuiResponse(body) → {void}
Enqueues a TUI response for the originating caller waiting in callTui.
| Name | Type | Description |
|---|---|---|
body | * | The response payload to enqueue. |
- 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.
| Name | Type | Description | |||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
input | Object | Substitution input. Properties
|
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.
| Name | Type | Description |
|---|---|---|
message | Object | A message with a |
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.
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.
| Name | Type | Description |
|---|---|---|
text | string | The full output text. |
maxLines | number | Maximum number of trailing lines to keep. |
maxBytes | number | Maximum byte budget for the kept text. |
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".
| Name | Type | Description |
|---|---|---|
value | string | Shell name to classify. |
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.
| Name | Type | Description |
|---|---|---|
input | Array | Stored messages, each |
model | Object | Target model |
options | Object | Optional |
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).
| Name | Type | Description |
|---|---|---|
info | Object | Partial session update info. |
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.
| Name | Type | Description |
|---|---|---|
req | Object | Express request object. |
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.
| Name | Type | Description |
|---|---|---|
diff | string | A unified diff string. |
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.
| Name | Type | Description |
|---|---|---|
text | string | The tool output text. |
maxChars | number | Maximum allowed length, or 0/undefined for no limit. |
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).
| Name | Type | Description |
|---|---|---|
messages | Array | Ordered session messages, each |
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.
- Type:
- void
unquote(text) → {string}
Strip a single matching pair of surrounding single or double quotes.
| Name | Type | Description |
|---|---|---|
text | string | The possibly-quoted token text. |
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.
| Name | Type | Description |
|---|---|---|
input | string | A path as emitted by git, possibly double-quoted with escape sequences. |
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.
| Name | Type | Description |
|---|---|---|
h | Object | Sequelize handle |
event | Object | The session-message event |
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.
| Name | Type | Description |
|---|---|---|
input | Object |
|
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.
| Name | Type | Description |
|---|---|---|
effect | Effect | The protected handler effect to run on success. |
credential | Object | The decoded credential (password is a Redacted value). |
config | Object | The server auth config ( |
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.
| Name | Type | Description |
|---|---|---|
effect | Effect | The protected handler effect to run on success. |
credential | Object | The decoded credential (password is a Redacted value). |
config | Object | The server auth config. |
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 }.
| Name | Type | Description |
|---|---|---|
target | string | Which segment to validate: "json", "param", or "query". |
zodSchema | * | The Zod schema whose safeParse performs the validation. |
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.
| Name | Type | Description |
|---|---|---|
workspaceID | string | The workspace to wait on. |
state | Object | The target sequence map (aggregate_id to seq) to wait for. |
signal | * | Optional AbortSignal to cancel the wait. |
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.
| Name | Type | Description |
|---|---|---|
workspaceID | string | The workspace to wait on. |
state | Object | The target sequence map (aggregate_id to seq) to wait for. |
signal | * | Optional AbortSignal to cancel the wait. |
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.
| Name | Type | Description |
|---|---|---|
signal | AbortSignal | | The abort signal to observe; when absent the effect never completes. |
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).
| Name | Type | Description |
|---|---|---|
corsOptions | * | Optional server CORS configuration; when its |
A web request handler function.
- Type:
- function
webSource(request) → {Request|undefined}
Extract the underlying web Request from a server request, if present.
| Name | Type | Description |
|---|---|---|
request | Object | The HTTP server request. |
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.
| Name | Type | Description |
|---|---|---|
request | Object | The incoming HTTP server request (must support upgrade). |
target | string | The target URL to open the upstream WebSocket against. |
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.
| Name | Type | Description |
|---|---|---|
input | Request | | A Request, or a plain object exposing the "sec-websocket-protocol" header. |
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.
| Name | Type | Description |
|---|---|---|
url | string | The source URL (typically http: or https:). |
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.
| Name | Type | Description |
|---|---|---|
target | string | Base URL of the remote workspace adapter. |
requestURL | URL | The incoming request URL being proxied. |
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.
| Name | Type | Description |
|---|---|---|
id | string | The tool identifier (used in error messages and span attributes). |
init | Object | | The resolved tool info, or a function returning it; either form provides parameters, execute, and optional formatValidationError. |
truncate | Object | The Truncate service used to cap oversized tool output and persist the full content to disk. |
agents | Object | The Agent service used to look up the current agent (to tailor the truncation hint). |
A zero-arg function that lazily produces the tool info with its execute() wrapped.
- Type:
- function