@fro.bot/opencode-plugin 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Fro Bot's plugin for [OpenCode](https://opencode.ai) V2 (v2.2.0 and later in the 2.x line). It gives the agent two things:
4
4
 
5
5
  - **Session history tools.** `session_list`, `session_read`, `session_search` and `session_info` read the sessions of the current workspace. `session_read` and `session_search` cover a session's active context window: the messages since its last compaction, plus the compaction summary. Todos come from the last completed `todowrite` call in that window.
6
- - **A subagent reuse guard.** A `subagent` call that carries a `sessionID` is rejected before it runs, with a fixed message that holds no ids. Every subagent starts a fresh child session.
6
+ - **A subagent resume guard.** A `subagent` call that carries a `sessionID` is rejected before it runs, with a fixed message that holds no ids, unless it resumes a child this run dispatched from the same session and the Action started the server.
7
7
 
8
8
  The plugin id is `fro-bot.opencode-plugin`. OpenCode V2 skips a plugin that fails to load and keeps serving, so anything that depends on this plugin should check `GET /api/plugin` for that id with status `active`.
9
9
 
@@ -42,6 +42,8 @@ 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
+ The root span of every trace (a turn's `invoke_agent`, and the root of a late continuation trace) also carries `langfuse.trace.name` set to the fixed string `fro-bot run`, which Langfuse shows as the trace's name. No other span has it, and it holds no content.
46
+
45
47
  **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
48
 
47
49
  - `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 or withhold (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. **Upgrading:** turns exported before the Action sent a `sessionId` stay in Langfuse under the OpenCode root session id, and new Action turns use the qualified conversation key, so one conversation shows as two sessions across the upgrade. Every span of both kinds carries `fro_bot.root_session.id` (the OpenCode root session id, whatever `langfuse.session.id` is), so a dashboard or a query can still join the old and the new turns of a conversation on it. `session.id` and `gen_ai.conversation.id` keep each span's own OpenCode session either way.
package/dist/index.mjs CHANGED
@@ -54,21 +54,21 @@ function err(error) {
54
54
  };
55
55
  }
56
56
  // ../runtime/src/session/storage-mappers-v2.ts
57
- const isRecord$1 = (v) => typeof v === "object" && v != null;
57
+ const isRecord$2 = (v) => typeof v === "object" && v != null;
58
58
  const readString = (v) => typeof v === "string" ? v : null;
59
59
  const readNumber = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
60
60
  /** Strips a `{data}` envelope. A bare payload passes through. */
61
61
  function unwrapData(v) {
62
- return isRecord$1(v) && !Array.isArray(v) && "data" in v ? v.data : v;
62
+ return isRecord$2(v) && !Array.isArray(v) && "data" in v ? v.data : v;
63
63
  }
64
64
  function mapSessionInfoV2(v) {
65
65
  const payload = unwrapData(v);
66
- if (!isRecord$1(payload) || Array.isArray(payload)) return null;
66
+ if (!isRecord$2(payload) || Array.isArray(payload)) return null;
67
67
  const id = readString(payload.id);
68
68
  const projectID = readString(payload.projectID);
69
69
  const time = payload.time;
70
70
  const location = payload.location;
71
- if (id == null || projectID == null || !isRecord$1(time) || !isRecord$1(location)) return null;
71
+ if (id == null || projectID == null || !isRecord$2(time) || !isRecord$2(location)) return null;
72
72
  const created = readNumber(time.created);
73
73
  const updated = readNumber(time.updated);
74
74
  const directory = readString(location.directory);
@@ -93,15 +93,15 @@ function mapSessionInfoV2(v) {
93
93
  * for "no sessions". Entries that fail to map are dropped.
94
94
  */
95
95
  function mapSessionPageV2(v) {
96
- const items = Array.isArray(v) ? v : isRecord$1(v) && Array.isArray(v.data) ? v.data : null;
96
+ const items = Array.isArray(v) ? v : isRecord$2(v) && Array.isArray(v.data) ? v.data : null;
97
97
  if (items == null) return null;
98
98
  const sessions = [];
99
99
  for (const item of items) {
100
100
  const mapped = mapSessionInfoV2(item);
101
101
  if (mapped != null) sessions.push(mapped);
102
102
  }
103
- const cursor = isRecord$1(v) ? v.cursor : void 0;
104
- const nextCursor = isRecord$1(cursor) ? readString(cursor.next) : null;
103
+ const cursor = isRecord$2(v) ? v.cursor : void 0;
104
+ const nextCursor = isRecord$2(cursor) ? readString(cursor.next) : null;
105
105
  return {
106
106
  sessions,
107
107
  ...nextCursor == null || nextCursor.length === 0 ? {} : { nextCursor }
@@ -125,17 +125,17 @@ function textPart(messageID, index, kind, text) {
125
125
  /** Joins the text items of a tool result. File items carry no searchable text. */
126
126
  function readToolText(content) {
127
127
  if (!Array.isArray(content)) return null;
128
- const texts = content.filter(isRecord$1).flatMap((item) => {
128
+ const texts = content.filter(isRecord$2).flatMap((item) => {
129
129
  const text = item.type === "text" ? readString(item.text) : null;
130
130
  return text == null ? [] : [text];
131
131
  });
132
132
  return texts.length === 0 ? null : texts.join("\n");
133
133
  }
134
134
  function readTodos(input) {
135
- if (!isRecord$1(input) || !Array.isArray(input.todos)) return null;
135
+ if (!isRecord$2(input) || !Array.isArray(input.todos)) return null;
136
136
  const todos = [];
137
137
  for (const item of input.todos) {
138
- if (!isRecord$1(item)) continue;
138
+ if (!isRecord$2(item)) continue;
139
139
  const content = readString(item.content);
140
140
  if (content == null) continue;
141
141
  const status = TODO_STATUSES.find((candidate) => candidate === item.status);
@@ -151,7 +151,7 @@ function mapAssistantContent(messageID, content) {
151
151
  const parts = [];
152
152
  let todos;
153
153
  for (const item of content) {
154
- if (!isRecord$1(item)) continue;
154
+ if (!isRecord$2(item)) continue;
155
155
  const index = parts.length;
156
156
  if (item.type === "text") {
157
157
  const text = readString(item.text);
@@ -159,7 +159,7 @@ function mapAssistantContent(messageID, content) {
159
159
  } else if (item.type === "reasoning") {
160
160
  const text = readString(item.text);
161
161
  if (text != null) parts.push(textPart(messageID, index, "reasoning", text));
162
- } else if (item.type === "tool" && isRecord$1(item.state) && item.state.status === "completed") {
162
+ } else if (item.type === "tool" && isRecord$2(item.state) && item.state.status === "completed") {
163
163
  const name = readString(item.name);
164
164
  const output = readToolText(item.state.content);
165
165
  if (name != null && output != null) parts.push(textPart(messageID, index, "tool", `${name}: ${output}`));
@@ -172,10 +172,10 @@ function mapAssistantContent(messageID, content) {
172
172
  };
173
173
  }
174
174
  function mapMessageV2(v) {
175
- if (!isRecord$1(v)) return null;
175
+ if (!isRecord$2(v)) return null;
176
176
  const id = readString(v.id);
177
177
  const time = v.time;
178
- const createdAt = isRecord$1(time) ? readNumber(time.created) : null;
178
+ const createdAt = isRecord$2(time) ? readNumber(time.created) : null;
179
179
  if (id == null || createdAt == null) return null;
180
180
  if (v.type === "user" || v.type === "synthetic") {
181
181
  const text = readString(v.text);
@@ -673,18 +673,79 @@ function createSessionTools(options) {
673
673
  };
674
674
  }
675
675
  // src/task-reuse-guard.ts
676
- /** Rejects `subagent` calls that resume a child session via `sessionID`, via the `execute.before` tool hook. */
676
+ /**
677
+ * Guards `subagent` calls that resume a child session via `sessionID`, through the `execute.before` and `execute.after`
678
+ * tool hooks. A resume is refused unless the plugin itself saw this caller dispatch that child in this run, and the
679
+ * server was started by the Action. Everything else gets one fixed refusal.
680
+ */
677
681
  /** The model-visible rejection text; it carries no ids or arguments. */
678
682
  const TASK_REUSE_REJECTION = "Session reuse is disabled in this environment. Start a new task and include the context it needs.";
683
+ /** How many dispatched children one guard remembers. The oldest is forgotten first, which refuses its resume. */
684
+ const DEFAULT_MAX_RECORDED_CHILDREN = 1024;
685
+ function isRecord$1(value) {
686
+ return value !== null && typeof value === "object" && !Array.isArray(value);
687
+ }
688
+ function nonEmptyString(value) {
689
+ return typeof value === "string" && value !== "" ? value : void 0;
690
+ }
679
691
  /** A resume is any `sessionID` other than absent, null or `""` (upstream treats `""` as absent); malformed values reject. */
680
- function carriesResume(input) {
681
- if (input === null || typeof input !== "object" || Array.isArray(input)) return false;
682
- const sessionID = Reflect.get(input, "sessionID");
683
- return sessionID !== void 0 && sessionID !== null && sessionID !== "";
692
+ function resumeTarget(input) {
693
+ if (!isRecord$1(input)) return { resume: false };
694
+ const sessionID = input.sessionID;
695
+ if (sessionID === void 0 || sessionID === null || sessionID === "") return { resume: false };
696
+ return {
697
+ resume: true,
698
+ sessionID
699
+ };
684
700
  }
685
- function rejectSubagentReuse(event) {
686
- if (event.tool !== "subagent") return;
687
- if (carriesResume(event.input)) throw new Error(TASK_REUSE_REJECTION);
701
+ /**
702
+ * The caller and child of a successful fresh `subagent` dispatch, or `undefined` for anything else. Shapes, as of
703
+ * OpenCode v2.4.1 (`packages/plugin/src/promise/tool.ts` `ToolHooks['execute.after']`, built in `packages/core/src/tool.ts`
704
+ * `executeTool`): the event is `{tool, sessionID, input, id, …}` plus `{status: 'completed', result}` or
705
+ * `{status: 'error', error}`. The `subagent` tool (`packages/core/src/tool/plugin/subagent.ts`) returns
706
+ * `{output: {sessionID, status: 'running', output}, content, metadata: {sessionID, status}}`, and `result` carries those
707
+ * as they are. The caller is the event's own `sessionID`, set by the host; nothing the model wrote names it.
708
+ */
709
+ function parseDispatch(event) {
710
+ if (!isRecord$1(event) || event.tool !== "subagent" || event.status !== "completed") return void 0;
711
+ if (!isRecord$1(event.input) || resumeTarget(event.input).resume) return void 0;
712
+ const caller = nonEmptyString(event.sessionID);
713
+ if (caller === void 0 || !isRecord$1(event.result)) return void 0;
714
+ const { metadata, output } = event.result;
715
+ const fromMetadata = isRecord$1(metadata) ? metadata.sessionID : void 0;
716
+ const fromOutput = isRecord$1(output) ? output.sessionID : void 0;
717
+ if (fromMetadata !== void 0 && fromOutput !== void 0 && fromMetadata !== fromOutput) return void 0;
718
+ const child = nonEmptyString(fromMetadata ?? fromOutput);
719
+ return child === void 0 ? void 0 : {
720
+ caller,
721
+ child
722
+ };
723
+ }
724
+ function createSubagentResumeGuard(options) {
725
+ const { actionHost, maxRecordedChildren } = options;
726
+ const bound = maxRecordedChildren !== void 0 && Number.isInteger(maxRecordedChildren) && maxRecordedChildren > 0 ? maxRecordedChildren : DEFAULT_MAX_RECORDED_CHILDREN;
727
+ /** Child session id to the session that dispatched it. A Map iterates in insertion order, so the first key is oldest. */
728
+ const children = /* @__PURE__ */ new Map();
729
+ return {
730
+ before(event) {
731
+ if (event.tool !== "subagent") return;
732
+ const target = resumeTarget(event.input);
733
+ if (!target.resume) return;
734
+ const caller = nonEmptyString(event.sessionID);
735
+ if (!(actionHost && caller !== void 0 && typeof target.sessionID === "string" && children.get(target.sessionID) === caller)) throw new Error(TASK_REUSE_REJECTION);
736
+ },
737
+ after(event) {
738
+ const dispatch = parseDispatch(event);
739
+ if (dispatch === void 0) return;
740
+ children.delete(dispatch.child);
741
+ children.set(dispatch.child, dispatch.caller);
742
+ while (children.size > bound) {
743
+ const oldest = children.keys().next();
744
+ if (oldest.done === true) break;
745
+ children.delete(oldest.value);
746
+ }
747
+ }
748
+ };
688
749
  }
689
750
  // src/tracing/settings.ts
690
751
  /**
@@ -895,6 +956,26 @@ function resolveLauncher(raw) {
895
956
  ...run
896
957
  };
897
958
  }
959
+ /**
960
+ * Whether the launcher variable names the Action as the host that started this server. Strict and independent of tracing:
961
+ * only a present, size-capped, valid JSON object with `version` 1 and `host` `'action'` answers `'action'`. The tracing
962
+ * mode, relay and identity fields are not read, so an Action run with tracing off, or with a field the tracing decision
963
+ * would refuse, is still the Action. Anything else (no variable, a malformed or oversized one, an unknown version, the
964
+ * workspace or any other host) answers `undefined`. A user file and the headless markers never name the Action: only the
965
+ * Action's own launcher does. Pure and never throws; it logs nothing.
966
+ */
967
+ function readLauncherHost(env) {
968
+ const raw = env[TRACING_LAUNCHER_ENV];
969
+ if (raw === void 0 || raw.length === 0 || raw.length > 4096) return void 0;
970
+ let document;
971
+ try {
972
+ document = JSON.parse(raw);
973
+ } catch {
974
+ return;
975
+ }
976
+ if (!isRecord(document) || document.version !== 1) return void 0;
977
+ return document.host === "action" ? "action" : void 0;
978
+ }
898
979
  /** Header names the exporter or the transport owns. A user file cannot set them. */
899
980
  const REFUSED_HEADER_NAMES = /* @__PURE__ */ new Set([
900
981
  "host",
@@ -1092,7 +1173,7 @@ function resolveTracingSettings(input) {
1092
1173
  */
1093
1174
  async function startTracing(host, settings, env, log) {
1094
1175
  try {
1095
- const handle = await (await import("./tracing-B4QJ2-E2.mjs")).startTracing({
1176
+ const handle = await (await import("./tracing-CHrTlTyx.mjs")).startTracing({
1096
1177
  session: host.session,
1097
1178
  tool: { hook: async (name, callback) => name === "execute.before" ? host.tool.hook(name, callback) : host.tool.hook(name, callback) },
1098
1179
  event: host.event
@@ -1113,8 +1194,13 @@ async function startTracing(host, settings, env, log) {
1113
1194
  }
1114
1195
  }
1115
1196
  async function setupFroBotPlugin(host, options = {}) {
1197
+ const env = options.env ?? process.env;
1198
+ const guard = createSubagentResumeGuard({ actionHost: readLauncherHost(env) === "action" });
1116
1199
  await host.tool.hook("execute.before", async (event) => {
1117
- rejectSubagentReuse(event);
1200
+ guard.before(event);
1201
+ });
1202
+ await host.tool.hook("execute.after", (event) => {
1203
+ guard.after(event);
1118
1204
  });
1119
1205
  const tools = createSessionTools({
1120
1206
  client: createPluginSessionClient(host.session),
@@ -1139,12 +1225,12 @@ async function setupFroBotPlugin(host, options = {}) {
1139
1225
  });
1140
1226
  const log = options.log ?? logPluginLine;
1141
1227
  const settings = resolveTracingSettings({
1142
- env: options.env ?? process.env,
1228
+ env,
1143
1229
  directory: host.location.directory,
1144
1230
  log
1145
1231
  });
1146
1232
  if (settings.mode !== "on") return void 0;
1147
- return startTracing(host, settings, options.env ?? process.env, log);
1233
+ return startTracing(host, settings, env, log);
1148
1234
  }
1149
1235
  // src/index.ts
1150
1236
  /** `@fro.bot/opencode-plugin`: the session tools and the subagent session-reuse guard. */