@fro.bot/opencode-plugin 0.2.0 → 0.3.0
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 +10 -0
- package/dist/index.mjs +54 -4
- package/dist/index.mjs.map +1 -1
- package/dist/{tracing-D4bUTAUS.mjs → tracing-DMDmxAqE.mjs} +3357 -3246
- package/dist/tracing-DMDmxAqE.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/tracing-D4bUTAUS.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -42,10 +42,20 @@ To turn it on, create `~/.config/fro-bot/opencode-plugin/tracing.json` (under `$
|
|
|
42
42
|
|
|
43
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.
|
|
44
44
|
|
|
45
|
+
**Joining a turn to its Action run.** The Action's launcher document (`OPENCODE_FROBOT_TRACING`) may carry three 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:
|
|
46
|
+
|
|
47
|
+
- `sessionId`: the telemetry session the Action computed, `<owner>/<repo>:<logical key>`: 1 to 200 characters, no control characters. The plugin sets `langfuse.session.id` to it **verbatim** on every span, and never derives or alters it. Every exported string is scrubbed, so a session id the scrub would change (a repository named `password-manager` reads as a name and a value) is never exported redacted, which would merge conversations into one session: that span falls back to the OpenCode root session instead. The Action avoids the fallback by passing the id through `scrubSafeSessionId` (`@fro-bot/runtime/tracing/session-id`) first, which returns the id as is when the scrub leaves it alone, else `sha256:` and 32 hex characters of its SHA-256, else none. Without it, and in every local session, `langfuse.session.id` stays the OpenCode root session as described above. `session.id` and `gen_ai.conversation.id` keep each span's own OpenCode session either way.
|
|
48
|
+
- `invocationId`: a 1 to 200 character id for the Action step that started the server, with no control characters. Every span carries it as `fro_bot.invocation.id`, mirrored to `langfuse.trace.metadata.invocation_id`. It tells apart two steps of one job, which share `run_id`, `run_attempt` and `job`.
|
|
49
|
+
- `rootSpan`: `{"traceId": "<32 hex>", "spanId": "<16 hex>"}`, the run's root span. Lower-case hex only, neither id all zero, no other key. Each turn's root span (the `invoke_agent` span of the turn's root session, standalone compaction turns included) carries one OpenTelemetry **link** to it and no link attributes. Tempo follows links; Langfuse ignores them. The turn stays a trace of its own: nothing is re-parented.
|
|
50
|
+
|
|
51
|
+
The plugin refuses a launcher document over 4,096 characters, counted on the serialized value. Fields at their 200-character limits fit when they are ordinary text, but escapes make a document longer than its fields (a lone surrogate is six characters), so the Action's writer measures the serialized value and writes the tracing-off document instead of one the plugin would refuse.
|
|
52
|
+
|
|
45
53
|
The plugin refuses the file, logging one line with a fixed reason and no values, unless it is a regular file you own, private to you (mode `0600`: **no** read, write or execute bit set for group or others, since it can hold a collector credential), under 16 KiB, and not inside the project directory. It is not read on Windows. When tracing turns on, the plugin logs the collector's host name once.
|
|
46
54
|
|
|
47
55
|
**This file is consent for the whole machine, under your account.** The plugin cannot tell your OpenCode processes apart. Any OpenCode you run here with no launcher variable and no headless marker exports its traces to the collector in this file. That includes an `opencode serve` you start by hand, the background service the interactive app connects to, and an editor integration or script that starts OpenCode for you. The one exception is a server another program embeds with `opencode serve --stdio` (the SDK, the Fro Bot Action, the gateway): it stays off, because the plugin cannot see its password. Name only machines you want traced, and delete the file to turn tracing off everywhere.
|
|
48
56
|
|
|
57
|
+
`opencode run` starts a private `serve --stdio` server unless a background service is already running. That server counts as a headless host, so it does not trace. Trace a local session through the TUI or a plain `opencode serve`.
|
|
58
|
+
|
|
49
59
|
**Matching steps to requests.** A model step is matched to its request by time, and the plugin stops matching for a session, until its execution ends, whenever it cannot tell the owner apart (an earlier request still has no step, a clock step-back, a lost event). The requests it could not match export no step data, an incomplete outcome and the gap `step-binding-uncertain`; a request that never gets a step (OpenCode abandoning it after an overflow or transport recovery) costs the rest of that execution's step data.
|
|
50
60
|
|
|
51
61
|
**Shutdown.** When the server stops, the plugin exports what it has within 3 seconds, then cancels the request that is in flight and counts what was not delivered as dropped. The SDK's retry wait is a timer the plugin cannot cancel, and it keeps a process alive that waits for its event loop to drain: after the plugin has finished, it can outlast it by up to the request timeout (10 seconds) if the collector sent a long `Retry-After`, and by about 1 to 5 seconds otherwise. Nothing is sent when it fires. OpenCode's own server does not wait for such a timer (it left about 3.3 seconds after stdin closed in every measured run, including against a collector that answers `503` with `Retry-After: 9`).
|
package/dist/index.mjs
CHANGED
|
@@ -742,7 +742,11 @@ function isRecord(value) {
|
|
|
742
742
|
}
|
|
743
743
|
/** True when `value` has exactly the listed keys, no more and no fewer. */
|
|
744
744
|
function hasExactKeys(value, keys) {
|
|
745
|
-
return
|
|
745
|
+
return hasKeys(value, keys, []);
|
|
746
|
+
}
|
|
747
|
+
/** True when `value` has every required key and no key outside `required` and `optional`. */
|
|
748
|
+
function hasKeys(value, required, optional) {
|
|
749
|
+
return required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key));
|
|
746
750
|
}
|
|
747
751
|
function hasControlCharacter(value) {
|
|
748
752
|
for (let index = 0; index < value.length; index += 1) {
|
|
@@ -812,6 +816,45 @@ function parseIdentity(value) {
|
|
|
812
816
|
trigger
|
|
813
817
|
};
|
|
814
818
|
}
|
|
819
|
+
const TRACE_ID = /^[\da-f]{32}$/;
|
|
820
|
+
const SPAN_ID = /^[\da-f]{16}$/;
|
|
821
|
+
const NON_ZERO = /[1-9a-f]/;
|
|
822
|
+
/** 32 and 16 lower-case hex characters, neither all zero: what W3C trace context accepts as ids. */
|
|
823
|
+
function parseRootSpan(value) {
|
|
824
|
+
if (!isRecord(value) || !hasExactKeys(value, ["traceId", "spanId"])) return void 0;
|
|
825
|
+
const { traceId, spanId } = value;
|
|
826
|
+
if (typeof traceId !== "string" || typeof spanId !== "string") return void 0;
|
|
827
|
+
if (!TRACE_ID.test(traceId) || !SPAN_ID.test(spanId) || !NON_ZERO.test(traceId) || !NON_ZERO.test(spanId)) return;
|
|
828
|
+
return {
|
|
829
|
+
traceId,
|
|
830
|
+
spanId
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
/** A non-empty string, at most as long as an identity field, free of control characters. */
|
|
834
|
+
function parseTextField(value) {
|
|
835
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 200) return void 0;
|
|
836
|
+
return hasControlCharacter(value) ? void 0 : value;
|
|
837
|
+
}
|
|
838
|
+
/** The launcher's optional run link fields. A field that is present and not acceptable refuses them all: `undefined`. */
|
|
839
|
+
function parseRunContext(document) {
|
|
840
|
+
const context = {};
|
|
841
|
+
if (Object.hasOwn(document, "rootSpan")) {
|
|
842
|
+
const rootSpan = parseRootSpan(document.rootSpan);
|
|
843
|
+
if (rootSpan === void 0) return void 0;
|
|
844
|
+
context.rootSpan = rootSpan;
|
|
845
|
+
}
|
|
846
|
+
if (Object.hasOwn(document, "sessionId")) {
|
|
847
|
+
const sessionId = parseTextField(document.sessionId);
|
|
848
|
+
if (sessionId === void 0) return void 0;
|
|
849
|
+
context.sessionId = sessionId;
|
|
850
|
+
}
|
|
851
|
+
if (Object.hasOwn(document, "invocationId")) {
|
|
852
|
+
const invocationId = parseTextField(document.invocationId);
|
|
853
|
+
if (invocationId === void 0) return void 0;
|
|
854
|
+
context.invocationId = invocationId;
|
|
855
|
+
}
|
|
856
|
+
return context;
|
|
857
|
+
}
|
|
815
858
|
/** Resolves the launcher variable's value. Pure: no environment, no file. */
|
|
816
859
|
function resolveLauncher(raw) {
|
|
817
860
|
if (raw.length === 0 || raw.length > 4096) return off("launcher-malformed");
|
|
@@ -827,22 +870,29 @@ function resolveLauncher(raw) {
|
|
|
827
870
|
if (document.host !== "action") return off("launcher-unsupported");
|
|
828
871
|
if (document.tracing === "off") return off("action-off");
|
|
829
872
|
if (document.tracing !== "on") return off("launcher-malformed");
|
|
830
|
-
if (!
|
|
873
|
+
if (!hasKeys(document, [
|
|
831
874
|
"version",
|
|
832
875
|
"host",
|
|
833
876
|
"tracing",
|
|
834
877
|
"relay",
|
|
835
878
|
"identity"
|
|
879
|
+
], [
|
|
880
|
+
"rootSpan",
|
|
881
|
+
"sessionId",
|
|
882
|
+
"invocationId"
|
|
836
883
|
])) return off("launcher-malformed");
|
|
837
884
|
const endpoint = parseRelayUrl(document.relay);
|
|
838
885
|
if (endpoint === void 0) return off("launcher-relay-invalid");
|
|
839
886
|
const identity = parseIdentity(document.identity);
|
|
840
887
|
if (identity === void 0) return off("launcher-identity-invalid");
|
|
888
|
+
const run = parseRunContext(document);
|
|
889
|
+
if (run === void 0) return off("launcher-run-invalid");
|
|
841
890
|
return {
|
|
842
891
|
mode: "on",
|
|
843
892
|
host: "action",
|
|
844
893
|
endpoint,
|
|
845
|
-
identity
|
|
894
|
+
identity,
|
|
895
|
+
...run
|
|
846
896
|
};
|
|
847
897
|
}
|
|
848
898
|
/** Header names the exporter or the transport owns. A user file cannot set them. */
|
|
@@ -1042,7 +1092,7 @@ function resolveTracingSettings(input) {
|
|
|
1042
1092
|
*/
|
|
1043
1093
|
async function startTracing(host, settings, env, log) {
|
|
1044
1094
|
try {
|
|
1045
|
-
const handle = await (await import("./tracing-
|
|
1095
|
+
const handle = await (await import("./tracing-DMDmxAqE.mjs")).startTracing({
|
|
1046
1096
|
session: host.session,
|
|
1047
1097
|
tool: { hook: async (name, callback) => name === "execute.before" ? host.tool.hook(name, callback) : host.tool.hook(name, callback) },
|
|
1048
1098
|
event: host.event
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["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} 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\". */\nfunction normalizeLimit(value: number | undefined): number | undefined {\n return value == null || value < 1 ? undefined : 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\nconst ListInput = Schema.Struct({\n limit: Schema.optionalKey(Schema.Number).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(Schema.Number).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(Schema.Number).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","/** Rejects `subagent` calls that resume a child session via `sessionID`, via the `execute.before` tool hook. */\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\nexport interface ToolCallBefore {\n readonly tool: string\n readonly input: unknown\n}\n\n/** A resume is any `sessionID` other than absent, null or `\"\"` (upstream treats `\"\"` as absent); malformed values reject. */\nfunction carriesResume(input: unknown): boolean {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) return false\n const sessionID: unknown = Reflect.get(input, 'sessionID')\n return sessionID !== undefined && sessionID !== null && sessionID !== ''\n}\n\nexport function rejectSubagentReuse(event: ToolCallBefore): void {\n if (event.tool !== GUARDED_TOOL) return\n if (carriesResume(event.input)) throw new Error(TASK_REUSE_REJECTION)\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/**\n * True when the command line is `opencode … serve … --stdio`: a server a parent process embeds (an SDK client, a gateway,\n * the Action). `opencode serve --stdio` deletes `OPENCODE_PASSWORD` and `OPENCODE_SERVER_PASSWORD` from the process\n * environment before a plugin loads (measured on 2.3.2), so such a server started with only a password shows none of the\n * markers above. The command line is what still says so. A `serve` started by hand, or the background service\n * (`serve --service`; `--stdio` cannot be combined with it), is not embedded: the user's file is consent for those too.\n * The subcommand is the first non-option word after the program path; `--stdio` must come after it.\n */\nfunction isEmbeddedServe(argv: readonly string[]): boolean {\n const rest = argv.slice(2)\n const serve = rest.indexOf('serve')\n return serve !== -1 && rest.slice(serve + 1).includes('--stdio')\n}\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/**\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 | '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 }\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 command line. Defaults to `process.argv`. A `serve --stdio` command is a server a parent embeds: headless. */\n readonly argv?: readonly string[] | 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 const actual = Object.keys(value)\n return actual.length === keys.length && keys.every(key => Object.hasOwn(value, key))\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\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 (!hasExactKeys(document, ['version', 'host', 'tracing', 'relay', 'identity'])) return off('launcher-malformed')\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 return {mode: 'on', host: 'action', endpoint, identity}\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.\n if (HEADLESS_MARKERS.some(marker => env[marker] !== undefined) || isEmbeddedServe(input.argv ?? process.argv)) {\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, 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 {rejectSubagentReuse} from './task-reuse-guard.js'\nimport {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 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},\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.\n await host.tool.hook('execute.before', async event => {\n rejectSubagentReuse(event)\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: options.env ?? process.env,\n directory: host.location.directory,\n log,\n })\n if (settings.mode !== 'on') return undefined\n return startTracing(host, settings, options.env ?? process.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,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O;CAC3B,IAAI;CACJ,OAAO,OAAM,QAAO,kBAAkB,GAAG;AAC3C,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["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} 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\". */\nfunction normalizeLimit(value: number | undefined): number | undefined {\n return value == null || value < 1 ? undefined : 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\nconst ListInput = Schema.Struct({\n limit: Schema.optionalKey(Schema.Number).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(Schema.Number).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(Schema.Number).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","/** Rejects `subagent` calls that resume a child session via `sessionID`, via the `execute.before` tool hook. */\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\nexport interface ToolCallBefore {\n readonly tool: string\n readonly input: unknown\n}\n\n/** A resume is any `sessionID` other than absent, null or `\"\"` (upstream treats `\"\"` as absent); malformed values reject. */\nfunction carriesResume(input: unknown): boolean {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) return false\n const sessionID: unknown = Reflect.get(input, 'sessionID')\n return sessionID !== undefined && sessionID !== null && sessionID !== ''\n}\n\nexport function rejectSubagentReuse(event: ToolCallBefore): void {\n if (event.tool !== GUARDED_TOOL) return\n if (carriesResume(event.input)) throw new Error(TASK_REUSE_REJECTION)\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/**\n * True when the command line is `opencode … serve … --stdio`: a server a parent process embeds (an SDK client, a gateway,\n * the Action). `opencode serve --stdio` deletes `OPENCODE_PASSWORD` and `OPENCODE_SERVER_PASSWORD` from the process\n * environment before a plugin loads (measured on 2.3.2), so such a server started with only a password shows none of the\n * markers above. The command line is what still says so. A `serve` started by hand, or the background service\n * (`serve --service`; `--stdio` cannot be combined with it), is not embedded: the user's file is consent for those too.\n * The subcommand is the first non-option word after the program path; `--stdio` must come after it.\n */\nfunction isEmbeddedServe(argv: readonly string[]): boolean {\n const rest = argv.slice(2)\n const serve = rest.indexOf('serve')\n return serve !== -1 && rest.slice(serve + 1).includes('--stdio')\n}\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\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 command line. Defaults to `process.argv`. A `serve --stdio` command is a server a parent embeds: headless. */\n readonly argv?: readonly string[] | 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/** 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} = {}\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 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(document, ['version', 'host', 'tracing', 'relay', 'identity'], ['rootSpan', 'sessionId', 'invocationId'])\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/** 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.\n if (HEADLESS_MARKERS.some(marker => env[marker] !== undefined) || isEmbeddedServe(input.argv ?? process.argv)) {\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, 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 {rejectSubagentReuse} from './task-reuse-guard.js'\nimport {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 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},\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.\n await host.tool.hook('execute.before', async event => {\n rejectSubagentReuse(event)\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: options.env ?? process.env,\n directory: host.location.directory,\n log,\n })\n if (settings.mode !== 'on') return undefined\n return startTracing(host, settings, options.env ?? process.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,MA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