@fro.bot/opencode-plugin 0.3.7 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,9 +40,9 @@ To turn it on, create `~/.config/fro-bot/opencode-plugin/tracing.json` (under `$
40
40
  - `headers` is optional, at most 16 entries. They carry your collector credential.
41
41
  - `hosts` is **required**: one to 16 machine names, and tracing is on only on a machine named in it. A name matches the machine's host name exactly (ignoring case and a trailing dot), or, when it has no dot, the part of the host name before its first dot (`my-laptop` matches `my-laptop.local`). There are no wildcards. A copy of this file on any other machine does nothing there, silently.
42
42
 
43
- Every span carries `langfuse.session.id` set to the **root** session's id, so Langfuse's Sessions view groups a subagent's spans with its parent's, while the standard `session.id` stays each span's own session. In the Action, each span also carries the run's repository, run id, attempt, job and trigger as `langfuse.trace.metadata.*` (`repository`, `run_id`, `run_attempt`, `job`, `trigger`), so Langfuse shows and filters by them; a local session has none of these.
43
+ Every span carries `langfuse.session.id` set to the **root** session's id, so Langfuse's Sessions view groups a subagent's spans with its parent's, while the standard `session.id` stays each span's own session. In the Action, each span also carries the run's repository, run id, attempt, job and trigger as `langfuse.trace.metadata.*` (`repository`, `run_id`, `run_attempt`, `job`, `trigger`), so Langfuse shows and filters by them; a local session has none of these run fields, and gets only the repository described under "What a trace contains".
44
44
 
45
- The root span of every trace (a turn's `invoke_agent`, and the root of a late continuation trace) also carries `langfuse.trace.name` set to the fixed string `fro-bot run`, which Langfuse shows as the trace's name. No other span has it, and it holds no content.
45
+ The root span of every trace (a turn's `invoke_agent`, and the root of a late continuation trace) also carries `langfuse.trace.name`, which Langfuse shows as the trace's name: the fixed string `fro-bot run` in an Action run, and `opencode session` in a local session. No other span has it, and it holds no content.
46
46
 
47
47
  ### What a trace contains
48
48
 
@@ -55,6 +55,8 @@ Spans follow the OpenTelemetry GenAI conventions at the revision named in `genai
55
55
  - `langfuse.observation.type`: set explicitly, so Langfuse does not depend on mapping the operation name: `generation` on a model request, `agent` on `invoke_agent` and `tool` on a tool call.
56
56
  - `fro_bot.outcome`: how the span ended. `ok`, `error` or `interrupted`. The Action's own lifecycle trace (`action.main` and its phases, exported by the Action, not by this plugin) also uses the attribute name `fro_bot.outcome`, with a different set of values: `succeeded`, `incomplete`, `failed`, `skipped` or `cancelled` (`src/shared/lifecycle-tracer.ts`), with `fro_bot.reason` for a stable reason code. A query on `fro_bot.outcome` must say which sender it means, by `service.name`.
57
57
  - In an Action run, `cicd.pipeline.run.id` (the run id, the same value as `langfuse.trace.metadata.run_id`) and, when the launcher carried `serverUrl`, `cicd.pipeline.run.url.full`. The URL is GitHub's own form: `<server>/<owner>/<repo>/actions/runs/<run id>` for the first attempt (the API's `html_url` for attempt 1 has no `/attempts/` part) and `<server>/<owner>/<repo>/actions/runs/<run id>/attempts/<attempt>` for a re-run. It is left off when the repository, run id or attempt is not a plain `owner/repo` slug and digits, so a URL is never guessed. The `cicd.*` attributes belong to the core OpenTelemetry conventions (release-candidate stability), not to the GenAI revision the plugin pins.
58
+ - `langfuse.environment`: `automation` on every span of a trace whose **root** session id starts with `ses_aut_`, subagents of that root included, in a local session and in an Action run. Any other trace sets none, and Langfuse reads that as `default`. This is a **labelling convention, not proof of where a session came from**: `ses_aut_` is the prefix OpenCode's own automation sessions use, but any caller can create a session with such an id, and a session without it may still be automated. Do not use it to decide anything about trust or origin.
59
+ - `langfuse.trace.metadata.repository` (local session only): the `owner/repo` of the `origin` remote of the **root** session's directory (the one its `session.created` event named), falling back to the directory of the OpenCode location the plugin loaded in. It is looked up **once per trace**, when the trace's first span is built, and every span of that trace carries the answer or none does: a linked subagent created in another checkout, a root resumed with no creation event, and a lookup that finishes mid-trace cannot give one trace two repositories. The lookup never waits: it starts in the background when the server starts and when a session is created, and a trace whose lookup had not finished by its first span has no repository. It reads the checkout's git files with `node:fs/promises` alone (no `git` process): a `.git` directory, or a `.git` file naming a `gitdir` (a linked worktree's `commondir` is followed), in that directory or one of its parents. Each file is opened once, without following links and without blocking, and the open handle is checked before anything is read: only a regular file is read, up to a size bound, under one 250 ms budget per directory, and only one directory is looked up at a time (the slot is held until the read really returns, and a directory asked for while it is taken has no repository until a later trace asks again), so a named pipe, a symlink (a symlinked `.git` or `config` is not followed) or a slow disk leaves the repository unset and never stalls OpenCode. The config is read the way git reads it: the remote's name must be exactly `origin` (`[remote "Origin"]` is not it), repeated `[remote "origin"]` sections are merged and the first `url` wins, values may be quoted, and `#` and `;` comments after a header or a value are ignored. A line ending in a backslash joins the next line in git; this reader does not follow that, so a config with one before or inside the `origin` section leaves the repository unset rather than guess. Only a `github.com` remote is accepted, as `https://github.com/<owner>/<repo>`, `git@github.com:<owner>/<repo>` or `ssh://git@github.com/<owner>/<repo>` (with or without `.git`), and the owner and repo must follow GitHub's naming rules (an owner is at most 39 characters, a repo at most 100). Any other host (an enterprise server included), form or name leaves it unset, as does any read error; credentials in a remote are never exported. The answer is cached per directory (256 at most) for the life of the server, so a remote added later is not seen until it restarts. It is a **declared label read from a checkout, not a verified identity**: a checkout can point `origin` anywhere. An Action run keeps the repository its launcher declared and this is never read there.
58
60
 
59
61
  **Model requests (`chat`).**
60
62
 
@@ -66,7 +68,7 @@ Spans follow the OpenTelemetry GenAI conventions at the revision named in `genai
66
68
 
67
69
  - `fro_bot.tool.outcome`: `success` (the tool ran and returned), `error` (it failed, or OpenCode refused the call), `rejected` (a permission rule or this plugin's subagent resume guard refused it before it ran: `error.type` is `permission.rejected` or `plugin.reuse-guard`; the guard exists only when a Fro Bot launcher started the server, so local and consumer use never sees `plugin.reuse-guard`) or `interrupted` (the turn was aborted while it ran).
68
70
  - `fro_bot.tool.offered`: `true` when the called name was in the tool list of the request that asked for the call, `false` when it was not. This covers OpenCode's two refusals (`Tool is not available for this request: <name>` and `No tool named "<name>" is currently available`) and a real tool that ran and failed. It is compared with the list the plugin captured when the request hook fired, not with the failure message. It is **left off** when the plugin cannot say: the call names no step, the step could not be matched to a request, an event was lost, the request's tool list was not captured or is incomplete (the snapshot left out an entry or cut the list at its bound), the provider ran the tool, or the tool's name is unknown. Unset means unknown, never `false`. The verdict is provisional until the request's step ends: a tool span that ends first is held (at most 256 at a time) until then, and exports **without** `offered` if the request turns uncertain (a loss), its execution ends, or the hold is full. The span itself always exports. A name that is not in the list but ran anyway (OpenCode runs a tool the request only offered inside Code Mode when it offered `execute`) is `false`.
69
- - `gen_ai.agent.name`: the agent the `execute.before` hook reported; else the agent of the request (or its step) that asked for the call, when that binding was certain; else the agent of the session that owns the call. A call refused before any hook still names its agent, and a session that switched agents does not blame the first one.
71
+ - `gen_ai.agent.name`: the agent the `execute.before` hook reported; else the agent of the request (or its step) that asked for the call, when that binding was certain, and stayed certain until the span exported; else the agent of the session that owns the call, and none when no agent is known. The request's agent is as provisional as `fro_bot.tool.offered`: the span is held for either, and a binding that turns uncertain (a loss), a request that closes unsettled or a full hold queue takes the request's agent away along with the verdict. A call refused before any hook still names its agent, and a session that switched agents does not blame the first one.
70
72
 
71
73
  **Joining a turn to its Action run.** The Action's launcher document (`OPENCODE_FROBOT_TRACING`) may carry four optional fields. The plugin accepts the document with or without them, refuses any other key, and turns tracing off, with a fixed reason and no value in the log line (`launcher-run-invalid`), when a field it carries is malformed:
72
74
 
package/dist/index.mjs CHANGED
@@ -1196,13 +1196,14 @@ function resolveTracingSettings(input) {
1196
1196
  */
1197
1197
  async function startTracing(host, settings, env, log) {
1198
1198
  try {
1199
- const handle = await (await import("./tracing-B58yZAvo.mjs")).startTracing({
1199
+ const handle = await (await import("./tracing-BeMbWlwI.mjs")).startTracing({
1200
1200
  session: host.session,
1201
1201
  tool: { hook: async (name, callback) => name === "execute.before" ? host.tool.hook(name, callback) : host.tool.hook(name, callback) },
1202
1202
  event: host.event
1203
1203
  }, settings, {
1204
1204
  env,
1205
1205
  log,
1206
+ directory: host.location.directory,
1206
1207
  ...typeof host.app?.version === "string" ? { opencodeVersion: host.app.version } : {}
1207
1208
  });
1208
1209
  return async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isRecord","isRecord","isRecord"],"sources":["../src/plugin-id.ts","../src/log.ts","../src/session-client.ts","../../../node_modules/@bfra.me/es/lib/chunk-XGJ2KYBN.js","../../runtime/src/session/storage-mappers-v2.ts","../../runtime/src/session/storage-message-mappers-v2.ts","../../runtime/src/shared/errors.ts","../../runtime/src/session/storage-v2.ts","../../runtime/src/session/search-v2.ts","../src/session-tools.ts","../src/task-reuse-guard.ts","../src/tracing/settings.ts","../src/setup.ts","../src/index.ts"],"sourcesContent":["/** Stable plugin id; the surfaces look it up in `GET /api/plugin` to confirm the plugin is active. */\nexport const FRO_BOT_PLUGIN_ID = 'fro-bot.opencode-plugin'\n","/**\n * The plugin's one log channel. `Plugin.Context` has no logger, and stdout carries the host's protocol in `serve --stdio`,\n * so a line goes to stderr, where the server's own diagnostics go. Never throws, and takes only fixed text: callers pass\n * no setting, header or error message.\n */\n\nimport process from 'node:process'\n\nexport function logPluginLine(message: string): void {\n try {\n process.stderr.write(`[fro-bot/opencode-plugin] ${message}\\n`)\n } catch {\n // A closed stderr must not fail the plugin.\n }\n}\n","/** Adapts the plugin context's `ctx.session` to the runtime's `SessionClientV2`. */\n\nimport type {SessionClientV2, SessionListQueryV2} from '@fro-bot/runtime/session-v2'\n\n/** The slice of `ctx.session` this package reads; method syntax so the branded `SessionID` parameter still fits. */\nexport interface PluginSessionApi {\n list: (query: SessionListQueryV2) => Promise<unknown>\n get: (input: {readonly sessionID: string}) => Promise<unknown>\n context: (input: {readonly sessionID: string}) => Promise<unknown>\n}\n\nconst SESSION_ID_PREFIX = 'ses'\nconst NOT_FOUND_TAG = 'Session.NotFoundError'\n\nexport function isSessionNotFound(error: unknown): boolean {\n return typeof error === 'object' && error !== null && Reflect.get(error, '_tag') === NOT_FOUND_TAG\n}\n\nexport function createPluginSessionClient(session: PluginSessionApi): SessionClientV2 {\n return {\n list: async query => session.list(query),\n async get(sessionID) {\n // The server rejects such an id with a SchemaError, which would read as an outage.\n if (!sessionID.startsWith(SESSION_ID_PREFIX)) return null\n try {\n return await session.get({sessionID})\n } catch (error) {\n if (isSessionNotFound(error)) return null\n throw error\n }\n },\n messages: async sessionID => session.context({sessionID}),\n }\n}\n","// src/result/factories.ts\nfunction ok(value) {\n return { success: true, data: value };\n}\nfunction err(error) {\n return { success: false, error };\n}\n\nexport {\n ok,\n err\n};\n//# sourceMappingURL=chunk-XGJ2KYBN.js.map","/** V2 sibling of `storage-mappers.ts`: parse raw V2 session payloads; every mapper takes `unknown` and never throws. */\n\nimport type {SessionInfoV2} from './types-v2.js'\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v != null\nexport const readString = (v: unknown): string | null => (typeof v === 'string' ? v : null)\nexport const readNumber = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\n/** Strips a `{data}` envelope. A bare payload passes through. */\nexport function unwrapData(v: unknown): unknown {\n return isRecord(v) && !Array.isArray(v) && 'data' in v ? v.data : v\n}\n\nexport function mapSessionInfoV2(v: unknown): SessionInfoV2 | null {\n const payload = unwrapData(v)\n if (!isRecord(payload) || Array.isArray(payload)) return null\n\n const id = readString(payload.id)\n const projectID = readString(payload.projectID)\n const time = payload.time\n const location = payload.location\n if (id == null || projectID == null || !isRecord(time) || !isRecord(location)) return null\n\n const created = readNumber(time.created)\n const updated = readNumber(time.updated)\n const directory = readString(location.directory)\n if (created == null || updated == null || directory == null) return null\n\n const parentID = readString(payload.parentID)\n const archived = readNumber(time.archived)\n return {\n id,\n projectID,\n directory,\n ...(parentID == null ? {} : {parentID}),\n title: readString(payload.title) ?? '',\n time: {created, updated, ...(archived == null ? {} : {archived})},\n }\n}\n\nexport interface SessionPageV2 {\n readonly sessions: readonly SessionInfoV2[]\n readonly nextCursor?: string\n}\n\n/**\n * Maps one page of sessions. Returns `null` when the payload is not list-shaped, so a protocol change is not mistaken\n * for \"no sessions\". Entries that fail to map are dropped.\n */\nexport function mapSessionPageV2(v: unknown): SessionPageV2 | null {\n const items = Array.isArray(v) ? v : isRecord(v) && Array.isArray(v.data) ? v.data : null\n if (items == null) return null\n\n const sessions: SessionInfoV2[] = []\n for (const item of items) {\n const mapped = mapSessionInfoV2(item)\n if (mapped != null) sessions.push(mapped)\n }\n\n const cursor = isRecord(v) ? v.cursor : undefined\n const nextCursor = isRecord(cursor) ? readString(cursor.next) : null\n return {sessions, ...(nextCursor == null || nextCursor.length === 0 ? {} : {nextCursor})}\n}\n","/** V2 sibling of `storage-message-mappers.ts`: flatten V2 session messages (user, synthetic, assistant, compaction). */\n\nimport type {MessageV2, PartV2, TodoItemV2} from './types-v2.js'\n\nimport {isRecord, readNumber, readString, unwrapData} from './storage-mappers-v2.js'\n\nconst TODO_TOOL = 'todowrite'\nconst TODO_STATUSES: readonly TodoItemV2['status'][] = ['pending', 'in_progress', 'completed', 'cancelled']\n\nfunction textPart(messageID: string, index: number, kind: PartV2['kind'], text: string): PartV2 {\n return {id: `${messageID}:${index}`, kind, text}\n}\n\n/** Joins the text items of a tool result. File items carry no searchable text. */\nfunction readToolText(content: unknown): string | null {\n if (!Array.isArray(content)) return null\n const texts = content.filter(isRecord).flatMap(item => {\n const text = item.type === 'text' ? readString(item.text) : null\n return text == null ? [] : [text]\n })\n return texts.length === 0 ? null : texts.join('\\n')\n}\n\nfunction readTodos(input: unknown): readonly TodoItemV2[] | null {\n if (!isRecord(input) || !Array.isArray(input.todos)) return null\n const todos: TodoItemV2[] = []\n for (const item of input.todos) {\n if (!isRecord(item)) continue\n const content = readString(item.content)\n if (content == null) continue\n const status = TODO_STATUSES.find(candidate => candidate === item.status)\n todos.push({content, status: status ?? 'pending'})\n }\n return todos\n}\n\nfunction mapAssistantContent(\n messageID: string,\n content: unknown,\n): {readonly parts: readonly PartV2[]; readonly todos?: readonly TodoItemV2[]} {\n if (!Array.isArray(content)) return {parts: []}\n\n const parts: PartV2[] = []\n let todos: readonly TodoItemV2[] | undefined\n for (const item of content) {\n if (!isRecord(item)) continue\n const index = parts.length\n if (item.type === 'text') {\n const text = readString(item.text)\n if (text != null) parts.push(textPart(messageID, index, 'text', text))\n } else if (item.type === 'reasoning') {\n const text = readString(item.text)\n if (text != null) parts.push(textPart(messageID, index, 'reasoning', text))\n } else if (item.type === 'tool' && isRecord(item.state) && item.state.status === 'completed') {\n const name = readString(item.name)\n const output = readToolText(item.state.content)\n if (name != null && output != null) parts.push(textPart(messageID, index, 'tool', `${name}: ${output}`))\n if (name === TODO_TOOL) todos = readTodos(item.state.input) ?? todos\n }\n }\n return {parts, ...(todos == null ? {} : {todos})}\n}\n\nfunction mapMessageV2(v: unknown): MessageV2 | null {\n if (!isRecord(v)) return null\n const id = readString(v.id)\n const time = v.time\n const createdAt = isRecord(time) ? readNumber(time.created) : null\n if (id == null || createdAt == null) return null\n\n if (v.type === 'user' || v.type === 'synthetic') {\n const text = readString(v.text)\n return {id, role: 'user', createdAt, parts: text == null ? [] : [textPart(id, 0, 'text', text)]}\n }\n if (v.type === 'assistant') {\n const agent = readString(v.agent)\n return {\n id,\n role: 'assistant',\n ...(agent == null ? {} : {agent}),\n createdAt,\n ...mapAssistantContent(id, v.content),\n }\n }\n // A completed compaction is the only record of what came before the active window, so keep its summary searchable.\n if (v.type === 'compaction' && v.status === 'completed') {\n const summary = readString(v.summary)\n return {id, role: 'assistant', createdAt, parts: summary == null ? [] : [textPart(id, 0, 'text', summary)]}\n }\n return null\n}\n\n/** Maps a message list oldest-first, or `null` when the payload is not list-shaped. */\nexport function mapMessagesV2(v: unknown): readonly MessageV2[] | null {\n const items = unwrapData(v)\n if (!Array.isArray(items)) return null\n\n const messages: MessageV2[] = []\n for (const item of items) {\n const mapped = mapMessageV2(item)\n if (mapped != null) messages.push(mapped)\n }\n return messages.toSorted((a, b) => a.createdAt - b.createdAt)\n}\n\n/** The todo list set by the most recent completed `todowrite` call, or an empty list. */\nexport function latestTodosV2(messages: readonly MessageV2[]): readonly TodoItemV2[] {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const todos = messages[index]?.todos\n if (todos != null) return todos\n }\n return []\n}\n","/**\n * Extract error message from unknown error.\n * @param error - Unknown value from catch block\n */\nexport function toErrorMessage(error: unknown): string {\n // A payload-owned coercion path (non-callable `toString`, a null prototype, or a throwing\n // getter) can make extraction itself throw; never let that escape an error-reporting helper.\n try {\n if (error instanceof Error) {\n return error.message\n }\n return String(error)\n } catch {\n return '[unprintable error]'\n }\n}\n\n/**\n * Wrap unknown error as Error instance.\n * @param error - Unknown value from catch block\n */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error\n }\n return new Error(toErrorMessage(error))\n}\n\n/** Longest string `formatSdkError` returns; longer messages and JSON are cut with a trailing `...`. */\nexport const SDK_ERROR_MAX_LENGTH = 500\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction bounded(text: string): string {\n return text.length > SDK_ERROR_MAX_LENGTH ? `${text.slice(0, SDK_ERROR_MAX_LENGTH - 3)}...` : text\n}\n\n/**\n * Describe the `error` of an OpenCode SDK result for a log line or an error message.\n *\n * The SDK client does not throw on an HTTP error; it returns `{error}` where `error` is the parsed response body:\n * a plain object for a JSON body (`{name: 'NotFoundError', data: {message}}`), a string for a text body. `String()`\n * of the object is `[object Object]`, which hides the cause.\n *\n * Picks, in order: `data.message`, `message`, `name`, `type`; an Error gives its message; a string is returned as\n * is. Any other object is serialised as JSON. The result is cut at `SDK_ERROR_MAX_LENGTH`. Only the value it is\n * given is read, so no request header or body can appear. Never throws: anything unreadable or unserialisable\n * (circular, BigInt, a throwing getter) is `[unprintable error]`.\n */\nexport function formatSdkError(error: unknown): string {\n try {\n if (typeof error !== 'object' || error === null || error instanceof Error) return bounded(toErrorMessage(error))\n\n const envelope = error as {\n readonly data?: unknown\n readonly message?: unknown\n readonly name?: unknown\n readonly type?: unknown\n }\n const data =\n typeof envelope.data === 'object' && envelope.data !== null\n ? (envelope.data as {readonly message?: unknown})\n : undefined\n const described =\n nonEmptyString(data?.message) ??\n nonEmptyString(envelope.message) ??\n nonEmptyString(envelope.name) ??\n nonEmptyString(envelope.type)\n return bounded(described ?? JSON.stringify(error))\n } catch {\n return '[unprintable error]'\n }\n}\n","/** V2 sibling of `storage.ts`: reads against a `SessionClientV2`, returning a `Result` so an outage is not \"no sessions\". */\n\nimport type {Result} from '@bfra.me/es/result'\nimport type {Logger} from '../shared/logger.js'\nimport type {SessionClientV2} from './backend-v2.js'\nimport type {MessageV2, SessionInfoV2, TodoItemV2} from './types-v2.js'\n\nimport {err, ok} from '@bfra.me/es/result'\nimport {toError} from '../shared/errors.js'\nimport {mapSessionInfoV2, mapSessionPageV2} from './storage-mappers-v2.js'\nimport {latestTodosV2, mapMessagesV2} from './storage-message-mappers-v2.js'\n\nconst SESSION_LIST_PAGE_SIZE = 100\n\n/** Upper bound on pages followed per listing: 10 pages of 100 sessions. */\nexport const SESSION_LIST_MAX_PAGES = 10\n\n/** Lists root, unarchived sessions created in `directory` (exact string match), newest first, up to a page bound. */\nexport async function listSessionsForDirectoryV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n return listRootSessionsV2(client, directory, logger, false)\n}\n\n/**\n * Root sessions in `directory` for retention: the unarchived ones AND the archived ones, each listed once. An archived\n * session (the context-overflow path archives the one it replaces) is out of every other listing by design, so it would\n * never age out; retention is the one reader that must see it. Both listings must succeed: pruning from half the\n * sessions would count the other half as absent.\n */\nexport async function listSessionsForPruningV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const live = await listRootSessionsV2(client, directory, logger, false)\n if (!live.success) return live\n const archived = await listRootSessionsV2(client, directory, logger, true)\n if (!archived.success) return archived\n const byId = new Map<string, SessionInfoV2>()\n for (const session of [...live.data, ...archived.data]) byId.set(session.id, session)\n return ok([...byId.values()])\n}\n\nasync function listRootSessionsV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n archivedOnly: boolean,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const sessions: SessionInfoV2[] = []\n let cursor: string | undefined\n\n for (let page = 0; page < SESSION_LIST_MAX_PAGES; page += 1) {\n let payload: unknown\n try {\n payload = await client.list({\n directory,\n limit: SESSION_LIST_PAGE_SIZE,\n order: 'desc',\n parentID: null,\n archived: archivedOnly,\n ...(cursor == null ? {} : {cursor}),\n })\n } catch (error) {\n logger.warning('V2 session list failed', {source: 'listSessionsForDirectoryV2', error: toError(error).message})\n return err(toError(error))\n }\n\n const parsed = mapSessionPageV2(payload)\n if (parsed == null) {\n logger.warning('V2 session list returned a payload that is not a session list', {\n source: 'listSessionsForDirectoryV2',\n type: typeof payload,\n })\n return err(new Error('session list response was not a session list'))\n }\n\n sessions.push(...parsed.sessions)\n // Stop on an empty page or a cursor that did not advance.\n if (parsed.sessions.length === 0 || parsed.nextCursor == null || parsed.nextCursor === cursor) break\n cursor = parsed.nextCursor\n }\n\n return ok(sessions)\n}\n\n/** Resolves to `ok(null)` when the session does not exist. */\nexport async function getSessionV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<SessionInfoV2 | null, Error>> {\n let payload: unknown\n try {\n payload = await client.get(sessionID)\n } catch (error) {\n logger.warning('V2 session get failed', {source: 'getSessionV2', error: toError(error).message})\n return err(toError(error))\n }\n\n if (payload == null) return ok(null)\n const session = mapSessionInfoV2(payload)\n if (session == null) {\n logger.warning('V2 session get returned an unparseable payload', {source: 'getSessionV2', type: typeof payload})\n return err(new Error('session response was not a session'))\n }\n return ok(session)\n}\n\nexport async function getSessionMessagesV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<readonly MessageV2[], Error>> {\n let payload: unknown\n try {\n payload = await client.messages(sessionID)\n } catch (error) {\n logger.warning('V2 session messages failed', {source: 'getSessionMessagesV2', error: toError(error).message})\n return err(toError(error))\n }\n\n const messages = mapMessagesV2(payload)\n if (messages == null) {\n logger.warning('V2 session messages returned a non-list payload', {\n source: 'getSessionMessagesV2',\n type: typeof payload,\n })\n return err(new Error('session messages response was not a message list'))\n }\n return ok(messages)\n}\n\n/** V2 has no todo endpoint; the list is whatever the last completed `todowrite` call in the readable messages set. */\nexport async function getSessionTodosV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<readonly TodoItemV2[], Error>> {\n const messages = await getSessionMessagesV2(client, sessionID, logger)\n return messages.success ? ok(latestTodosV2(messages.data)) : messages\n}\n","/** V2 sibling of `search.ts`: listing, content search (reads at most `SEARCH_MAX_SESSIONS` sessions) and summaries. */\n\nimport type {Result} from '@bfra.me/es/result'\nimport type {Logger} from '../shared/logger.js'\nimport type {SessionClientV2} from './backend-v2.js'\nimport type {MessageV2, SessionInfoV2, TodoItemV2} from './types-v2.js'\nimport type {SessionMatch, SessionSearchResult} from './types.js'\n\nimport {err, ok} from '@bfra.me/es/result'\nimport {latestTodosV2} from './storage-message-mappers-v2.js'\nimport {getSessionMessagesV2, getSessionV2, listSessionsForDirectoryV2} from './storage-v2.js'\n\n/** Most sessions one content search will read. */\nexport const SEARCH_MAX_SESSIONS = 100\n\nconst EXCERPT_CONTEXT_CHARS = 50\n\nexport async function listSessionsV2(\n client: SessionClientV2,\n directory: string,\n options: {readonly limit?: number; readonly fromDate?: Date; readonly toDate?: Date},\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const {limit, fromDate, toDate} = options\n logger.debug('Listing V2 sessions', {directory, limit})\n\n const listed = await listSessionsForDirectoryV2(client, directory, logger)\n if (!listed.success) return listed\n\n // Filter again in case the server ignores the root and unarchived query filters.\n const filtered = listed.data.filter(session => {\n if (session.parentID != null || session.time.archived != null) return false\n if (fromDate != null && session.time.created < fromDate.getTime()) return false\n if (toDate != null && session.time.created > toDate.getTime()) return false\n return true\n })\n\n const sorted = filtered.toSorted((a, b) => b.time.updated - a.time.updated)\n const limited = limit == null ? sorted : sorted.slice(0, limit)\n logger.info('Listed V2 sessions', {count: limited.length, directory})\n return ok(limited)\n}\n\nfunction uniqueAgents(messages: readonly MessageV2[]): readonly string[] {\n const agents = new Set<string>()\n for (const message of messages) {\n if (message.agent != null) agents.add(message.agent)\n }\n return [...agents]\n}\n\nfunction searchMessages(\n messages: readonly MessageV2[],\n pattern: string,\n caseSensitive: boolean,\n): readonly SessionMatch[] {\n const matches: SessionMatch[] = []\n for (const message of messages) {\n for (const part of message.parts) {\n const searchText = caseSensitive ? part.text : part.text.toLowerCase()\n const index = searchText.indexOf(pattern)\n if (index === -1) continue\n\n const start = Math.max(0, index - EXCERPT_CONTEXT_CHARS)\n const end = Math.min(part.text.length, index + pattern.length + EXCERPT_CONTEXT_CHARS)\n matches.push({\n messageId: message.id,\n partId: part.id,\n excerpt: `...${part.text.slice(start, end)}...`,\n role: message.role,\n ...(message.agent == null ? {} : {agent: message.agent}),\n })\n }\n }\n return matches\n}\n\nexport async function searchSessionsV2(\n query: string,\n client: SessionClientV2,\n directory: string,\n options: {\n readonly limit?: number\n readonly caseSensitive?: boolean\n readonly sessionId?: string\n readonly excludeSessionIds?: readonly string[]\n },\n logger: Logger,\n): Promise<Result<readonly SessionSearchResult[], Error>> {\n const {limit = 20, caseSensitive = false, sessionId, excludeSessionIds = []} = options\n const excluded = new Set(excludeSessionIds)\n const pattern = caseSensitive ? query : query.toLowerCase()\n logger.debug('Searching V2 sessions', {directory, limit, caseSensitive})\n\n if (sessionId != null) {\n if (excluded.has(sessionId)) return ok([])\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return messages\n const matches = searchMessages(messages.data, pattern, caseSensitive)\n return ok(matches.length === 0 ? [] : [{sessionId, matches: matches.slice(0, limit)}])\n }\n\n const listed = await listSessionsV2(client, directory, {}, logger)\n if (!listed.success) return listed\n\n const results: SessionSearchResult[] = []\n let totalMatches = 0\n let attempted = 0\n let succeeded = 0\n let firstReadError: Error | undefined\n for (const session of listed.data.filter(s => !excluded.has(s.id)).slice(0, SEARCH_MAX_SESSIONS)) {\n if (totalMatches >= limit) break\n\n attempted += 1\n const messages = await getSessionMessagesV2(client, session.id, logger)\n if (!messages.success) {\n // already logged; one unreadable session must not sink the whole search\n firstReadError ??= messages.error\n continue\n }\n succeeded += 1\n\n const matches = searchMessages(messages.data, pattern, caseSensitive)\n if (matches.length === 0) continue\n const kept = matches.slice(0, limit - totalMatches)\n results.push({sessionId: session.id, matches: kept})\n totalMatches += kept.length\n }\n\n // Nothing was searched: \"no matches\" would be a lie.\n if (attempted > 0 && succeeded === 0 && firstReadError != null) {\n return err(new Error(`could not read any of ${attempted} sessions: ${firstReadError.message}`))\n }\n\n logger.info('V2 session search complete', {resultCount: results.length, totalMatches})\n return ok(results)\n}\n\nexport interface SessionDetailsV2 {\n readonly session: SessionInfoV2\n readonly messageCount: number\n readonly agents: readonly string[]\n readonly hasTodos: boolean\n readonly todoCount: number\n readonly completedTodos: number\n}\n\n/** Resolves to `ok(null)` when the session does not exist. */\nexport async function getSessionInfoV2(\n client: SessionClientV2,\n sessionId: string,\n logger: Logger,\n): Promise<Result<SessionDetailsV2 | null, Error>> {\n const session = await getSessionV2(client, sessionId, logger)\n if (!session.success) return session\n if (session.data == null) return ok(null)\n\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return err(messages.error)\n\n const todos: readonly TodoItemV2[] = latestTodosV2(messages.data)\n return ok({\n session: session.data,\n messageCount: messages.data.length,\n agents: uniqueAgents(messages.data),\n hasTodos: todos.length > 0,\n todoCount: todos.length,\n completedTodos: todos.filter(todo => todo.status === 'completed').length,\n })\n}\n","/**\n * The session tools `session_list`, `session_read`, `session_search` and `session_info` on the V2 session API.\n *\n * Transcripts and search read the session's active context window (messages since the last compaction, with its summary\n * standing in for older ones); todos are the list the last `todowrite` call in that window set.\n *\n * `run()` never throws: every failure returns `session store unavailable: <reason>`, one line and length-capped.\n */\n\nimport type {MessageV2, SessionClientV2, SessionInfoV2} from '@fro-bot/runtime/session-v2'\n\nimport {\n getSessionInfoV2,\n getSessionMessagesV2,\n getSessionV2,\n latestTodosV2,\n listSessionsV2,\n searchSessionsV2,\n} from '@fro-bot/runtime/session-v2'\nimport {Schema, SchemaTransformation} from 'effect'\n\nconst UNAVAILABLE_PREFIX = 'session store unavailable'\nconst REASON_MAX_CHARS = 200\n\nexport const TRANSCRIPT_CHAR_CAP = 48_000\n\nexport const SESSION_TOOL_NAMES = {\n list: 'session_list',\n read: 'session_read',\n search: 'session_search',\n info: 'session_info',\n} as const\n\n/** No-op logger: plugins have no logging channel. */\nconst silentLogger = {\n debug: (): void => {},\n info: (): void => {},\n warning: (): void => {},\n error: (): void => {},\n}\n\nexport interface SessionToolSpec<Input extends Schema.Top = Schema.Top> {\n readonly name: string\n readonly description: string\n readonly input: Input\n /** Takes the decoded tool input, defensively re-checked; never throws. */\n readonly run: (args: Readonly<Record<string, unknown>>) => Promise<string>\n}\n\nexport interface SessionToolSet {\n readonly list: SessionToolSpec<typeof ListInput>\n readonly read: SessionToolSpec<typeof ReadInput>\n readonly search: SessionToolSpec<typeof SearchInput>\n readonly info: SessionToolSpec<typeof InfoInput>\n}\n\nfunction unavailable(reason: string): string {\n return `${UNAVAILABLE_PREFIX}: ${reason}`\n}\n\n/** One line, capped. Effect tagged errors can have an empty message, so fall back to the tag. */\nfunction describeFailure(error: unknown): string {\n let raw: string\n if (error instanceof Error) {\n const tag: unknown = Reflect.get(error, '_tag')\n raw = error.message.length > 0 ? error.message : typeof tag === 'string' ? tag : error.name\n } else {\n raw = typeof error === 'string' ? error : 'unknown error'\n }\n const firstLine = raw.split('\\n')[0] ?? ''\n return firstLine.length > REASON_MAX_CHARS ? `${firstLine.slice(0, REASON_MAX_CHARS)}...` : firstLine\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined\n}\n\nfunction parseDate(value: string | undefined): Date | undefined {\n if (value == null) return undefined\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? undefined : parsed\n}\n\n/** Parses a `to_date` bound to the END of that day (inclusive upper bound). */\nfunction parseEndOfDayDate(value: string | undefined): Date | undefined {\n const parsed = parseDate(value)\n if (parsed == null) return undefined\n const endOfDay = new Date(parsed)\n endOfDay.setUTCHours(23, 59, 59, 999)\n return endOfDay\n}\n\n/** Any limit below 1 (including negative values) means \"no limit\"; a fractional limit is floored. */\nfunction normalizeLimit(value: number | undefined): number | undefined {\n return value == null || value < 1 ? undefined : Math.floor(value)\n}\n\nfunction formatTimestamp(ms: number): string {\n return new Date(ms).toISOString()\n}\n\nfunction titleOf(session: SessionInfoV2): string {\n return session.title.length > 0 ? session.title : '(untitled)'\n}\n\nfunction formatMessageForTranscript(message: MessageV2): string {\n const text = message.parts.map(part => part.text).join(' ')\n return text.length > 0 ? `[${message.role}] ${text}` : `[${message.role}] (no content)`\n}\n\n/** Renders messages oldest-first, capping total rendered size so a huge transcript can't blow the response. */\nfunction renderTranscript(messages: readonly MessageV2[]): string[] {\n const lines: string[] = []\n let size = 0\n let shown = 0\n\n for (const message of messages) {\n const line = ` ${formatMessageForTranscript(message)}`\n if (size + line.length > TRANSCRIPT_CHAR_CAP) break\n lines.push(line)\n size += line.length\n shown += 1\n }\n\n if (shown < messages.length) {\n lines.push(` ... transcript truncated (${shown} of ${messages.length} messages shown)`)\n }\n return lines\n}\n\nfunction sessionHeader(session: SessionInfoV2): string[] {\n return [\n `Session ${session.id}`,\n `Title: ${titleOf(session)}`,\n `Created: ${formatTimestamp(session.time.created)}`,\n `Updated: ${formatTimestamp(session.time.updated)}`,\n ]\n}\n\nconst CONTEXT_WINDOW_NOTE =\n \"Covers the session's active context window: messages since its last compaction, plus the compaction summary.\"\n\n/**\n * Models often send `limit` as a string (\"15\"), and OpenCode validates tool arguments with Effect Schema before the\n * handler runs, so a plain `Schema.Number` rejects it. Accept a number or a plain decimal string and DECODE it to a\n * number here: the handler's `asNumber` ignores strings, so a merely widened schema would run the read uncapped.\n * Blank, malformed (hex, trailing junk) and non-finite strings stay schema errors.\n *\n * The `u` flag and no `i` flag are deliberate: Effect exports a regex's JSON Schema `pattern` only for flags in\n * `/^[dg]*uy?$/`, and otherwise publishes the string branch as accepting anything.\n */\n// eslint-disable-next-line regexp/use-ignore-case -- the `i` flag would drop the exported JSON Schema `pattern`\nconst DECIMAL_STRING = /^\\s*[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*$/u\n\nconst LimitInput = Schema.Union([\n Schema.Number,\n Schema.String.check(Schema.isPattern(DECIMAL_STRING)).pipe(\n Schema.decodeTo(Schema.Finite, SchemaTransformation.numberFromString),\n ),\n])\n\nconst ListInput = Schema.Struct({\n limit: Schema.optionalKey(LimitInput).annotate({description: 'Maximum number of sessions to return.'}),\n from_date: Schema.optionalKey(Schema.String).annotate({\n description: 'Only include sessions created on or after this date (YYYY-MM-DD).',\n }),\n to_date: Schema.optionalKey(Schema.String).annotate({\n description: 'Only include sessions created on or before this date (YYYY-MM-DD).',\n }),\n project_path: Schema.optionalKey(Schema.String).annotate({\n description: 'Workspace/project directory to list sessions for.',\n }),\n})\n\nconst ReadInput = Schema.Struct({\n session_id: Schema.String.annotate({description: 'The session id to read (required).'}),\n include_todos: Schema.optionalKey(Schema.Boolean).annotate({description: 'Include the session todo list.'}),\n include_transcript: Schema.optionalKey(Schema.Boolean).annotate({description: 'Include the message transcript.'}),\n limit: Schema.optionalKey(LimitInput).annotate({\n description: 'Maximum number of transcript messages to include.',\n }),\n})\n\nconst SearchInput = Schema.Struct({\n query: Schema.String.annotate({description: 'Text to search for (required).'}),\n session_id: Schema.optionalKey(Schema.String).annotate({description: 'Restrict the search to a single session id.'}),\n case_sensitive: Schema.optionalKey(Schema.Boolean).annotate({description: 'Match case-sensitively.'}),\n limit: Schema.optionalKey(LimitInput).annotate({description: 'Maximum number of matches to return.'}),\n})\n\nconst InfoInput = Schema.Struct({\n session_id: Schema.String.annotate({description: 'The session id to summarize (required).'}),\n})\n\n/**\n * Builds the four tool definitions against an injected client. `directory` is the workspace the tools default to:\n * `session_list` honours a `project_path` override, `session_search` always searches the workspace.\n */\nexport function createSessionTools(options: {\n readonly client: SessionClientV2\n readonly directory: string\n}): SessionToolSet {\n const {client, directory} = options\n const logger = silentLogger\n\n const list: SessionToolSpec<typeof ListInput> = {\n name: SESSION_TOOL_NAMES.list,\n description: 'List recent OpenCode sessions for the current workspace, most recently updated first.',\n input: ListInput,\n async run(args) {\n try {\n const sessions = await listSessionsV2(\n client,\n asString(args.project_path) ?? directory,\n {\n limit: normalizeLimit(asNumber(args.limit)),\n fromDate: parseDate(asString(args.from_date)),\n toDate: parseEndOfDayDate(asString(args.to_date)),\n },\n logger,\n )\n if (!sessions.success) return unavailable(describeFailure(sessions.error))\n if (sessions.data.length === 0) return 'No sessions found.'\n\n return sessions.data\n .map(session => `${session.id} ${titleOf(session)} updated ${formatTimestamp(session.time.updated)}`)\n .join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const read: SessionToolSpec<typeof ReadInput> = {\n name: SESSION_TOOL_NAMES.read,\n description: `Read a session: header, optional todos, and optional transcript. ${CONTEXT_WINDOW_NOTE}`,\n input: ReadInput,\n async run(args) {\n const sessionId = asString(args.session_id)\n if (sessionId == null) return unavailable('session_id is required')\n\n try {\n const found = await getSessionV2(client, sessionId, logger)\n if (!found.success) return unavailable(describeFailure(found.error))\n if (found.data == null) return `session not found: ${sessionId}`\n\n const lines = sessionHeader(found.data)\n\n const includeTodos = asBoolean(args.include_todos) === true\n const includeTranscript = asBoolean(args.include_transcript) === true\n if (!includeTodos && !includeTranscript) return lines.join('\\n')\n\n // One snapshot of the active context feeds both sections.\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return unavailable(describeFailure(messages.error))\n\n if (includeTodos) {\n const todos = latestTodosV2(messages.data)\n lines.push('', 'Todos:')\n if (todos.length === 0) {\n lines.push(' (none)')\n } else {\n for (const todo of todos) lines.push(` [${todo.status}] ${todo.content}`)\n }\n }\n\n if (includeTranscript) {\n // Oldest-first; a limit returns the earliest N messages.\n const limit = normalizeLimit(asNumber(args.limit))\n const sliced = limit == null ? messages.data : messages.data.slice(0, limit)\n lines.push('', 'Transcript:')\n if (sliced.length === 0) {\n lines.push(' (empty)')\n } else {\n lines.push(...renderTranscript(sliced))\n }\n }\n\n return lines.join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const search: SessionToolSpec<typeof SearchInput> = {\n name: SESSION_TOOL_NAMES.search,\n description: `Search prior session content for matching text, optionally scoped to one session. ${CONTEXT_WINDOW_NOTE}`,\n input: SearchInput,\n async run(args) {\n const query = asString(args.query)\n if (query == null) return unavailable('query is required')\n\n try {\n const scopedSessionId = asString(args.session_id)\n if (scopedSessionId != null) {\n const found = await getSessionV2(client, scopedSessionId, logger)\n if (!found.success) return unavailable(describeFailure(found.error))\n if (found.data == null) return `session not found: ${scopedSessionId}`\n }\n\n // Search always scopes to the current workspace; there is no project_path.\n const results = await searchSessionsV2(\n query,\n client,\n directory,\n {\n limit: normalizeLimit(asNumber(args.limit)),\n caseSensitive: asBoolean(args.case_sensitive),\n sessionId: scopedSessionId,\n },\n logger,\n )\n if (!results.success) return unavailable(describeFailure(results.error))\n if (results.data.length === 0) return 'No matches found.'\n\n const lines: string[] = []\n for (const result of results.data) {\n lines.push(`Session ${result.sessionId}:`)\n for (const match of result.matches) {\n lines.push(` [${match.role}${match.agent == null ? '' : `/${match.agent}`}] ${match.excerpt}`)\n }\n }\n return lines.join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const info: SessionToolSpec<typeof InfoInput> = {\n name: SESSION_TOOL_NAMES.info,\n description: `Summarize a session: id, title, timestamps, message and todo counts. ${CONTEXT_WINDOW_NOTE}`,\n input: InfoInput,\n async run(args) {\n const sessionId = asString(args.session_id)\n if (sessionId == null) return unavailable('session_id is required')\n\n try {\n const details = await getSessionInfoV2(client, sessionId, logger)\n if (!details.success) return unavailable(describeFailure(details.error))\n if (details.data == null) return `session not found: ${sessionId}`\n\n const {session, messageCount, agents, hasTodos, todoCount, completedTodos} = details.data\n return [\n ...sessionHeader(session),\n `Messages: ${messageCount}`,\n `Agents: ${agents.length > 0 ? agents.join(', ') : '(none)'}`,\n `Todos: ${hasTodos ? `${completedTodos}/${todoCount} completed` : '(none)'}`,\n ].join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n return {list, read, search, info}\n}\n","/**\n * Guards `subagent` calls that resume a child session via `sessionID`, through the `execute.before` and `execute.after`\n * tool hooks. A resume is refused unless the plugin itself saw this caller dispatch that child in this run, and the\n * server was started by the Action. Everything else gets one fixed refusal.\n */\n\n/** The model-visible rejection text; it carries no ids or arguments. */\nexport const TASK_REUSE_REJECTION =\n 'Session reuse is disabled in this environment. Start a new task and include the context it needs.'\n\n/** The one tool the guard covers: a direct tool, never inside Code Mode. */\nexport const GUARDED_TOOL = 'subagent'\n\n/** How many dispatched children one guard remembers. The oldest is forgotten first, which refuses its resume. */\nexport const DEFAULT_MAX_RECORDED_CHILDREN = 1024\n\n/** The slice of the host's `execute.before` event the guard reads. `sessionID` is the calling session, host-supplied. */\nexport interface ToolCallBefore {\n readonly tool: string\n readonly input: unknown\n readonly sessionID?: string | undefined\n}\n\nexport interface SubagentResumeGuardOptions {\n /** True only when the server's launcher names the Action as its host. Any other host refuses every resume. */\n readonly actionHost: boolean\n /** Bound on remembered children. Anything that is not a positive integer uses the default. */\n readonly maxRecordedChildren?: number | undefined\n}\n\nexport interface SubagentResumeGuard {\n /** Throws the fixed refusal for a `subagent` resume that is not admitted; otherwise returns. */\n readonly before: (event: ToolCallBefore) => void\n /** Records the child of a successful fresh `subagent` dispatch. Never throws, whatever it is handed. */\n readonly after: (event: unknown) => void\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/** A resume is any `sessionID` other than absent, null or `\"\"` (upstream treats `\"\"` as absent); malformed values reject. */\nfunction resumeTarget(input: unknown): {readonly resume: false} | {readonly resume: true; readonly sessionID: unknown} {\n if (!isRecord(input)) return {resume: false}\n const sessionID: unknown = input.sessionID\n if (sessionID === undefined || sessionID === null || sessionID === '') return {resume: false}\n return {resume: true, sessionID}\n}\n\n/**\n * The caller and child of a successful fresh `subagent` dispatch, or `undefined` for anything else. Shapes, as of\n * OpenCode v2.4.1 (`packages/plugin/src/promise/tool.ts` `ToolHooks['execute.after']`, built in `packages/core/src/tool.ts`\n * `executeTool`): the event is `{tool, sessionID, input, id, …}` plus `{status: 'completed', result}` or\n * `{status: 'error', error}`. The `subagent` tool (`packages/core/src/tool/plugin/subagent.ts`) returns\n * `{output: {sessionID, status: 'running', output}, content, metadata: {sessionID, status}}`, and `result` carries those\n * as they are. The caller is the event's own `sessionID`, set by the host; nothing the model wrote names it.\n */\nfunction parseDispatch(event: unknown): {readonly caller: string; readonly child: string} | undefined {\n if (!isRecord(event) || event.tool !== GUARDED_TOOL || event.status !== 'completed') return undefined\n // A call that carried a sessionID was a resume (or a forged event): it creates no child, so it records nothing.\n if (!isRecord(event.input) || resumeTarget(event.input).resume) return undefined\n const caller = nonEmptyString(event.sessionID)\n if (caller === undefined || !isRecord(event.result)) return undefined\n\n const {metadata, output} = event.result\n const fromMetadata = isRecord(metadata) ? metadata.sessionID : undefined\n const fromOutput = isRecord(output) ? output.sessionID : undefined\n // The two name one child. When both are present and differ, neither is trusted.\n if (fromMetadata !== undefined && fromOutput !== undefined && fromMetadata !== fromOutput) return undefined\n const child = nonEmptyString(fromMetadata ?? fromOutput)\n return child === undefined ? undefined : {caller, child}\n}\n\nexport function createSubagentResumeGuard(options: SubagentResumeGuardOptions): SubagentResumeGuard {\n const {actionHost, maxRecordedChildren} = options\n const bound =\n maxRecordedChildren !== undefined && Number.isInteger(maxRecordedChildren) && maxRecordedChildren > 0\n ? maxRecordedChildren\n : DEFAULT_MAX_RECORDED_CHILDREN\n /** Child session id to the session that dispatched it. A Map iterates in insertion order, so the first key is oldest. */\n const children = new Map<string, string>()\n\n return {\n before(event) {\n if (event.tool !== GUARDED_TOOL) return\n const target = resumeTarget(event.input)\n if (!target.resume) return\n const caller = nonEmptyString(event.sessionID)\n const admitted =\n actionHost &&\n caller !== undefined &&\n typeof target.sessionID === 'string' &&\n children.get(target.sessionID) === caller\n if (!admitted) throw new Error(TASK_REUSE_REJECTION)\n },\n after(event) {\n const dispatch = parseDispatch(event)\n if (dispatch === undefined) return\n // Re-recording moves the child to the newest slot.\n children.delete(dispatch.child)\n children.set(dispatch.child, dispatch.caller)\n while (children.size > bound) {\n const oldest = children.keys().next()\n if (oldest.done === true) break\n children.delete(oldest.value)\n }\n },\n }\n}\n","/**\n * Host mode and tracing settings: one function decides whether tracing is on and where spans go, and fails closed.\n *\n * This module sits OUTSIDE the lazy tracing chunk: it decides whether the chunk loads at all, so it must stay small and\n * import nothing from the OpenTelemetry SDK. Resolving to off never evaluates the chunk.\n *\n * Where settings come from, and nowhere else:\n * - The launcher variable `OPENCODE_FROBOT_TRACING`, set by whatever started the server (the Action, the workspace).\n * - Otherwise, only in a local session, a user-scope file under the user's config directory.\n * Plugin options, project config, the checkout, restored state and session content are never read.\n *\n * The user file names the machines it is for (`hosts`, required): a file synced to another machine, or left behind on a\n * shared one, does nothing there. And a remote collector in it must be `https`, with the platform's certificate\n * verification left on: the exporter sends the file's headers (a credential) to that URL, and the file has no switch to\n * relax verification, to follow a redirect, or to use plain `http` anywhere but a loopback literal.\n */\n\nimport {Buffer} from 'node:buffer'\nimport {closeSync, constants, fstatSync, openSync, readSync, realpathSync} from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\n/**\n * Name of the launcher variable. `OPENCODE_`-prefixed so the Action's environment filter admits it, and not ending in a\n * denied suffix (`_TOKEN`, `_KEY`, `_SECRET`, `_PASSWORD`, …). It carries no credential: only host, on/off, a loopback\n * relay address and run identity.\n */\nexport const TRACING_LAUNCHER_ENV = 'OPENCODE_FROBOT_TRACING'\n\n/** Version of both the launcher document and the user file. Anything else resolves to off. */\nexport const TRACING_SETTINGS_VERSION = 1\n\n/** Variables a headless server (the Action, the workspace, any `opencode serve`) always has and a local session lacks. */\nexport const HEADLESS_MARKERS = ['OPENCODE_PASSWORD', 'OPENCODE_CONFIG_CONTENT'] as const\n\n/** The user file, relative to the user's config directory. Not under `opencode/`: OpenCode reads nothing from here. */\nexport const USER_SETTINGS_RELATIVE_PATH = path.join('fro-bot', 'opencode-plugin', 'tracing.json')\n\n/** Ceilings. A document or file over its ceiling is malformed, not truncated. */\nexport const MAX_LAUNCHER_CHARS = 4096\nexport const MAX_SETTINGS_FILE_BYTES = 16 * 1024\nexport const MAX_ENDPOINT_CHARS = 2048\nexport const MAX_HEADERS = 16\nexport const MAX_HEADER_VALUE_CHARS = 4096\nexport const MAX_HOSTS = 16\n/** The longest name DNS allows. */\nexport const MAX_HOSTNAME_CHARS = 253\nexport const MAX_IDENTITY_FIELD_CHARS = 200\n\n/** Run identity the Action supplies. Every span of an Action run carries it. */\nexport interface ActionIdentity {\n readonly repository: string\n readonly runId: string\n readonly attempt: string\n readonly job: string\n readonly trigger: string\n}\n\n/** The Action run's root span, which each turn's root span links to. Both ids are lower-case hex, not all zero. */\nexport interface RootSpanContext {\n readonly traceId: string\n readonly spanId: string\n}\n\n/**\n * What ties a turn trace to the Action run that started it. All three come from the launcher, each is optional, and none is\n * derived or altered here: `sessionId` (the Action's `<owner>/<repo>:<logical key>`) is used verbatim.\n */\nexport interface ActionRunContext {\n readonly rootSpan?: RootSpanContext | undefined\n readonly sessionId?: string | undefined\n readonly invocationId?: string | undefined\n /**\n * The GitHub server the run is on (`GITHUB_SERVER_URL`): an `https` origin with no path, query, fragment or credentials. The\n * run's URL is built from it. A launcher written before the field existed does not carry it, and reads as it always has.\n */\n readonly serverUrl?: string | undefined\n}\n\n/**\n * Why tracing is off. Fixed strings: they are the only thing a log line says about a refused setting. The first group is\n * a deliberate off and stays silent; the rest are logged once.\n */\nexport type OffReason =\n | 'action-off'\n | 'workspace-host'\n | 'unsupported-platform'\n | 'no-settings-file'\n | 'machine-not-listed'\n | 'launcher-malformed'\n | 'launcher-unsupported'\n | 'launcher-relay-invalid'\n | 'launcher-identity-invalid'\n | 'launcher-run-invalid'\n | 'headless-host'\n | 'settings-file-unreadable'\n | 'settings-file-unsafe'\n | 'settings-file-invalid'\n | 'settings-error'\n\nconst SILENT_REASONS: ReadonlySet<OffReason> = new Set([\n 'action-off',\n 'workspace-host',\n 'unsupported-platform',\n 'no-settings-file',\n 'machine-not-listed',\n])\n\nexport type TracingSettings =\n | {readonly mode: 'off'; readonly reason: OffReason}\n | ({\n readonly mode: 'on'\n readonly host: 'action'\n /** The relay's loopback traces URL. The collector credential never reaches the plugin. */\n readonly endpoint: string\n readonly identity: ActionIdentity\n } & ActionRunContext)\n | {\n readonly mode: 'on'\n readonly host: 'local'\n readonly endpoint: string\n readonly headers: Readonly<Record<string, string>>\n }\n\nexport interface ResolveTracingSettingsInput {\n readonly env: Readonly<Record<string, string | undefined>>\n /** The session's project directory: a settings file that resolves inside it is refused. */\n readonly directory: string\n readonly log: (line: string) => void\n /** Defaults to the running platform. */\n readonly platform?: NodeJS.Platform\n /** The current user's id. Defaults to `process.getuid()`. */\n readonly uid?: number | undefined\n /** The machine's name. Defaults to `os.hostname()`. Read only for a local session with a valid user file. */\n readonly hostname?: (() => string) | undefined\n}\n\nconst off = (reason: OffReason): TracingSettings => ({mode: 'off', reason})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** True when `value` has exactly the listed keys, no more and no fewer. */\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return hasKeys(value, keys, [])\n}\n\n/** True when `value` has every required key and no key outside `required` and `optional`. */\nfunction hasKeys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[]): boolean {\n return (\n required.every(key => Object.hasOwn(value, key)) &&\n Object.keys(value).every(key => required.includes(key) || optional.includes(key))\n )\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\n/** `127.0.0.0/8` literals or `[::1]`. A hostname such as `localhost` is not accepted: it resolves through the host. */\nfunction isLoopbackHostname(hostname: string): boolean {\n if (hostname === '[::1]') return true\n const octets = hostname.split('.')\n return (\n octets.length === 4 && octets[0] === '127' && octets.every(octet => /^\\d{1,3}$/.test(octet) && Number(octet) <= 255)\n )\n}\n\nfunction parseUrl(value: unknown): URL | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_ENDPOINT_CHARS) return undefined\n if (hasControlCharacter(value)) return undefined\n try {\n const url = new URL(value)\n // Credentials in a URL would be logged by anything that prints it.\n if (url.username !== '' || url.password !== '' || url.hash !== '') return undefined\n return url\n } catch {\n return undefined\n }\n}\n\n/** The launcher's relay: plain HTTP to a loopback literal with an explicit port. */\nfunction parseRelayUrl(value: unknown): string | undefined {\n const url = parseUrl(value)\n if (url === undefined || url.protocol !== 'http:' || !isLoopbackHostname(url.hostname) || url.port === '') {\n return undefined\n }\n if (url.search !== '') return undefined\n return url.href\n}\n\n/** A user-file endpoint: HTTPS, or plain HTTP to a loopback literal. */\nfunction parseCollectorUrl(value: unknown): URL | undefined {\n const url = parseUrl(value)\n if (url === undefined) return undefined\n if (url.protocol === 'https:') return url\n if (url.protocol === 'http:' && isLoopbackHostname(url.hostname)) return url\n return undefined\n}\n\nfunction parseIdentity(value: unknown): ActionIdentity | undefined {\n if (!isRecord(value) || !hasExactKeys(value, ['repository', 'runId', 'attempt', 'job', 'trigger'])) return undefined\n const fields: string[] = []\n for (const key of ['repository', 'runId', 'attempt', 'job', 'trigger']) {\n const field = value[key]\n if (typeof field !== 'string' || field.length === 0 || field.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n if (hasControlCharacter(field)) return undefined\n fields.push(field)\n }\n const [repository = '', runId = '', attempt = '', job = '', trigger = ''] = fields\n return {repository, runId, attempt, job, trigger}\n}\n\nconst TRACE_ID = /^[\\da-f]{32}$/\nconst SPAN_ID = /^[\\da-f]{16}$/\nconst NON_ZERO = /[1-9a-f]/\n\n/** 32 and 16 lower-case hex characters, neither all zero: what W3C trace context accepts as ids. */\nfunction parseRootSpan(value: unknown): RootSpanContext | undefined {\n if (!isRecord(value) || !hasExactKeys(value, ['traceId', 'spanId'])) return undefined\n const {traceId, spanId} = value\n if (typeof traceId !== 'string' || typeof spanId !== 'string') return undefined\n if (!TRACE_ID.test(traceId) || !SPAN_ID.test(spanId) || !NON_ZERO.test(traceId) || !NON_ZERO.test(spanId)) {\n return undefined\n }\n return {traceId, spanId}\n}\n\n/** A non-empty string, at most as long as an identity field, free of control characters. */\nfunction parseTextField(value: unknown): string | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n return hasControlCharacter(value) ? undefined : value\n}\n\n/**\n * A GitHub server origin: exactly `https://<host>[:<port>]`, optionally with one trailing slash, no more. The text must be\n * what the URL parser would write back, so nothing is rewritten or discarded on the way (a path, a query, a fragment,\n * credentials, an upper-case host, a default port, a non-ASCII host all fail). Bounded like an identity field.\n */\nfunction parseServerUrl(value: unknown): string | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n if (hasControlCharacter(value)) return undefined\n let url: URL\n try {\n url = new URL(value)\n } catch {\n return undefined\n }\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') return undefined\n if (value !== url.origin && value !== `${url.origin}/`) return undefined\n return url.origin\n}\n\n/** The launcher's optional run link fields. A field that is present and not acceptable refuses them all: `undefined`. */\nfunction parseRunContext(document: Record<string, unknown>): ActionRunContext | undefined {\n const context: {rootSpan?: RootSpanContext; sessionId?: string; invocationId?: string; serverUrl?: string} = {}\n if (Object.hasOwn(document, 'rootSpan')) {\n const rootSpan = parseRootSpan(document.rootSpan)\n if (rootSpan === undefined) return undefined\n context.rootSpan = rootSpan\n }\n if (Object.hasOwn(document, 'sessionId')) {\n const sessionId = parseTextField(document.sessionId)\n if (sessionId === undefined) return undefined\n context.sessionId = sessionId\n }\n if (Object.hasOwn(document, 'invocationId')) {\n const invocationId = parseTextField(document.invocationId)\n if (invocationId === undefined) return undefined\n context.invocationId = invocationId\n }\n if (Object.hasOwn(document, 'serverUrl')) {\n const serverUrl = parseServerUrl(document.serverUrl)\n if (serverUrl === undefined) return undefined\n context.serverUrl = serverUrl\n }\n return context\n}\n\n/** Resolves the launcher variable's value. Pure: no environment, no file. */\nfunction resolveLauncher(raw: string): TracingSettings {\n if (raw.length === 0 || raw.length > MAX_LAUNCHER_CHARS) return off('launcher-malformed')\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch {\n return off('launcher-malformed')\n }\n if (!isRecord(document)) return off('launcher-malformed')\n if (document.version !== TRACING_SETTINGS_VERSION) return off('launcher-unsupported')\n if (document.host === 'workspace') return off('workspace-host')\n if (document.host !== 'action') return off('launcher-unsupported')\n if (document.tracing === 'off') return off('action-off')\n if (document.tracing !== 'on') return off('launcher-malformed')\n if (\n !hasKeys(\n document,\n ['version', 'host', 'tracing', 'relay', 'identity'],\n ['rootSpan', 'sessionId', 'invocationId', 'serverUrl'],\n )\n ) {\n return off('launcher-malformed')\n }\n\n const endpoint = parseRelayUrl(document.relay)\n if (endpoint === undefined) return off('launcher-relay-invalid')\n const identity = parseIdentity(document.identity)\n if (identity === undefined) return off('launcher-identity-invalid')\n const run = parseRunContext(document)\n if (run === undefined) return off('launcher-run-invalid')\n return {mode: 'on', host: 'action', endpoint, identity, ...run}\n}\n\n/**\n * Whether the launcher variable names the Action as the host that started this server. Strict and independent of tracing:\n * only a present, size-capped, valid JSON object with `version` 1 and `host` `'action'` answers `'action'`. The tracing\n * mode, relay and identity fields are not read, so an Action run with tracing off, or with a field the tracing decision\n * would refuse, is still the Action. Anything else (no variable, a malformed or oversized one, an unknown version, the\n * workspace or any other host) answers `undefined`. A user file and the headless markers never name the Action: only the\n * Action's own launcher does. Pure and never throws; it logs nothing.\n */\nexport function readLauncherHost(env: Readonly<Record<string, string | undefined>>): 'action' | undefined {\n const raw = env[TRACING_LAUNCHER_ENV]\n if (raw === undefined || raw.length === 0 || raw.length > MAX_LAUNCHER_CHARS) return undefined\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (!isRecord(document) || document.version !== TRACING_SETTINGS_VERSION) return undefined\n return document.host === 'action' ? 'action' : undefined\n}\n\n/**\n * Whether a Fro Bot launcher started this server, for the subagent resume guard: `'none'` when the launcher variable is\n * absent (a workstation, the TUI, `opencode run`, any consumer), `'action'` when it names the Action (see\n * `readLauncherHost`), and `'other'` for any variable that is present but does not: the workspace, an unknown host, or a\n * malformed document. Presence alone means a Fro Bot launcher, so a present but unreadable variable stays fail-closed.\n * Pure and never throws.\n */\nexport function readLauncherKind(env: Readonly<Record<string, string | undefined>>): 'action' | 'other' | 'none' {\n if (env[TRACING_LAUNCHER_ENV] === undefined) return 'none'\n return readLauncherHost(env) === 'action' ? 'action' : 'other'\n}\n\n/** Header names the exporter or the transport owns. A user file cannot set them. */\nconst REFUSED_HEADER_NAMES: ReadonlySet<string> = new Set([\n 'host',\n 'content-length',\n 'content-type',\n 'content-encoding',\n 'transfer-encoding',\n 'connection',\n 'keep-alive',\n 'upgrade',\n 'te',\n 'trailer',\n 'expect',\n 'proxy-authorization',\n 'proxy-authenticate',\n])\nconst HEADER_NAME = /^[\\w!#$%&'*+.^`|~-]+$/\n\nfunction parseHeaders(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return {}\n if (!isRecord(value)) return undefined\n const entries = Object.entries(value)\n if (entries.length > MAX_HEADERS) return undefined\n const headers: Record<string, string> = {}\n for (const [name, headerValue] of entries) {\n const lower = name.toLowerCase()\n if (name.length > 64 || !HEADER_NAME.test(name) || REFUSED_HEADER_NAMES.has(lower)) return undefined\n if (typeof headerValue !== 'string' || headerValue.length === 0 || headerValue.length > MAX_HEADER_VALUE_CHARS) {\n return undefined\n }\n if (hasControlCharacter(headerValue) || Object.hasOwn(headers, lower)) return undefined\n headers[lower] = headerValue\n }\n return headers\n}\n\n/** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */\nexport function userSettingsFilePath(env: Readonly<Record<string, string | undefined>>): string {\n const configured = env.XDG_CONFIG_HOME\n if (configured !== undefined && path.isAbsolute(configured)) return path.join(configured, USER_SETTINGS_RELATIVE_PATH)\n const home = env.HOME !== undefined && path.isAbsolute(env.HOME) ? env.HOME : os.homedir()\n return path.join(home, '.config', USER_SETTINGS_RELATIVE_PATH)\n}\n\ntype FileRead =\n | {readonly ok: true; readonly text: string}\n | {readonly ok: false; readonly reason: 'no-settings-file' | 'settings-file-unreadable' | 'settings-file-unsafe'}\n\nfunction errorCode(error: unknown): string | undefined {\n return isRecord(error) && typeof error.code === 'string' ? error.code : undefined\n}\n\nfunction isInside(child: string, parent: string): boolean {\n const relative = path.relative(parent, child)\n if (relative === '') return true\n // Outside means a way up (`..` alone, or `..` and a separator) or another root. A child NAMED `..config` is inside:\n // `startsWith('..')` alone would let a checkout choose the settings file.\n const goesUp = relative === '..' || relative.startsWith(`..${path.sep}`)\n return !goesUp && !path.isAbsolute(relative)\n}\n\n/**\n * Reads the user file, checking the OPENED handle: a regular file, owned by the current user, private to its owner (no group\n * or other permission bit at all: it can hold a collector credential, so readable is as bad as writable), small, and whose\n * real path is outside the project. A symlink is resolved first and its target is what gets opened and checked.\n */\nfunction readSettingsFile(filePath: string, directory: string, uid: number): FileRead {\n let realPath: string\n try {\n realPath = realpathSync(filePath)\n } catch (error) {\n const code = errorCode(error)\n return {\n ok: false,\n reason: code === 'ENOENT' || code === 'ENOTDIR' ? 'no-settings-file' : 'settings-file-unreadable',\n }\n }\n\n let realDirectory: string\n try {\n realDirectory = realpathSync(directory)\n } catch {\n realDirectory = path.resolve(directory)\n }\n if (isInside(realPath, realDirectory)) return {ok: false, reason: 'settings-file-unsafe'}\n\n let fd: number\n try {\n // NONBLOCK so a FIFO cannot hang the open; NOFOLLOW because `realPath` has no links left to follow.\n fd = openSync(realPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)\n } catch {\n return {ok: false, reason: 'settings-file-unreadable'}\n }\n try {\n const stat = fstatSync(fd)\n if (!stat.isFile() || stat.uid !== uid || (stat.mode & 0o077) !== 0 || stat.size > MAX_SETTINGS_FILE_BYTES) {\n return {ok: false, reason: 'settings-file-unsafe'}\n }\n const buffer = Buffer.alloc(stat.size)\n let offset = 0\n while (offset < buffer.length) {\n const read = readSync(fd, buffer, offset, buffer.length - offset, offset)\n if (read === 0) break\n offset += read\n }\n return {ok: true, text: buffer.subarray(0, offset).toString('utf8')}\n } catch {\n return {ok: false, reason: 'settings-file-unreadable'}\n } finally {\n closeSync(fd)\n }\n}\n\n/** A name as compared: trimmed, lower case, without one trailing dot. */\nconst normalizeHostname = (value: string): string => {\n const lower = value.trim().toLowerCase()\n return lower.endsWith('.') ? lower.slice(0, -1) : lower\n}\n\n/** Letters, digits, dot, hyphen and underscore: what a machine name holds. No wildcard, port, path or space. */\nconst HOSTNAME_ENTRY = /^[\\da-z._-]+$/\n\n/** The `hosts` list: one to 16 names, each normalized. Undefined when the list or any entry is not acceptable. */\nfunction parseHosts(value: unknown): string[] | undefined {\n if (!Array.isArray(value) || value.length === 0 || value.length > MAX_HOSTS) return undefined\n const hosts: string[] = []\n for (const entry of value as unknown[]) {\n if (typeof entry !== 'string' || entry.length > MAX_HOSTNAME_CHARS + 2) return undefined\n const host = normalizeHostname(entry)\n if (host.length === 0 || host.length > MAX_HOSTNAME_CHARS || !HOSTNAME_ENTRY.test(host)) return undefined\n hosts.push(host)\n }\n return hosts\n}\n\n/**\n * Whether `machine` is one of `hosts`. An entry matches the whole name, or the part of the name before its first dot. That\n * part never holds a dot, so an entry with a dot can only ever match the whole name: `build-box.example.test` does not\n * match a machine called `build-box`. No wildcards, no prefix or suffix matching.\n */\nfunction namesMachine(hosts: readonly string[], machine: string): boolean {\n const name = normalizeHostname(machine)\n if (name.length === 0) return false\n const short = name.split('.')[0]\n return hosts.some(host => host === name || host === short)\n}\n\nfunction resolveSettingsFile(\n text: string,\n hostname: () => string,\n): {readonly settings: TracingSettings; readonly host?: string} {\n let document: unknown\n try {\n document = JSON.parse(text)\n } catch {\n return {settings: off('settings-file-invalid')}\n }\n if (!isRecord(document) || document.version !== TRACING_SETTINGS_VERSION) {\n return {settings: off('settings-file-invalid')}\n }\n const allowed = Object.keys(document).every(\n key => key === 'version' || key === 'endpoint' || key === 'headers' || key === 'hosts',\n )\n const url = parseCollectorUrl(document.endpoint)\n const headers = parseHeaders(document.headers)\n const hosts = parseHosts(document.hosts)\n if (!allowed || url === undefined || headers === undefined || hosts === undefined) {\n return {settings: off('settings-file-invalid')}\n }\n // A valid file for another machine is not an error: it is silently not for this one.\n if (!namesMachine(hosts, hostname())) return {settings: off('machine-not-listed')}\n return {settings: {mode: 'on', host: 'local', endpoint: url.href, headers}, host: url.host}\n}\n\n/**\n * Decides whether tracing is on. Never throws. Logs at most one line: an off with a reason worth knowing, or, for a local\n * session, the destination host. Lines carry fixed text and a host name, never a header, a path or a settings value.\n */\nexport function resolveTracingSettings(input: ResolveTracingSettingsInput): TracingSettings {\n const {env, directory, log} = input\n const finish = (settings: TracingSettings): TracingSettings => {\n if (settings.mode === 'off' && !SILENT_REASONS.has(settings.reason)) log(`tracing off (${settings.reason})`)\n return settings\n }\n\n try {\n const launcher = env[TRACING_LAUNCHER_ENV]\n // The launcher decides alone: a declared off or a workspace host is never overridden by a user file.\n if (launcher !== undefined) return finish(resolveLauncher(launcher))\n\n // No launcher: something that is not this repo's Action started the server. A headless server stays off. The command\n // line says nothing: `serve --stdio` is also how the interactive app's private backend starts (`--standalone`, `run`,\n // ACP), and every launcher of this repo sets the variable above. Any other stdio server on this machine, an SDK\n // embedder included, falls under the user file unless it passes `OPENCODE_CONFIG_CONTENT`.\n if (HEADLESS_MARKERS.some(marker => env[marker] !== undefined)) {\n return finish(off('headless-host'))\n }\n\n const platform = input.platform ?? process.platform\n const uid = input.uid ?? process.getuid?.()\n if (platform === 'win32' || uid === undefined) return finish(off('unsupported-platform'))\n\n const file = readSettingsFile(userSettingsFilePath(env), directory, uid)\n if (!file.ok) return finish(off(file.reason))\n const resolved = resolveSettingsFile(file.text, input.hostname ?? os.hostname)\n if (resolved.settings.mode === 'on' && resolved.host !== undefined) {\n log(`tracing on, destination host ${resolved.host}`)\n }\n return finish(resolved.settings)\n } catch {\n return finish(off('settings-error'))\n }\n}\n","/** Plugin setup: registers the subagent session-reuse guard (two hooks, Fro Bot launchers only), then the four session tools. */\n\nimport type {Plugin} from '@opencode/plugin'\nimport type {PluginSessionApi} from './session-client.js'\nimport type {ToolCallBefore} from './task-reuse-guard.js'\nimport type {ObserverHost} from './tracing/record-observations.js'\nimport process from 'node:process'\nimport {logPluginLine} from './log.js'\nimport {createPluginSessionClient} from './session-client.js'\nimport {createSessionTools} from './session-tools.js'\nimport {createSubagentResumeGuard} from './task-reuse-guard.js'\nimport {readLauncherKind, resolveTracingSettings, type TracingSettings} from './tracing/settings.js'\n\ntype ToolEditor = Parameters<Parameters<Plugin.Context['tool']['transform']>[0]>[0]\ntype ToolInfo = Parameters<ToolEditor['add']>[0]\n\n/**\n * The slice of `Plugin.Context` this plugin uses: the session tools, the reuse guard and, when tracing is on, the\n * observer hooks and the event stream. Structural, so a fake host can stand in and the real context still fits.\n */\nexport interface HostSurface {\n readonly location: {readonly directory: string}\n /** The host application (`Plugin.Context.app`). Only its version is read, for the trace resource. */\n readonly app?: {readonly version?: string | undefined} | undefined\n readonly session: PluginSessionApi & ObserverHost['session']\n readonly tool: {\n transform: (callback: (editor: Pick<ToolEditor, 'add'>) => void) => Promise<unknown>\n hook: {\n (name: 'execute.before', callback: (event: ToolCallBefore) => Promise<void> | void): Promise<unknown>\n (name: 'execute.after', callback: (event: unknown) => void): Promise<unknown>\n }\n }\n readonly event: ObserverHost['event']\n}\n\n/** Cleanup the host runs when the location shuts down. */\nexport type PluginCleanup = () => Promise<void>\n\n/**\n * The only way into the tracing chunk. Called only when settings resolved to on, so with tracing off the dynamic import never\n * runs and the chunk and the SDK inside it are never evaluated. Every step (the import, SDK construction, hook\n * registration, and later the cleanup) is wrapped: a failure leaves the plugin exactly as it was, and the one log line\n * names the failure class only, since an error message can carry a path or URL.\n */\nasync function startTracing(\n host: HostSurface,\n settings: Extract<TracingSettings, {mode: 'on'}>,\n env: Readonly<Record<string, string | undefined>>,\n log: (line: string) => void,\n): Promise<PluginCleanup | undefined> {\n try {\n const tracing = await import('./tracing/index.js')\n const handle = await tracing.startTracing(\n {\n session: host.session,\n tool: {\n hook: async (name, callback) =>\n name === 'execute.before' ? host.tool.hook(name, callback) : host.tool.hook(name, callback),\n },\n event: host.event,\n },\n settings,\n {env, log, ...(typeof host.app?.version === 'string' ? {opencodeVersion: host.app.version} : {})},\n )\n return async () => {\n try {\n await handle.stop()\n } catch (error) {\n log(`tracing cleanup failed (${error instanceof Error ? error.name : 'unknown error'})`)\n }\n }\n } catch (error) {\n log(`tracing could not start (${error instanceof Error ? error.name : 'unknown error'})`)\n return undefined\n }\n}\n\n/** What `setupFroBotPlugin` reads from outside the host: injected so tests need no real environment. */\nexport interface SetupOptions {\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly log?: (line: string) => void\n}\n\nexport async function setupFroBotPlugin(\n host: HostSurface,\n options: SetupOptions = {},\n): Promise<PluginCleanup | undefined> {\n // The guard goes first: if it cannot be registered the plugin fails before exposing any tool. It exists only for Fro\n // Bot's own launchers (the Action, the workspace), told by the launcher variable: with none, resumes are stock\n // OpenCode and no hook is registered. Its record of dispatched children lives in this closure, so a reload starts empty\n // and refuses every resume until a new dispatch is seen.\n const env = options.env ?? process.env\n const launcher = readLauncherKind(env)\n if (launcher !== 'none') {\n const guard = createSubagentResumeGuard({actionHost: launcher === 'action'})\n await host.tool.hook('execute.before', async event => {\n guard.before(event)\n })\n await host.tool.hook('execute.after', event => {\n guard.after(event)\n })\n }\n\n const tools = createSessionTools({\n client: createPluginSessionClient(host.session),\n directory: host.location.directory,\n })\n await host.tool.transform(editor => {\n for (const spec of [tools.list, tools.read, tools.search, tools.info]) {\n const tool: ToolInfo = {\n name: spec.name,\n // Direct tools: the prompt names them, so they stay out of the Code Mode catalog.\n options: {codemode: false},\n description: spec.description,\n input: spec.input,\n execute: async (input: Readonly<Record<string, unknown>>) => ({content: await spec.run(input)}),\n }\n editor.add(tool)\n }\n })\n\n // Last, and never able to fail the registrations above. The settings decision lives outside the lazy chunk.\n const log = options.log ?? logPluginLine\n const settings = resolveTracingSettings({\n env,\n directory: host.location.directory,\n log,\n })\n if (settings.mode !== 'on') return undefined\n return startTracing(host, settings, env, log)\n}\n","/** `@fro.bot/opencode-plugin`: the session tools and the subagent session-reuse guard. */\n\nimport {Plugin} from '@opencode/plugin'\nimport {FRO_BOT_PLUGIN_ID} from './plugin-id.js'\nimport {setupFroBotPlugin} from './setup.js'\n\nexport {FRO_BOT_PLUGIN_ID} from './plugin-id.js'\n\nexport default Plugin.define({\n id: FRO_BOT_PLUGIN_ID,\n setup: async ctx => setupFroBotPlugin(ctx),\n})\n"],"ignoreList":[3],"mappings":";;;;;;;;;AACA,MAAa,oBAAoB;;;;;;;ACOjC,SAAgB,cAAc,SAAuB;CACnD,IAAI;EACF,QAAQ,OAAO,MAAM,6BAA6B,QAAQ,GAAG;CAC/D,QAAQ,CAER;AACF;;ACHA,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAEtB,SAAgB,kBAAkB,OAAyB;CACzD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,QAAQ,IAAI,OAA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AU,MAAK;IACzB,aAAa,KAAK;IAClB,OAAO,KAAK;IACZ,SAAS,OAAO,WAA8C,EAAC,SAAS,MAAM,KAAK,IAAI,KAAK,EAAC;GAC/F;GACA,OAAO,IAAI,IAAI;EACjB;CACF,CAAC;CAGD,MAAM,MAAM,QAAQ,OAAO;CAC3B,MAAM,WAAW,uBAAuB;EACtC;EACA,WAAW,KAAK,SAAS;EACzB;CACF,CAAC;CACD,IAAI,SAAS,SAAS,MAAM,OAAO,KAAA;CACnC,OAAO,aAAa,MAAM,UAAU,KAAK,GAAG;AAC9C;;;AC1HA,IAAA,cAAe,OAAO,OAAO;CAC3B,IAAI;CACJ,OAAO,OAAM,QAAO,kBAAkB,GAAG;AAC3C,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["isRecord","isRecord","isRecord"],"sources":["../src/plugin-id.ts","../src/log.ts","../src/session-client.ts","../../../node_modules/@bfra.me/es/lib/chunk-XGJ2KYBN.js","../../runtime/src/session/storage-mappers-v2.ts","../../runtime/src/session/storage-message-mappers-v2.ts","../../runtime/src/shared/errors.ts","../../runtime/src/session/storage-v2.ts","../../runtime/src/session/search-v2.ts","../src/session-tools.ts","../src/task-reuse-guard.ts","../src/tracing/settings.ts","../src/setup.ts","../src/index.ts"],"sourcesContent":["/** Stable plugin id; the surfaces look it up in `GET /api/plugin` to confirm the plugin is active. */\nexport const FRO_BOT_PLUGIN_ID = 'fro-bot.opencode-plugin'\n","/**\n * The plugin's one log channel. `Plugin.Context` has no logger, and stdout carries the host's protocol in `serve --stdio`,\n * so a line goes to stderr, where the server's own diagnostics go. Never throws, and takes only fixed text: callers pass\n * no setting, header or error message.\n */\n\nimport process from 'node:process'\n\nexport function logPluginLine(message: string): void {\n try {\n process.stderr.write(`[fro-bot/opencode-plugin] ${message}\\n`)\n } catch {\n // A closed stderr must not fail the plugin.\n }\n}\n","/** Adapts the plugin context's `ctx.session` to the runtime's `SessionClientV2`. */\n\nimport type {SessionClientV2, SessionListQueryV2} from '@fro-bot/runtime/session-v2'\n\n/** The slice of `ctx.session` this package reads; method syntax so the branded `SessionID` parameter still fits. */\nexport interface PluginSessionApi {\n list: (query: SessionListQueryV2) => Promise<unknown>\n get: (input: {readonly sessionID: string}) => Promise<unknown>\n context: (input: {readonly sessionID: string}) => Promise<unknown>\n}\n\nconst SESSION_ID_PREFIX = 'ses'\nconst NOT_FOUND_TAG = 'Session.NotFoundError'\n\nexport function isSessionNotFound(error: unknown): boolean {\n return typeof error === 'object' && error !== null && Reflect.get(error, '_tag') === NOT_FOUND_TAG\n}\n\nexport function createPluginSessionClient(session: PluginSessionApi): SessionClientV2 {\n return {\n list: async query => session.list(query),\n async get(sessionID) {\n // The server rejects such an id with a SchemaError, which would read as an outage.\n if (!sessionID.startsWith(SESSION_ID_PREFIX)) return null\n try {\n return await session.get({sessionID})\n } catch (error) {\n if (isSessionNotFound(error)) return null\n throw error\n }\n },\n messages: async sessionID => session.context({sessionID}),\n }\n}\n","// src/result/factories.ts\nfunction ok(value) {\n return { success: true, data: value };\n}\nfunction err(error) {\n return { success: false, error };\n}\n\nexport {\n ok,\n err\n};\n//# sourceMappingURL=chunk-XGJ2KYBN.js.map","/** V2 sibling of `storage-mappers.ts`: parse raw V2 session payloads; every mapper takes `unknown` and never throws. */\n\nimport type {SessionInfoV2} from './types-v2.js'\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v != null\nexport const readString = (v: unknown): string | null => (typeof v === 'string' ? v : null)\nexport const readNumber = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)\n\n/** Strips a `{data}` envelope. A bare payload passes through. */\nexport function unwrapData(v: unknown): unknown {\n return isRecord(v) && !Array.isArray(v) && 'data' in v ? v.data : v\n}\n\nexport function mapSessionInfoV2(v: unknown): SessionInfoV2 | null {\n const payload = unwrapData(v)\n if (!isRecord(payload) || Array.isArray(payload)) return null\n\n const id = readString(payload.id)\n const projectID = readString(payload.projectID)\n const time = payload.time\n const location = payload.location\n if (id == null || projectID == null || !isRecord(time) || !isRecord(location)) return null\n\n const created = readNumber(time.created)\n const updated = readNumber(time.updated)\n const directory = readString(location.directory)\n if (created == null || updated == null || directory == null) return null\n\n const parentID = readString(payload.parentID)\n const archived = readNumber(time.archived)\n return {\n id,\n projectID,\n directory,\n ...(parentID == null ? {} : {parentID}),\n title: readString(payload.title) ?? '',\n time: {created, updated, ...(archived == null ? {} : {archived})},\n }\n}\n\nexport interface SessionPageV2 {\n readonly sessions: readonly SessionInfoV2[]\n readonly nextCursor?: string\n}\n\n/**\n * Maps one page of sessions. Returns `null` when the payload is not list-shaped, so a protocol change is not mistaken\n * for \"no sessions\". Entries that fail to map are dropped.\n */\nexport function mapSessionPageV2(v: unknown): SessionPageV2 | null {\n const items = Array.isArray(v) ? v : isRecord(v) && Array.isArray(v.data) ? v.data : null\n if (items == null) return null\n\n const sessions: SessionInfoV2[] = []\n for (const item of items) {\n const mapped = mapSessionInfoV2(item)\n if (mapped != null) sessions.push(mapped)\n }\n\n const cursor = isRecord(v) ? v.cursor : undefined\n const nextCursor = isRecord(cursor) ? readString(cursor.next) : null\n return {sessions, ...(nextCursor == null || nextCursor.length === 0 ? {} : {nextCursor})}\n}\n","/** V2 sibling of `storage-message-mappers.ts`: flatten V2 session messages (user, synthetic, assistant, compaction). */\n\nimport type {MessageV2, PartV2, TodoItemV2} from './types-v2.js'\n\nimport {isRecord, readNumber, readString, unwrapData} from './storage-mappers-v2.js'\n\nconst TODO_TOOL = 'todowrite'\nconst TODO_STATUSES: readonly TodoItemV2['status'][] = ['pending', 'in_progress', 'completed', 'cancelled']\n\nfunction textPart(messageID: string, index: number, kind: PartV2['kind'], text: string): PartV2 {\n return {id: `${messageID}:${index}`, kind, text}\n}\n\n/** Joins the text items of a tool result. File items carry no searchable text. */\nfunction readToolText(content: unknown): string | null {\n if (!Array.isArray(content)) return null\n const texts = content.filter(isRecord).flatMap(item => {\n const text = item.type === 'text' ? readString(item.text) : null\n return text == null ? [] : [text]\n })\n return texts.length === 0 ? null : texts.join('\\n')\n}\n\nfunction readTodos(input: unknown): readonly TodoItemV2[] | null {\n if (!isRecord(input) || !Array.isArray(input.todos)) return null\n const todos: TodoItemV2[] = []\n for (const item of input.todos) {\n if (!isRecord(item)) continue\n const content = readString(item.content)\n if (content == null) continue\n const status = TODO_STATUSES.find(candidate => candidate === item.status)\n todos.push({content, status: status ?? 'pending'})\n }\n return todos\n}\n\nfunction mapAssistantContent(\n messageID: string,\n content: unknown,\n): {readonly parts: readonly PartV2[]; readonly todos?: readonly TodoItemV2[]} {\n if (!Array.isArray(content)) return {parts: []}\n\n const parts: PartV2[] = []\n let todos: readonly TodoItemV2[] | undefined\n for (const item of content) {\n if (!isRecord(item)) continue\n const index = parts.length\n if (item.type === 'text') {\n const text = readString(item.text)\n if (text != null) parts.push(textPart(messageID, index, 'text', text))\n } else if (item.type === 'reasoning') {\n const text = readString(item.text)\n if (text != null) parts.push(textPart(messageID, index, 'reasoning', text))\n } else if (item.type === 'tool' && isRecord(item.state) && item.state.status === 'completed') {\n const name = readString(item.name)\n const output = readToolText(item.state.content)\n if (name != null && output != null) parts.push(textPart(messageID, index, 'tool', `${name}: ${output}`))\n if (name === TODO_TOOL) todos = readTodos(item.state.input) ?? todos\n }\n }\n return {parts, ...(todos == null ? {} : {todos})}\n}\n\nfunction mapMessageV2(v: unknown): MessageV2 | null {\n if (!isRecord(v)) return null\n const id = readString(v.id)\n const time = v.time\n const createdAt = isRecord(time) ? readNumber(time.created) : null\n if (id == null || createdAt == null) return null\n\n if (v.type === 'user' || v.type === 'synthetic') {\n const text = readString(v.text)\n return {id, role: 'user', createdAt, parts: text == null ? [] : [textPart(id, 0, 'text', text)]}\n }\n if (v.type === 'assistant') {\n const agent = readString(v.agent)\n return {\n id,\n role: 'assistant',\n ...(agent == null ? {} : {agent}),\n createdAt,\n ...mapAssistantContent(id, v.content),\n }\n }\n // A completed compaction is the only record of what came before the active window, so keep its summary searchable.\n if (v.type === 'compaction' && v.status === 'completed') {\n const summary = readString(v.summary)\n return {id, role: 'assistant', createdAt, parts: summary == null ? [] : [textPart(id, 0, 'text', summary)]}\n }\n return null\n}\n\n/** Maps a message list oldest-first, or `null` when the payload is not list-shaped. */\nexport function mapMessagesV2(v: unknown): readonly MessageV2[] | null {\n const items = unwrapData(v)\n if (!Array.isArray(items)) return null\n\n const messages: MessageV2[] = []\n for (const item of items) {\n const mapped = mapMessageV2(item)\n if (mapped != null) messages.push(mapped)\n }\n return messages.toSorted((a, b) => a.createdAt - b.createdAt)\n}\n\n/** The todo list set by the most recent completed `todowrite` call, or an empty list. */\nexport function latestTodosV2(messages: readonly MessageV2[]): readonly TodoItemV2[] {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const todos = messages[index]?.todos\n if (todos != null) return todos\n }\n return []\n}\n","/**\n * Extract error message from unknown error.\n * @param error - Unknown value from catch block\n */\nexport function toErrorMessage(error: unknown): string {\n // A payload-owned coercion path (non-callable `toString`, a null prototype, or a throwing\n // getter) can make extraction itself throw; never let that escape an error-reporting helper.\n try {\n if (error instanceof Error) {\n return error.message\n }\n return String(error)\n } catch {\n return '[unprintable error]'\n }\n}\n\n/**\n * Wrap unknown error as Error instance.\n * @param error - Unknown value from catch block\n */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error\n }\n return new Error(toErrorMessage(error))\n}\n\n/** Longest string `formatSdkError` returns; longer messages and JSON are cut with a trailing `...`. */\nexport const SDK_ERROR_MAX_LENGTH = 500\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction bounded(text: string): string {\n return text.length > SDK_ERROR_MAX_LENGTH ? `${text.slice(0, SDK_ERROR_MAX_LENGTH - 3)}...` : text\n}\n\n/**\n * Describe the `error` of an OpenCode SDK result for a log line or an error message.\n *\n * The SDK client does not throw on an HTTP error; it returns `{error}` where `error` is the parsed response body:\n * a plain object for a JSON body (`{name: 'NotFoundError', data: {message}}`), a string for a text body. `String()`\n * of the object is `[object Object]`, which hides the cause.\n *\n * Picks, in order: `data.message`, `message`, `name`, `type`; an Error gives its message; a string is returned as\n * is. Any other object is serialised as JSON. The result is cut at `SDK_ERROR_MAX_LENGTH`. Only the value it is\n * given is read, so no request header or body can appear. Never throws: anything unreadable or unserialisable\n * (circular, BigInt, a throwing getter) is `[unprintable error]`.\n */\nexport function formatSdkError(error: unknown): string {\n try {\n if (typeof error !== 'object' || error === null || error instanceof Error) return bounded(toErrorMessage(error))\n\n const envelope = error as {\n readonly data?: unknown\n readonly message?: unknown\n readonly name?: unknown\n readonly type?: unknown\n }\n const data =\n typeof envelope.data === 'object' && envelope.data !== null\n ? (envelope.data as {readonly message?: unknown})\n : undefined\n const described =\n nonEmptyString(data?.message) ??\n nonEmptyString(envelope.message) ??\n nonEmptyString(envelope.name) ??\n nonEmptyString(envelope.type)\n return bounded(described ?? JSON.stringify(error))\n } catch {\n return '[unprintable error]'\n }\n}\n","/** V2 sibling of `storage.ts`: reads against a `SessionClientV2`, returning a `Result` so an outage is not \"no sessions\". */\n\nimport type {Result} from '@bfra.me/es/result'\nimport type {Logger} from '../shared/logger.js'\nimport type {SessionClientV2} from './backend-v2.js'\nimport type {MessageV2, SessionInfoV2, TodoItemV2} from './types-v2.js'\n\nimport {err, ok} from '@bfra.me/es/result'\nimport {toError} from '../shared/errors.js'\nimport {mapSessionInfoV2, mapSessionPageV2} from './storage-mappers-v2.js'\nimport {latestTodosV2, mapMessagesV2} from './storage-message-mappers-v2.js'\n\nconst SESSION_LIST_PAGE_SIZE = 100\n\n/** Upper bound on pages followed per listing: 10 pages of 100 sessions. */\nexport const SESSION_LIST_MAX_PAGES = 10\n\n/** Lists root, unarchived sessions created in `directory` (exact string match), newest first, up to a page bound. */\nexport async function listSessionsForDirectoryV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n return listRootSessionsV2(client, directory, logger, false)\n}\n\n/**\n * Root sessions in `directory` for retention: the unarchived ones AND the archived ones, each listed once. An archived\n * session (the context-overflow path archives the one it replaces) is out of every other listing by design, so it would\n * never age out; retention is the one reader that must see it. Both listings must succeed: pruning from half the\n * sessions would count the other half as absent.\n */\nexport async function listSessionsForPruningV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const live = await listRootSessionsV2(client, directory, logger, false)\n if (!live.success) return live\n const archived = await listRootSessionsV2(client, directory, logger, true)\n if (!archived.success) return archived\n const byId = new Map<string, SessionInfoV2>()\n for (const session of [...live.data, ...archived.data]) byId.set(session.id, session)\n return ok([...byId.values()])\n}\n\nasync function listRootSessionsV2(\n client: SessionClientV2,\n directory: string,\n logger: Logger,\n archivedOnly: boolean,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const sessions: SessionInfoV2[] = []\n let cursor: string | undefined\n\n for (let page = 0; page < SESSION_LIST_MAX_PAGES; page += 1) {\n let payload: unknown\n try {\n payload = await client.list({\n directory,\n limit: SESSION_LIST_PAGE_SIZE,\n order: 'desc',\n parentID: null,\n archived: archivedOnly,\n ...(cursor == null ? {} : {cursor}),\n })\n } catch (error) {\n logger.warning('V2 session list failed', {source: 'listSessionsForDirectoryV2', error: toError(error).message})\n return err(toError(error))\n }\n\n const parsed = mapSessionPageV2(payload)\n if (parsed == null) {\n logger.warning('V2 session list returned a payload that is not a session list', {\n source: 'listSessionsForDirectoryV2',\n type: typeof payload,\n })\n return err(new Error('session list response was not a session list'))\n }\n\n sessions.push(...parsed.sessions)\n // Stop on an empty page or a cursor that did not advance.\n if (parsed.sessions.length === 0 || parsed.nextCursor == null || parsed.nextCursor === cursor) break\n cursor = parsed.nextCursor\n }\n\n return ok(sessions)\n}\n\n/** Resolves to `ok(null)` when the session does not exist. */\nexport async function getSessionV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<SessionInfoV2 | null, Error>> {\n let payload: unknown\n try {\n payload = await client.get(sessionID)\n } catch (error) {\n logger.warning('V2 session get failed', {source: 'getSessionV2', error: toError(error).message})\n return err(toError(error))\n }\n\n if (payload == null) return ok(null)\n const session = mapSessionInfoV2(payload)\n if (session == null) {\n logger.warning('V2 session get returned an unparseable payload', {source: 'getSessionV2', type: typeof payload})\n return err(new Error('session response was not a session'))\n }\n return ok(session)\n}\n\nexport async function getSessionMessagesV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<readonly MessageV2[], Error>> {\n let payload: unknown\n try {\n payload = await client.messages(sessionID)\n } catch (error) {\n logger.warning('V2 session messages failed', {source: 'getSessionMessagesV2', error: toError(error).message})\n return err(toError(error))\n }\n\n const messages = mapMessagesV2(payload)\n if (messages == null) {\n logger.warning('V2 session messages returned a non-list payload', {\n source: 'getSessionMessagesV2',\n type: typeof payload,\n })\n return err(new Error('session messages response was not a message list'))\n }\n return ok(messages)\n}\n\n/** V2 has no todo endpoint; the list is whatever the last completed `todowrite` call in the readable messages set. */\nexport async function getSessionTodosV2(\n client: SessionClientV2,\n sessionID: string,\n logger: Logger,\n): Promise<Result<readonly TodoItemV2[], Error>> {\n const messages = await getSessionMessagesV2(client, sessionID, logger)\n return messages.success ? ok(latestTodosV2(messages.data)) : messages\n}\n","/** V2 sibling of `search.ts`: listing, content search (reads at most `SEARCH_MAX_SESSIONS` sessions) and summaries. */\n\nimport type {Result} from '@bfra.me/es/result'\nimport type {Logger} from '../shared/logger.js'\nimport type {SessionClientV2} from './backend-v2.js'\nimport type {MessageV2, SessionInfoV2, TodoItemV2} from './types-v2.js'\nimport type {SessionMatch, SessionSearchResult} from './types.js'\n\nimport {err, ok} from '@bfra.me/es/result'\nimport {latestTodosV2} from './storage-message-mappers-v2.js'\nimport {getSessionMessagesV2, getSessionV2, listSessionsForDirectoryV2} from './storage-v2.js'\n\n/** Most sessions one content search will read. */\nexport const SEARCH_MAX_SESSIONS = 100\n\nconst EXCERPT_CONTEXT_CHARS = 50\n\nexport async function listSessionsV2(\n client: SessionClientV2,\n directory: string,\n options: {readonly limit?: number; readonly fromDate?: Date; readonly toDate?: Date},\n logger: Logger,\n): Promise<Result<readonly SessionInfoV2[], Error>> {\n const {limit, fromDate, toDate} = options\n logger.debug('Listing V2 sessions', {directory, limit})\n\n const listed = await listSessionsForDirectoryV2(client, directory, logger)\n if (!listed.success) return listed\n\n // Filter again in case the server ignores the root and unarchived query filters.\n const filtered = listed.data.filter(session => {\n if (session.parentID != null || session.time.archived != null) return false\n if (fromDate != null && session.time.created < fromDate.getTime()) return false\n if (toDate != null && session.time.created > toDate.getTime()) return false\n return true\n })\n\n const sorted = filtered.toSorted((a, b) => b.time.updated - a.time.updated)\n const limited = limit == null ? sorted : sorted.slice(0, limit)\n logger.info('Listed V2 sessions', {count: limited.length, directory})\n return ok(limited)\n}\n\nfunction uniqueAgents(messages: readonly MessageV2[]): readonly string[] {\n const agents = new Set<string>()\n for (const message of messages) {\n if (message.agent != null) agents.add(message.agent)\n }\n return [...agents]\n}\n\nfunction searchMessages(\n messages: readonly MessageV2[],\n pattern: string,\n caseSensitive: boolean,\n): readonly SessionMatch[] {\n const matches: SessionMatch[] = []\n for (const message of messages) {\n for (const part of message.parts) {\n const searchText = caseSensitive ? part.text : part.text.toLowerCase()\n const index = searchText.indexOf(pattern)\n if (index === -1) continue\n\n const start = Math.max(0, index - EXCERPT_CONTEXT_CHARS)\n const end = Math.min(part.text.length, index + pattern.length + EXCERPT_CONTEXT_CHARS)\n matches.push({\n messageId: message.id,\n partId: part.id,\n excerpt: `...${part.text.slice(start, end)}...`,\n role: message.role,\n ...(message.agent == null ? {} : {agent: message.agent}),\n })\n }\n }\n return matches\n}\n\nexport async function searchSessionsV2(\n query: string,\n client: SessionClientV2,\n directory: string,\n options: {\n readonly limit?: number\n readonly caseSensitive?: boolean\n readonly sessionId?: string\n readonly excludeSessionIds?: readonly string[]\n },\n logger: Logger,\n): Promise<Result<readonly SessionSearchResult[], Error>> {\n const {limit = 20, caseSensitive = false, sessionId, excludeSessionIds = []} = options\n const excluded = new Set(excludeSessionIds)\n const pattern = caseSensitive ? query : query.toLowerCase()\n logger.debug('Searching V2 sessions', {directory, limit, caseSensitive})\n\n if (sessionId != null) {\n if (excluded.has(sessionId)) return ok([])\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return messages\n const matches = searchMessages(messages.data, pattern, caseSensitive)\n return ok(matches.length === 0 ? [] : [{sessionId, matches: matches.slice(0, limit)}])\n }\n\n const listed = await listSessionsV2(client, directory, {}, logger)\n if (!listed.success) return listed\n\n const results: SessionSearchResult[] = []\n let totalMatches = 0\n let attempted = 0\n let succeeded = 0\n let firstReadError: Error | undefined\n for (const session of listed.data.filter(s => !excluded.has(s.id)).slice(0, SEARCH_MAX_SESSIONS)) {\n if (totalMatches >= limit) break\n\n attempted += 1\n const messages = await getSessionMessagesV2(client, session.id, logger)\n if (!messages.success) {\n // already logged; one unreadable session must not sink the whole search\n firstReadError ??= messages.error\n continue\n }\n succeeded += 1\n\n const matches = searchMessages(messages.data, pattern, caseSensitive)\n if (matches.length === 0) continue\n const kept = matches.slice(0, limit - totalMatches)\n results.push({sessionId: session.id, matches: kept})\n totalMatches += kept.length\n }\n\n // Nothing was searched: \"no matches\" would be a lie.\n if (attempted > 0 && succeeded === 0 && firstReadError != null) {\n return err(new Error(`could not read any of ${attempted} sessions: ${firstReadError.message}`))\n }\n\n logger.info('V2 session search complete', {resultCount: results.length, totalMatches})\n return ok(results)\n}\n\nexport interface SessionDetailsV2 {\n readonly session: SessionInfoV2\n readonly messageCount: number\n readonly agents: readonly string[]\n readonly hasTodos: boolean\n readonly todoCount: number\n readonly completedTodos: number\n}\n\n/** Resolves to `ok(null)` when the session does not exist. */\nexport async function getSessionInfoV2(\n client: SessionClientV2,\n sessionId: string,\n logger: Logger,\n): Promise<Result<SessionDetailsV2 | null, Error>> {\n const session = await getSessionV2(client, sessionId, logger)\n if (!session.success) return session\n if (session.data == null) return ok(null)\n\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return err(messages.error)\n\n const todos: readonly TodoItemV2[] = latestTodosV2(messages.data)\n return ok({\n session: session.data,\n messageCount: messages.data.length,\n agents: uniqueAgents(messages.data),\n hasTodos: todos.length > 0,\n todoCount: todos.length,\n completedTodos: todos.filter(todo => todo.status === 'completed').length,\n })\n}\n","/**\n * The session tools `session_list`, `session_read`, `session_search` and `session_info` on the V2 session API.\n *\n * Transcripts and search read the session's active context window (messages since the last compaction, with its summary\n * standing in for older ones); todos are the list the last `todowrite` call in that window set.\n *\n * `run()` never throws: every failure returns `session store unavailable: <reason>`, one line and length-capped.\n */\n\nimport type {MessageV2, SessionClientV2, SessionInfoV2} from '@fro-bot/runtime/session-v2'\n\nimport {\n getSessionInfoV2,\n getSessionMessagesV2,\n getSessionV2,\n latestTodosV2,\n listSessionsV2,\n searchSessionsV2,\n} from '@fro-bot/runtime/session-v2'\nimport {Schema, SchemaTransformation} from 'effect'\n\nconst UNAVAILABLE_PREFIX = 'session store unavailable'\nconst REASON_MAX_CHARS = 200\n\nexport const TRANSCRIPT_CHAR_CAP = 48_000\n\nexport const SESSION_TOOL_NAMES = {\n list: 'session_list',\n read: 'session_read',\n search: 'session_search',\n info: 'session_info',\n} as const\n\n/** No-op logger: plugins have no logging channel. */\nconst silentLogger = {\n debug: (): void => {},\n info: (): void => {},\n warning: (): void => {},\n error: (): void => {},\n}\n\nexport interface SessionToolSpec<Input extends Schema.Top = Schema.Top> {\n readonly name: string\n readonly description: string\n readonly input: Input\n /** Takes the decoded tool input, defensively re-checked; never throws. */\n readonly run: (args: Readonly<Record<string, unknown>>) => Promise<string>\n}\n\nexport interface SessionToolSet {\n readonly list: SessionToolSpec<typeof ListInput>\n readonly read: SessionToolSpec<typeof ReadInput>\n readonly search: SessionToolSpec<typeof SearchInput>\n readonly info: SessionToolSpec<typeof InfoInput>\n}\n\nfunction unavailable(reason: string): string {\n return `${UNAVAILABLE_PREFIX}: ${reason}`\n}\n\n/** One line, capped. Effect tagged errors can have an empty message, so fall back to the tag. */\nfunction describeFailure(error: unknown): string {\n let raw: string\n if (error instanceof Error) {\n const tag: unknown = Reflect.get(error, '_tag')\n raw = error.message.length > 0 ? error.message : typeof tag === 'string' ? tag : error.name\n } else {\n raw = typeof error === 'string' ? error : 'unknown error'\n }\n const firstLine = raw.split('\\n')[0] ?? ''\n return firstLine.length > REASON_MAX_CHARS ? `${firstLine.slice(0, REASON_MAX_CHARS)}...` : firstLine\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined\n}\n\nfunction parseDate(value: string | undefined): Date | undefined {\n if (value == null) return undefined\n const parsed = new Date(value)\n return Number.isNaN(parsed.getTime()) ? undefined : parsed\n}\n\n/** Parses a `to_date` bound to the END of that day (inclusive upper bound). */\nfunction parseEndOfDayDate(value: string | undefined): Date | undefined {\n const parsed = parseDate(value)\n if (parsed == null) return undefined\n const endOfDay = new Date(parsed)\n endOfDay.setUTCHours(23, 59, 59, 999)\n return endOfDay\n}\n\n/** Any limit below 1 (including negative values) means \"no limit\"; a fractional limit is floored. */\nfunction normalizeLimit(value: number | undefined): number | undefined {\n return value == null || value < 1 ? undefined : Math.floor(value)\n}\n\nfunction formatTimestamp(ms: number): string {\n return new Date(ms).toISOString()\n}\n\nfunction titleOf(session: SessionInfoV2): string {\n return session.title.length > 0 ? session.title : '(untitled)'\n}\n\nfunction formatMessageForTranscript(message: MessageV2): string {\n const text = message.parts.map(part => part.text).join(' ')\n return text.length > 0 ? `[${message.role}] ${text}` : `[${message.role}] (no content)`\n}\n\n/** Renders messages oldest-first, capping total rendered size so a huge transcript can't blow the response. */\nfunction renderTranscript(messages: readonly MessageV2[]): string[] {\n const lines: string[] = []\n let size = 0\n let shown = 0\n\n for (const message of messages) {\n const line = ` ${formatMessageForTranscript(message)}`\n if (size + line.length > TRANSCRIPT_CHAR_CAP) break\n lines.push(line)\n size += line.length\n shown += 1\n }\n\n if (shown < messages.length) {\n lines.push(` ... transcript truncated (${shown} of ${messages.length} messages shown)`)\n }\n return lines\n}\n\nfunction sessionHeader(session: SessionInfoV2): string[] {\n return [\n `Session ${session.id}`,\n `Title: ${titleOf(session)}`,\n `Created: ${formatTimestamp(session.time.created)}`,\n `Updated: ${formatTimestamp(session.time.updated)}`,\n ]\n}\n\nconst CONTEXT_WINDOW_NOTE =\n \"Covers the session's active context window: messages since its last compaction, plus the compaction summary.\"\n\n/**\n * Models often send `limit` as a string (\"15\"), and OpenCode validates tool arguments with Effect Schema before the\n * handler runs, so a plain `Schema.Number` rejects it. Accept a number or a plain decimal string and DECODE it to a\n * number here: the handler's `asNumber` ignores strings, so a merely widened schema would run the read uncapped.\n * Blank, malformed (hex, trailing junk) and non-finite strings stay schema errors.\n *\n * The `u` flag and no `i` flag are deliberate: Effect exports a regex's JSON Schema `pattern` only for flags in\n * `/^[dg]*uy?$/`, and otherwise publishes the string branch as accepting anything.\n */\n// eslint-disable-next-line regexp/use-ignore-case -- the `i` flag would drop the exported JSON Schema `pattern`\nconst DECIMAL_STRING = /^\\s*[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*$/u\n\nconst LimitInput = Schema.Union([\n Schema.Number,\n Schema.String.check(Schema.isPattern(DECIMAL_STRING)).pipe(\n Schema.decodeTo(Schema.Finite, SchemaTransformation.numberFromString),\n ),\n])\n\nconst ListInput = Schema.Struct({\n limit: Schema.optionalKey(LimitInput).annotate({description: 'Maximum number of sessions to return.'}),\n from_date: Schema.optionalKey(Schema.String).annotate({\n description: 'Only include sessions created on or after this date (YYYY-MM-DD).',\n }),\n to_date: Schema.optionalKey(Schema.String).annotate({\n description: 'Only include sessions created on or before this date (YYYY-MM-DD).',\n }),\n project_path: Schema.optionalKey(Schema.String).annotate({\n description: 'Workspace/project directory to list sessions for.',\n }),\n})\n\nconst ReadInput = Schema.Struct({\n session_id: Schema.String.annotate({description: 'The session id to read (required).'}),\n include_todos: Schema.optionalKey(Schema.Boolean).annotate({description: 'Include the session todo list.'}),\n include_transcript: Schema.optionalKey(Schema.Boolean).annotate({description: 'Include the message transcript.'}),\n limit: Schema.optionalKey(LimitInput).annotate({\n description: 'Maximum number of transcript messages to include.',\n }),\n})\n\nconst SearchInput = Schema.Struct({\n query: Schema.String.annotate({description: 'Text to search for (required).'}),\n session_id: Schema.optionalKey(Schema.String).annotate({description: 'Restrict the search to a single session id.'}),\n case_sensitive: Schema.optionalKey(Schema.Boolean).annotate({description: 'Match case-sensitively.'}),\n limit: Schema.optionalKey(LimitInput).annotate({description: 'Maximum number of matches to return.'}),\n})\n\nconst InfoInput = Schema.Struct({\n session_id: Schema.String.annotate({description: 'The session id to summarize (required).'}),\n})\n\n/**\n * Builds the four tool definitions against an injected client. `directory` is the workspace the tools default to:\n * `session_list` honours a `project_path` override, `session_search` always searches the workspace.\n */\nexport function createSessionTools(options: {\n readonly client: SessionClientV2\n readonly directory: string\n}): SessionToolSet {\n const {client, directory} = options\n const logger = silentLogger\n\n const list: SessionToolSpec<typeof ListInput> = {\n name: SESSION_TOOL_NAMES.list,\n description: 'List recent OpenCode sessions for the current workspace, most recently updated first.',\n input: ListInput,\n async run(args) {\n try {\n const sessions = await listSessionsV2(\n client,\n asString(args.project_path) ?? directory,\n {\n limit: normalizeLimit(asNumber(args.limit)),\n fromDate: parseDate(asString(args.from_date)),\n toDate: parseEndOfDayDate(asString(args.to_date)),\n },\n logger,\n )\n if (!sessions.success) return unavailable(describeFailure(sessions.error))\n if (sessions.data.length === 0) return 'No sessions found.'\n\n return sessions.data\n .map(session => `${session.id} ${titleOf(session)} updated ${formatTimestamp(session.time.updated)}`)\n .join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const read: SessionToolSpec<typeof ReadInput> = {\n name: SESSION_TOOL_NAMES.read,\n description: `Read a session: header, optional todos, and optional transcript. ${CONTEXT_WINDOW_NOTE}`,\n input: ReadInput,\n async run(args) {\n const sessionId = asString(args.session_id)\n if (sessionId == null) return unavailable('session_id is required')\n\n try {\n const found = await getSessionV2(client, sessionId, logger)\n if (!found.success) return unavailable(describeFailure(found.error))\n if (found.data == null) return `session not found: ${sessionId}`\n\n const lines = sessionHeader(found.data)\n\n const includeTodos = asBoolean(args.include_todos) === true\n const includeTranscript = asBoolean(args.include_transcript) === true\n if (!includeTodos && !includeTranscript) return lines.join('\\n')\n\n // One snapshot of the active context feeds both sections.\n const messages = await getSessionMessagesV2(client, sessionId, logger)\n if (!messages.success) return unavailable(describeFailure(messages.error))\n\n if (includeTodos) {\n const todos = latestTodosV2(messages.data)\n lines.push('', 'Todos:')\n if (todos.length === 0) {\n lines.push(' (none)')\n } else {\n for (const todo of todos) lines.push(` [${todo.status}] ${todo.content}`)\n }\n }\n\n if (includeTranscript) {\n // Oldest-first; a limit returns the earliest N messages.\n const limit = normalizeLimit(asNumber(args.limit))\n const sliced = limit == null ? messages.data : messages.data.slice(0, limit)\n lines.push('', 'Transcript:')\n if (sliced.length === 0) {\n lines.push(' (empty)')\n } else {\n lines.push(...renderTranscript(sliced))\n }\n }\n\n return lines.join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const search: SessionToolSpec<typeof SearchInput> = {\n name: SESSION_TOOL_NAMES.search,\n description: `Search prior session content for matching text, optionally scoped to one session. ${CONTEXT_WINDOW_NOTE}`,\n input: SearchInput,\n async run(args) {\n const query = asString(args.query)\n if (query == null) return unavailable('query is required')\n\n try {\n const scopedSessionId = asString(args.session_id)\n if (scopedSessionId != null) {\n const found = await getSessionV2(client, scopedSessionId, logger)\n if (!found.success) return unavailable(describeFailure(found.error))\n if (found.data == null) return `session not found: ${scopedSessionId}`\n }\n\n // Search always scopes to the current workspace; there is no project_path.\n const results = await searchSessionsV2(\n query,\n client,\n directory,\n {\n limit: normalizeLimit(asNumber(args.limit)),\n caseSensitive: asBoolean(args.case_sensitive),\n sessionId: scopedSessionId,\n },\n logger,\n )\n if (!results.success) return unavailable(describeFailure(results.error))\n if (results.data.length === 0) return 'No matches found.'\n\n const lines: string[] = []\n for (const result of results.data) {\n lines.push(`Session ${result.sessionId}:`)\n for (const match of result.matches) {\n lines.push(` [${match.role}${match.agent == null ? '' : `/${match.agent}`}] ${match.excerpt}`)\n }\n }\n return lines.join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n const info: SessionToolSpec<typeof InfoInput> = {\n name: SESSION_TOOL_NAMES.info,\n description: `Summarize a session: id, title, timestamps, message and todo counts. ${CONTEXT_WINDOW_NOTE}`,\n input: InfoInput,\n async run(args) {\n const sessionId = asString(args.session_id)\n if (sessionId == null) return unavailable('session_id is required')\n\n try {\n const details = await getSessionInfoV2(client, sessionId, logger)\n if (!details.success) return unavailable(describeFailure(details.error))\n if (details.data == null) return `session not found: ${sessionId}`\n\n const {session, messageCount, agents, hasTodos, todoCount, completedTodos} = details.data\n return [\n ...sessionHeader(session),\n `Messages: ${messageCount}`,\n `Agents: ${agents.length > 0 ? agents.join(', ') : '(none)'}`,\n `Todos: ${hasTodos ? `${completedTodos}/${todoCount} completed` : '(none)'}`,\n ].join('\\n')\n } catch (error) {\n return unavailable(describeFailure(error))\n }\n },\n }\n\n return {list, read, search, info}\n}\n","/**\n * Guards `subagent` calls that resume a child session via `sessionID`, through the `execute.before` and `execute.after`\n * tool hooks. A resume is refused unless the plugin itself saw this caller dispatch that child in this run, and the\n * server was started by the Action. Everything else gets one fixed refusal.\n */\n\n/** The model-visible rejection text; it carries no ids or arguments. */\nexport const TASK_REUSE_REJECTION =\n 'Session reuse is disabled in this environment. Start a new task and include the context it needs.'\n\n/** The one tool the guard covers: a direct tool, never inside Code Mode. */\nexport const GUARDED_TOOL = 'subagent'\n\n/** How many dispatched children one guard remembers. The oldest is forgotten first, which refuses its resume. */\nexport const DEFAULT_MAX_RECORDED_CHILDREN = 1024\n\n/** The slice of the host's `execute.before` event the guard reads. `sessionID` is the calling session, host-supplied. */\nexport interface ToolCallBefore {\n readonly tool: string\n readonly input: unknown\n readonly sessionID?: string | undefined\n}\n\nexport interface SubagentResumeGuardOptions {\n /** True only when the server's launcher names the Action as its host. Any other host refuses every resume. */\n readonly actionHost: boolean\n /** Bound on remembered children. Anything that is not a positive integer uses the default. */\n readonly maxRecordedChildren?: number | undefined\n}\n\nexport interface SubagentResumeGuard {\n /** Throws the fixed refusal for a `subagent` resume that is not admitted; otherwise returns. */\n readonly before: (event: ToolCallBefore) => void\n /** Records the child of a successful fresh `subagent` dispatch. Never throws, whatever it is handed. */\n readonly after: (event: unknown) => void\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined\n}\n\n/** A resume is any `sessionID` other than absent, null or `\"\"` (upstream treats `\"\"` as absent); malformed values reject. */\nfunction resumeTarget(input: unknown): {readonly resume: false} | {readonly resume: true; readonly sessionID: unknown} {\n if (!isRecord(input)) return {resume: false}\n const sessionID: unknown = input.sessionID\n if (sessionID === undefined || sessionID === null || sessionID === '') return {resume: false}\n return {resume: true, sessionID}\n}\n\n/**\n * The caller and child of a successful fresh `subagent` dispatch, or `undefined` for anything else. Shapes, as of\n * OpenCode v2.4.1 (`packages/plugin/src/promise/tool.ts` `ToolHooks['execute.after']`, built in `packages/core/src/tool.ts`\n * `executeTool`): the event is `{tool, sessionID, input, id, …}` plus `{status: 'completed', result}` or\n * `{status: 'error', error}`. The `subagent` tool (`packages/core/src/tool/plugin/subagent.ts`) returns\n * `{output: {sessionID, status: 'running', output}, content, metadata: {sessionID, status}}`, and `result` carries those\n * as they are. The caller is the event's own `sessionID`, set by the host; nothing the model wrote names it.\n */\nfunction parseDispatch(event: unknown): {readonly caller: string; readonly child: string} | undefined {\n if (!isRecord(event) || event.tool !== GUARDED_TOOL || event.status !== 'completed') return undefined\n // A call that carried a sessionID was a resume (or a forged event): it creates no child, so it records nothing.\n if (!isRecord(event.input) || resumeTarget(event.input).resume) return undefined\n const caller = nonEmptyString(event.sessionID)\n if (caller === undefined || !isRecord(event.result)) return undefined\n\n const {metadata, output} = event.result\n const fromMetadata = isRecord(metadata) ? metadata.sessionID : undefined\n const fromOutput = isRecord(output) ? output.sessionID : undefined\n // The two name one child. When both are present and differ, neither is trusted.\n if (fromMetadata !== undefined && fromOutput !== undefined && fromMetadata !== fromOutput) return undefined\n const child = nonEmptyString(fromMetadata ?? fromOutput)\n return child === undefined ? undefined : {caller, child}\n}\n\nexport function createSubagentResumeGuard(options: SubagentResumeGuardOptions): SubagentResumeGuard {\n const {actionHost, maxRecordedChildren} = options\n const bound =\n maxRecordedChildren !== undefined && Number.isInteger(maxRecordedChildren) && maxRecordedChildren > 0\n ? maxRecordedChildren\n : DEFAULT_MAX_RECORDED_CHILDREN\n /** Child session id to the session that dispatched it. A Map iterates in insertion order, so the first key is oldest. */\n const children = new Map<string, string>()\n\n return {\n before(event) {\n if (event.tool !== GUARDED_TOOL) return\n const target = resumeTarget(event.input)\n if (!target.resume) return\n const caller = nonEmptyString(event.sessionID)\n const admitted =\n actionHost &&\n caller !== undefined &&\n typeof target.sessionID === 'string' &&\n children.get(target.sessionID) === caller\n if (!admitted) throw new Error(TASK_REUSE_REJECTION)\n },\n after(event) {\n const dispatch = parseDispatch(event)\n if (dispatch === undefined) return\n // Re-recording moves the child to the newest slot.\n children.delete(dispatch.child)\n children.set(dispatch.child, dispatch.caller)\n while (children.size > bound) {\n const oldest = children.keys().next()\n if (oldest.done === true) break\n children.delete(oldest.value)\n }\n },\n }\n}\n","/**\n * Host mode and tracing settings: one function decides whether tracing is on and where spans go, and fails closed.\n *\n * This module sits OUTSIDE the lazy tracing chunk: it decides whether the chunk loads at all, so it must stay small and\n * import nothing from the OpenTelemetry SDK. Resolving to off never evaluates the chunk.\n *\n * Where settings come from, and nowhere else:\n * - The launcher variable `OPENCODE_FROBOT_TRACING`, set by whatever started the server (the Action, the workspace).\n * - Otherwise, only in a local session, a user-scope file under the user's config directory.\n * Plugin options, project config, the checkout, restored state and session content are never read.\n *\n * The user file names the machines it is for (`hosts`, required): a file synced to another machine, or left behind on a\n * shared one, does nothing there. And a remote collector in it must be `https`, with the platform's certificate\n * verification left on: the exporter sends the file's headers (a credential) to that URL, and the file has no switch to\n * relax verification, to follow a redirect, or to use plain `http` anywhere but a loopback literal.\n */\n\nimport {Buffer} from 'node:buffer'\nimport {closeSync, constants, fstatSync, openSync, readSync, realpathSync} from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\n/**\n * Name of the launcher variable. `OPENCODE_`-prefixed so the Action's environment filter admits it, and not ending in a\n * denied suffix (`_TOKEN`, `_KEY`, `_SECRET`, `_PASSWORD`, …). It carries no credential: only host, on/off, a loopback\n * relay address and run identity.\n */\nexport const TRACING_LAUNCHER_ENV = 'OPENCODE_FROBOT_TRACING'\n\n/** Version of both the launcher document and the user file. Anything else resolves to off. */\nexport const TRACING_SETTINGS_VERSION = 1\n\n/** Variables a headless server (the Action, the workspace, any `opencode serve`) always has and a local session lacks. */\nexport const HEADLESS_MARKERS = ['OPENCODE_PASSWORD', 'OPENCODE_CONFIG_CONTENT'] as const\n\n/** The user file, relative to the user's config directory. Not under `opencode/`: OpenCode reads nothing from here. */\nexport const USER_SETTINGS_RELATIVE_PATH = path.join('fro-bot', 'opencode-plugin', 'tracing.json')\n\n/** Ceilings. A document or file over its ceiling is malformed, not truncated. */\nexport const MAX_LAUNCHER_CHARS = 4096\nexport const MAX_SETTINGS_FILE_BYTES = 16 * 1024\nexport const MAX_ENDPOINT_CHARS = 2048\nexport const MAX_HEADERS = 16\nexport const MAX_HEADER_VALUE_CHARS = 4096\nexport const MAX_HOSTS = 16\n/** The longest name DNS allows. */\nexport const MAX_HOSTNAME_CHARS = 253\nexport const MAX_IDENTITY_FIELD_CHARS = 200\n\n/** Run identity the Action supplies. Every span of an Action run carries it. */\nexport interface ActionIdentity {\n readonly repository: string\n readonly runId: string\n readonly attempt: string\n readonly job: string\n readonly trigger: string\n}\n\n/** The Action run's root span, which each turn's root span links to. Both ids are lower-case hex, not all zero. */\nexport interface RootSpanContext {\n readonly traceId: string\n readonly spanId: string\n}\n\n/**\n * What ties a turn trace to the Action run that started it. All three come from the launcher, each is optional, and none is\n * derived or altered here: `sessionId` (the Action's `<owner>/<repo>:<logical key>`) is used verbatim.\n */\nexport interface ActionRunContext {\n readonly rootSpan?: RootSpanContext | undefined\n readonly sessionId?: string | undefined\n readonly invocationId?: string | undefined\n /**\n * The GitHub server the run is on (`GITHUB_SERVER_URL`): an `https` origin with no path, query, fragment or credentials. The\n * run's URL is built from it. A launcher written before the field existed does not carry it, and reads as it always has.\n */\n readonly serverUrl?: string | undefined\n}\n\n/**\n * Why tracing is off. Fixed strings: they are the only thing a log line says about a refused setting. The first group is\n * a deliberate off and stays silent; the rest are logged once.\n */\nexport type OffReason =\n | 'action-off'\n | 'workspace-host'\n | 'unsupported-platform'\n | 'no-settings-file'\n | 'machine-not-listed'\n | 'launcher-malformed'\n | 'launcher-unsupported'\n | 'launcher-relay-invalid'\n | 'launcher-identity-invalid'\n | 'launcher-run-invalid'\n | 'headless-host'\n | 'settings-file-unreadable'\n | 'settings-file-unsafe'\n | 'settings-file-invalid'\n | 'settings-error'\n\nconst SILENT_REASONS: ReadonlySet<OffReason> = new Set([\n 'action-off',\n 'workspace-host',\n 'unsupported-platform',\n 'no-settings-file',\n 'machine-not-listed',\n])\n\nexport type TracingSettings =\n | {readonly mode: 'off'; readonly reason: OffReason}\n | ({\n readonly mode: 'on'\n readonly host: 'action'\n /** The relay's loopback traces URL. The collector credential never reaches the plugin. */\n readonly endpoint: string\n readonly identity: ActionIdentity\n } & ActionRunContext)\n | {\n readonly mode: 'on'\n readonly host: 'local'\n readonly endpoint: string\n readonly headers: Readonly<Record<string, string>>\n }\n\nexport interface ResolveTracingSettingsInput {\n readonly env: Readonly<Record<string, string | undefined>>\n /** The session's project directory: a settings file that resolves inside it is refused. */\n readonly directory: string\n readonly log: (line: string) => void\n /** Defaults to the running platform. */\n readonly platform?: NodeJS.Platform\n /** The current user's id. Defaults to `process.getuid()`. */\n readonly uid?: number | undefined\n /** The machine's name. Defaults to `os.hostname()`. Read only for a local session with a valid user file. */\n readonly hostname?: (() => string) | undefined\n}\n\nconst off = (reason: OffReason): TracingSettings => ({mode: 'off', reason})\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** True when `value` has exactly the listed keys, no more and no fewer. */\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return hasKeys(value, keys, [])\n}\n\n/** True when `value` has every required key and no key outside `required` and `optional`. */\nfunction hasKeys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[]): boolean {\n return (\n required.every(key => Object.hasOwn(value, key)) &&\n Object.keys(value).every(key => required.includes(key) || optional.includes(key))\n )\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\n/** `127.0.0.0/8` literals or `[::1]`. A hostname such as `localhost` is not accepted: it resolves through the host. */\nfunction isLoopbackHostname(hostname: string): boolean {\n if (hostname === '[::1]') return true\n const octets = hostname.split('.')\n return (\n octets.length === 4 && octets[0] === '127' && octets.every(octet => /^\\d{1,3}$/.test(octet) && Number(octet) <= 255)\n )\n}\n\nfunction parseUrl(value: unknown): URL | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_ENDPOINT_CHARS) return undefined\n if (hasControlCharacter(value)) return undefined\n try {\n const url = new URL(value)\n // Credentials in a URL would be logged by anything that prints it.\n if (url.username !== '' || url.password !== '' || url.hash !== '') return undefined\n return url\n } catch {\n return undefined\n }\n}\n\n/** The launcher's relay: plain HTTP to a loopback literal with an explicit port. */\nfunction parseRelayUrl(value: unknown): string | undefined {\n const url = parseUrl(value)\n if (url === undefined || url.protocol !== 'http:' || !isLoopbackHostname(url.hostname) || url.port === '') {\n return undefined\n }\n if (url.search !== '') return undefined\n return url.href\n}\n\n/** A user-file endpoint: HTTPS, or plain HTTP to a loopback literal. */\nfunction parseCollectorUrl(value: unknown): URL | undefined {\n const url = parseUrl(value)\n if (url === undefined) return undefined\n if (url.protocol === 'https:') return url\n if (url.protocol === 'http:' && isLoopbackHostname(url.hostname)) return url\n return undefined\n}\n\nfunction parseIdentity(value: unknown): ActionIdentity | undefined {\n if (!isRecord(value) || !hasExactKeys(value, ['repository', 'runId', 'attempt', 'job', 'trigger'])) return undefined\n const fields: string[] = []\n for (const key of ['repository', 'runId', 'attempt', 'job', 'trigger']) {\n const field = value[key]\n if (typeof field !== 'string' || field.length === 0 || field.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n if (hasControlCharacter(field)) return undefined\n fields.push(field)\n }\n const [repository = '', runId = '', attempt = '', job = '', trigger = ''] = fields\n return {repository, runId, attempt, job, trigger}\n}\n\nconst TRACE_ID = /^[\\da-f]{32}$/\nconst SPAN_ID = /^[\\da-f]{16}$/\nconst NON_ZERO = /[1-9a-f]/\n\n/** 32 and 16 lower-case hex characters, neither all zero: what W3C trace context accepts as ids. */\nfunction parseRootSpan(value: unknown): RootSpanContext | undefined {\n if (!isRecord(value) || !hasExactKeys(value, ['traceId', 'spanId'])) return undefined\n const {traceId, spanId} = value\n if (typeof traceId !== 'string' || typeof spanId !== 'string') return undefined\n if (!TRACE_ID.test(traceId) || !SPAN_ID.test(spanId) || !NON_ZERO.test(traceId) || !NON_ZERO.test(spanId)) {\n return undefined\n }\n return {traceId, spanId}\n}\n\n/** A non-empty string, at most as long as an identity field, free of control characters. */\nfunction parseTextField(value: unknown): string | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n return hasControlCharacter(value) ? undefined : value\n}\n\n/**\n * A GitHub server origin: exactly `https://<host>[:<port>]`, optionally with one trailing slash, no more. The text must be\n * what the URL parser would write back, so nothing is rewritten or discarded on the way (a path, a query, a fragment,\n * credentials, an upper-case host, a default port, a non-ASCII host all fail). Bounded like an identity field.\n */\nfunction parseServerUrl(value: unknown): string | undefined {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_IDENTITY_FIELD_CHARS) return undefined\n if (hasControlCharacter(value)) return undefined\n let url: URL\n try {\n url = new URL(value)\n } catch {\n return undefined\n }\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') return undefined\n if (value !== url.origin && value !== `${url.origin}/`) return undefined\n return url.origin\n}\n\n/** The launcher's optional run link fields. A field that is present and not acceptable refuses them all: `undefined`. */\nfunction parseRunContext(document: Record<string, unknown>): ActionRunContext | undefined {\n const context: {rootSpan?: RootSpanContext; sessionId?: string; invocationId?: string; serverUrl?: string} = {}\n if (Object.hasOwn(document, 'rootSpan')) {\n const rootSpan = parseRootSpan(document.rootSpan)\n if (rootSpan === undefined) return undefined\n context.rootSpan = rootSpan\n }\n if (Object.hasOwn(document, 'sessionId')) {\n const sessionId = parseTextField(document.sessionId)\n if (sessionId === undefined) return undefined\n context.sessionId = sessionId\n }\n if (Object.hasOwn(document, 'invocationId')) {\n const invocationId = parseTextField(document.invocationId)\n if (invocationId === undefined) return undefined\n context.invocationId = invocationId\n }\n if (Object.hasOwn(document, 'serverUrl')) {\n const serverUrl = parseServerUrl(document.serverUrl)\n if (serverUrl === undefined) return undefined\n context.serverUrl = serverUrl\n }\n return context\n}\n\n/** Resolves the launcher variable's value. Pure: no environment, no file. */\nfunction resolveLauncher(raw: string): TracingSettings {\n if (raw.length === 0 || raw.length > MAX_LAUNCHER_CHARS) return off('launcher-malformed')\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch {\n return off('launcher-malformed')\n }\n if (!isRecord(document)) return off('launcher-malformed')\n if (document.version !== TRACING_SETTINGS_VERSION) return off('launcher-unsupported')\n if (document.host === 'workspace') return off('workspace-host')\n if (document.host !== 'action') return off('launcher-unsupported')\n if (document.tracing === 'off') return off('action-off')\n if (document.tracing !== 'on') return off('launcher-malformed')\n if (\n !hasKeys(\n document,\n ['version', 'host', 'tracing', 'relay', 'identity'],\n ['rootSpan', 'sessionId', 'invocationId', 'serverUrl'],\n )\n ) {\n return off('launcher-malformed')\n }\n\n const endpoint = parseRelayUrl(document.relay)\n if (endpoint === undefined) return off('launcher-relay-invalid')\n const identity = parseIdentity(document.identity)\n if (identity === undefined) return off('launcher-identity-invalid')\n const run = parseRunContext(document)\n if (run === undefined) return off('launcher-run-invalid')\n return {mode: 'on', host: 'action', endpoint, identity, ...run}\n}\n\n/**\n * Whether the launcher variable names the Action as the host that started this server. Strict and independent of tracing:\n * only a present, size-capped, valid JSON object with `version` 1 and `host` `'action'` answers `'action'`. The tracing\n * mode, relay and identity fields are not read, so an Action run with tracing off, or with a field the tracing decision\n * would refuse, is still the Action. Anything else (no variable, a malformed or oversized one, an unknown version, the\n * workspace or any other host) answers `undefined`. A user file and the headless markers never name the Action: only the\n * Action's own launcher does. Pure and never throws; it logs nothing.\n */\nexport function readLauncherHost(env: Readonly<Record<string, string | undefined>>): 'action' | undefined {\n const raw = env[TRACING_LAUNCHER_ENV]\n if (raw === undefined || raw.length === 0 || raw.length > MAX_LAUNCHER_CHARS) return undefined\n let document: unknown\n try {\n document = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (!isRecord(document) || document.version !== TRACING_SETTINGS_VERSION) return undefined\n return document.host === 'action' ? 'action' : undefined\n}\n\n/**\n * Whether a Fro Bot launcher started this server, for the subagent resume guard: `'none'` when the launcher variable is\n * absent (a workstation, the TUI, `opencode run`, any consumer), `'action'` when it names the Action (see\n * `readLauncherHost`), and `'other'` for any variable that is present but does not: the workspace, an unknown host, or a\n * malformed document. Presence alone means a Fro Bot launcher, so a present but unreadable variable stays fail-closed.\n * Pure and never throws.\n */\nexport function readLauncherKind(env: Readonly<Record<string, string | undefined>>): 'action' | 'other' | 'none' {\n if (env[TRACING_LAUNCHER_ENV] === undefined) return 'none'\n return readLauncherHost(env) === 'action' ? 'action' : 'other'\n}\n\n/** Header names the exporter or the transport owns. A user file cannot set them. */\nconst REFUSED_HEADER_NAMES: ReadonlySet<string> = new Set([\n 'host',\n 'content-length',\n 'content-type',\n 'content-encoding',\n 'transfer-encoding',\n 'connection',\n 'keep-alive',\n 'upgrade',\n 'te',\n 'trailer',\n 'expect',\n 'proxy-authorization',\n 'proxy-authenticate',\n])\nconst HEADER_NAME = /^[\\w!#$%&'*+.^`|~-]+$/\n\nfunction parseHeaders(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return {}\n if (!isRecord(value)) return undefined\n const entries = Object.entries(value)\n if (entries.length > MAX_HEADERS) return undefined\n const headers: Record<string, string> = {}\n for (const [name, headerValue] of entries) {\n const lower = name.toLowerCase()\n if (name.length > 64 || !HEADER_NAME.test(name) || REFUSED_HEADER_NAMES.has(lower)) return undefined\n if (typeof headerValue !== 'string' || headerValue.length === 0 || headerValue.length > MAX_HEADER_VALUE_CHARS) {\n return undefined\n }\n if (hasControlCharacter(headerValue) || Object.hasOwn(headers, lower)) return undefined\n headers[lower] = headerValue\n }\n return headers\n}\n\n/** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */\nexport function userSettingsFilePath(env: Readonly<Record<string, string | undefined>>): string {\n const configured = env.XDG_CONFIG_HOME\n if (configured !== undefined && path.isAbsolute(configured)) return path.join(configured, USER_SETTINGS_RELATIVE_PATH)\n const home = env.HOME !== undefined && path.isAbsolute(env.HOME) ? env.HOME : os.homedir()\n return path.join(home, '.config', USER_SETTINGS_RELATIVE_PATH)\n}\n\ntype FileRead =\n | {readonly ok: true; readonly text: string}\n | {readonly ok: false; readonly reason: 'no-settings-file' | 'settings-file-unreadable' | 'settings-file-unsafe'}\n\nfunction errorCode(error: unknown): string | undefined {\n return isRecord(error) && typeof error.code === 'string' ? error.code : undefined\n}\n\nfunction isInside(child: string, parent: string): boolean {\n const relative = path.relative(parent, child)\n if (relative === '') return true\n // Outside means a way up (`..` alone, or `..` and a separator) or another root. A child NAMED `..config` is inside:\n // `startsWith('..')` alone would let a checkout choose the settings file.\n const goesUp = relative === '..' || relative.startsWith(`..${path.sep}`)\n return !goesUp && !path.isAbsolute(relative)\n}\n\n/**\n * Reads the user file, checking the OPENED handle: a regular file, owned by the current user, private to its owner (no group\n * or other permission bit at all: it can hold a collector credential, so readable is as bad as writable), small, and whose\n * real path is outside the project. A symlink is resolved first and its target is what gets opened and checked.\n */\nfunction readSettingsFile(filePath: string, directory: string, uid: number): FileRead {\n let realPath: string\n try {\n realPath = realpathSync(filePath)\n } catch (error) {\n const code = errorCode(error)\n return {\n ok: false,\n reason: code === 'ENOENT' || code === 'ENOTDIR' ? 'no-settings-file' : 'settings-file-unreadable',\n }\n }\n\n let realDirectory: string\n try {\n realDirectory = realpathSync(directory)\n } catch {\n realDirectory = path.resolve(directory)\n }\n if (isInside(realPath, realDirectory)) return {ok: false, reason: 'settings-file-unsafe'}\n\n let fd: number\n try {\n // NONBLOCK so a FIFO cannot hang the open; NOFOLLOW because `realPath` has no links left to follow.\n fd = openSync(realPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)\n } catch {\n return {ok: false, reason: 'settings-file-unreadable'}\n }\n try {\n const stat = fstatSync(fd)\n if (!stat.isFile() || stat.uid !== uid || (stat.mode & 0o077) !== 0 || stat.size > MAX_SETTINGS_FILE_BYTES) {\n return {ok: false, reason: 'settings-file-unsafe'}\n }\n const buffer = Buffer.alloc(stat.size)\n let offset = 0\n while (offset < buffer.length) {\n const read = readSync(fd, buffer, offset, buffer.length - offset, offset)\n if (read === 0) break\n offset += read\n }\n return {ok: true, text: buffer.subarray(0, offset).toString('utf8')}\n } catch {\n return {ok: false, reason: 'settings-file-unreadable'}\n } finally {\n closeSync(fd)\n }\n}\n\n/** A name as compared: trimmed, lower case, without one trailing dot. */\nconst normalizeHostname = (value: string): string => {\n const lower = value.trim().toLowerCase()\n return lower.endsWith('.') ? lower.slice(0, -1) : lower\n}\n\n/** Letters, digits, dot, hyphen and underscore: what a machine name holds. No wildcard, port, path or space. */\nconst HOSTNAME_ENTRY = /^[\\da-z._-]+$/\n\n/** The `hosts` list: one to 16 names, each normalized. Undefined when the list or any entry is not acceptable. */\nfunction parseHosts(value: unknown): string[] | undefined {\n if (!Array.isArray(value) || value.length === 0 || value.length > MAX_HOSTS) return undefined\n const hosts: string[] = []\n for (const entry of value as unknown[]) {\n if (typeof entry !== 'string' || entry.length > MAX_HOSTNAME_CHARS + 2) return undefined\n const host = normalizeHostname(entry)\n if (host.length === 0 || host.length > MAX_HOSTNAME_CHARS || !HOSTNAME_ENTRY.test(host)) return undefined\n hosts.push(host)\n }\n return hosts\n}\n\n/**\n * Whether `machine` is one of `hosts`. An entry matches the whole name, or the part of the name before its first dot. That\n * part never holds a dot, so an entry with a dot can only ever match the whole name: `build-box.example.test` does not\n * match a machine called `build-box`. No wildcards, no prefix or suffix matching.\n */\nfunction namesMachine(hosts: readonly string[], machine: string): boolean {\n const name = normalizeHostname(machine)\n if (name.length === 0) return false\n const short = name.split('.')[0]\n return hosts.some(host => host === name || host === short)\n}\n\nfunction resolveSettingsFile(\n text: string,\n hostname: () => string,\n): {readonly settings: TracingSettings; readonly host?: string} {\n let document: unknown\n try {\n document = JSON.parse(text)\n } catch {\n return {settings: off('settings-file-invalid')}\n }\n if (!isRecord(document) || document.version !== TRACING_SETTINGS_VERSION) {\n return {settings: off('settings-file-invalid')}\n }\n const allowed = Object.keys(document).every(\n key => key === 'version' || key === 'endpoint' || key === 'headers' || key === 'hosts',\n )\n const url = parseCollectorUrl(document.endpoint)\n const headers = parseHeaders(document.headers)\n const hosts = parseHosts(document.hosts)\n if (!allowed || url === undefined || headers === undefined || hosts === undefined) {\n return {settings: off('settings-file-invalid')}\n }\n // A valid file for another machine is not an error: it is silently not for this one.\n if (!namesMachine(hosts, hostname())) return {settings: off('machine-not-listed')}\n return {settings: {mode: 'on', host: 'local', endpoint: url.href, headers}, host: url.host}\n}\n\n/**\n * Decides whether tracing is on. Never throws. Logs at most one line: an off with a reason worth knowing, or, for a local\n * session, the destination host. Lines carry fixed text and a host name, never a header, a path or a settings value.\n */\nexport function resolveTracingSettings(input: ResolveTracingSettingsInput): TracingSettings {\n const {env, directory, log} = input\n const finish = (settings: TracingSettings): TracingSettings => {\n if (settings.mode === 'off' && !SILENT_REASONS.has(settings.reason)) log(`tracing off (${settings.reason})`)\n return settings\n }\n\n try {\n const launcher = env[TRACING_LAUNCHER_ENV]\n // The launcher decides alone: a declared off or a workspace host is never overridden by a user file.\n if (launcher !== undefined) return finish(resolveLauncher(launcher))\n\n // No launcher: something that is not this repo's Action started the server. A headless server stays off. The command\n // line says nothing: `serve --stdio` is also how the interactive app's private backend starts (`--standalone`, `run`,\n // ACP), and every launcher of this repo sets the variable above. Any other stdio server on this machine, an SDK\n // embedder included, falls under the user file unless it passes `OPENCODE_CONFIG_CONTENT`.\n if (HEADLESS_MARKERS.some(marker => env[marker] !== undefined)) {\n return finish(off('headless-host'))\n }\n\n const platform = input.platform ?? process.platform\n const uid = input.uid ?? process.getuid?.()\n if (platform === 'win32' || uid === undefined) return finish(off('unsupported-platform'))\n\n const file = readSettingsFile(userSettingsFilePath(env), directory, uid)\n if (!file.ok) return finish(off(file.reason))\n const resolved = resolveSettingsFile(file.text, input.hostname ?? os.hostname)\n if (resolved.settings.mode === 'on' && resolved.host !== undefined) {\n log(`tracing on, destination host ${resolved.host}`)\n }\n return finish(resolved.settings)\n } catch {\n return finish(off('settings-error'))\n }\n}\n","/** Plugin setup: registers the subagent session-reuse guard (two hooks, Fro Bot launchers only), then the four session tools. */\n\nimport type {Plugin} from '@opencode/plugin'\nimport type {PluginSessionApi} from './session-client.js'\nimport type {ToolCallBefore} from './task-reuse-guard.js'\nimport type {ObserverHost} from './tracing/record-observations.js'\nimport process from 'node:process'\nimport {logPluginLine} from './log.js'\nimport {createPluginSessionClient} from './session-client.js'\nimport {createSessionTools} from './session-tools.js'\nimport {createSubagentResumeGuard} from './task-reuse-guard.js'\nimport {readLauncherKind, resolveTracingSettings, type TracingSettings} from './tracing/settings.js'\n\ntype ToolEditor = Parameters<Parameters<Plugin.Context['tool']['transform']>[0]>[0]\ntype ToolInfo = Parameters<ToolEditor['add']>[0]\n\n/**\n * The slice of `Plugin.Context` this plugin uses: the session tools, the reuse guard and, when tracing is on, the\n * observer hooks and the event stream. Structural, so a fake host can stand in and the real context still fits.\n */\nexport interface HostSurface {\n readonly location: {readonly directory: string}\n /** The host application (`Plugin.Context.app`). Only its version is read, for the trace resource. */\n readonly app?: {readonly version?: string | undefined} | undefined\n readonly session: PluginSessionApi & ObserverHost['session']\n readonly tool: {\n transform: (callback: (editor: Pick<ToolEditor, 'add'>) => void) => Promise<unknown>\n hook: {\n (name: 'execute.before', callback: (event: ToolCallBefore) => Promise<void> | void): Promise<unknown>\n (name: 'execute.after', callback: (event: unknown) => void): Promise<unknown>\n }\n }\n readonly event: ObserverHost['event']\n}\n\n/** Cleanup the host runs when the location shuts down. */\nexport type PluginCleanup = () => Promise<void>\n\n/**\n * The only way into the tracing chunk. Called only when settings resolved to on, so with tracing off the dynamic import never\n * runs and the chunk and the SDK inside it are never evaluated. Every step (the import, SDK construction, hook\n * registration, and later the cleanup) is wrapped: a failure leaves the plugin exactly as it was, and the one log line\n * names the failure class only, since an error message can carry a path or URL.\n */\nasync function startTracing(\n host: HostSurface,\n settings: Extract<TracingSettings, {mode: 'on'}>,\n env: Readonly<Record<string, string | undefined>>,\n log: (line: string) => void,\n): Promise<PluginCleanup | undefined> {\n try {\n const tracing = await import('./tracing/index.js')\n const handle = await tracing.startTracing(\n {\n session: host.session,\n tool: {\n hook: async (name, callback) =>\n name === 'execute.before' ? host.tool.hook(name, callback) : host.tool.hook(name, callback),\n },\n event: host.event,\n },\n settings,\n {\n env,\n log,\n directory: host.location.directory,\n ...(typeof host.app?.version === 'string' ? {opencodeVersion: host.app.version} : {}),\n },\n )\n return async () => {\n try {\n await handle.stop()\n } catch (error) {\n log(`tracing cleanup failed (${error instanceof Error ? error.name : 'unknown error'})`)\n }\n }\n } catch (error) {\n log(`tracing could not start (${error instanceof Error ? error.name : 'unknown error'})`)\n return undefined\n }\n}\n\n/** What `setupFroBotPlugin` reads from outside the host: injected so tests need no real environment. */\nexport interface SetupOptions {\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly log?: (line: string) => void\n}\n\nexport async function setupFroBotPlugin(\n host: HostSurface,\n options: SetupOptions = {},\n): Promise<PluginCleanup | undefined> {\n // The guard goes first: if it cannot be registered the plugin fails before exposing any tool. It exists only for Fro\n // Bot's own launchers (the Action, the workspace), told by the launcher variable: with none, resumes are stock\n // OpenCode and no hook is registered. Its record of dispatched children lives in this closure, so a reload starts empty\n // and refuses every resume until a new dispatch is seen.\n const env = options.env ?? process.env\n const launcher = readLauncherKind(env)\n if (launcher !== 'none') {\n const guard = createSubagentResumeGuard({actionHost: launcher === 'action'})\n await host.tool.hook('execute.before', async event => {\n guard.before(event)\n })\n await host.tool.hook('execute.after', event => {\n guard.after(event)\n })\n }\n\n const tools = createSessionTools({\n client: createPluginSessionClient(host.session),\n directory: host.location.directory,\n })\n await host.tool.transform(editor => {\n for (const spec of [tools.list, tools.read, tools.search, tools.info]) {\n const tool: ToolInfo = {\n name: spec.name,\n // Direct tools: the prompt names them, so they stay out of the Code Mode catalog.\n options: {codemode: false},\n description: spec.description,\n input: spec.input,\n execute: async (input: Readonly<Record<string, unknown>>) => ({content: await spec.run(input)}),\n }\n editor.add(tool)\n }\n })\n\n // Last, and never able to fail the registrations above. The settings decision lives outside the lazy chunk.\n const log = options.log ?? logPluginLine\n const settings = resolveTracingSettings({\n env,\n directory: host.location.directory,\n log,\n })\n if (settings.mode !== 'on') return undefined\n return startTracing(host, settings, env, log)\n}\n","/** `@fro.bot/opencode-plugin`: the session tools and the subagent session-reuse guard. */\n\nimport {Plugin} from '@opencode/plugin'\nimport {FRO_BOT_PLUGIN_ID} from './plugin-id.js'\nimport {setupFroBotPlugin} from './setup.js'\n\nexport {FRO_BOT_PLUGIN_ID} from './plugin-id.js'\n\nexport default Plugin.define({\n id: FRO_BOT_PLUGIN_ID,\n setup: async ctx => setupFroBotPlugin(ctx),\n})\n"],"ignoreList":[3],"mappings":";;;;;;;;;AACA,MAAa,oBAAoB;;;;;;;ACOjC,SAAgB,cAAc,SAAuB;CACnD,IAAI;EACF,QAAQ,OAAO,MAAM,6BAA6B,QAAQ,GAAG;CAC/D,QAAQ,CAER;AACF;;ACHA,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AAEtB,SAAgB,kBAAkB,OAAyB;CACzD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,QAAQ,IAAI,OAAO,MAAM,MAAM;AACvF;AAEA,SAAgB,0BAA0B,SAA4C;CACpF,OAAO;EACL,MAAM,OAAM,UAAS,QAAQ,KAAK,KAAK;EACvC,MAAM,IAAI,WAAW;GAEnB,IAAI,CAAC,UAAU,WAAW,iBAAiB,GAAG,OAAO;GACrD,IAAI;IACF,OAAO,MAAM,QAAQ,IAAI,EAAC,UAAS,CAAC;GACtC,SAAS,OAAO;IACd,IAAI,kBAAkB,KAAK,GAAG,OAAO;IACrC,MAAM;GACR;EACF;EACA,UAAU,OAAM,cAAa,QAAQ,QAAQ,EAAC,UAAS,CAAC;CAC1D;AACF;;AChCA,SAAS,GAAG,OAAO;CACjB,OAAO;EAAE,SAAS;EAAM,MAAM;CAAM;AACtC;AACA,SAAS,IAAI,OAAO;CAClB,OAAO;EAAE,SAAS;EAAO;CAAM;AACjC;;ACFA,MAAaA,cAAY,MAA6C,OAAO,MAAM,YAAY,KAAK;AACpG,MAAa,cAAc,MAA+B,OAAO,MAAM,WAAW,IAAI;AACtF,MAAa,cAAc,MAA+B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI;;AAG5G,SAAgB,WAAW,GAAqB;CAC9C,OAAOA,WA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