@fro.bot/opencode-plugin 0.0.0 → 0.2.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/dist/index.mjs ADDED
@@ -0,0 +1,1107 @@
1
+ import { Plugin } from "@opencode/plugin";
2
+ import process from "node:process";
3
+ import { Schema } from "effect";
4
+ import { Buffer } from "node:buffer";
5
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ // src/plugin-id.ts
9
+ /** Stable plugin id; the surfaces look it up in `GET /api/plugin` to confirm the plugin is active. */
10
+ const FRO_BOT_PLUGIN_ID = "fro-bot.opencode-plugin";
11
+ // src/log.ts
12
+ /**
13
+ * The plugin's one log channel. `Plugin.Context` has no logger, and stdout carries the host's protocol in `serve --stdio`,
14
+ * so a line goes to stderr, where the server's own diagnostics go. Never throws, and takes only fixed text: callers pass
15
+ * no setting, header or error message.
16
+ */
17
+ function logPluginLine(message) {
18
+ try {
19
+ process.stderr.write(`[fro-bot/opencode-plugin] ${message}\n`);
20
+ } catch {}
21
+ }
22
+ // src/session-client.ts
23
+ const SESSION_ID_PREFIX = "ses";
24
+ const NOT_FOUND_TAG = "Session.NotFoundError";
25
+ function isSessionNotFound(error) {
26
+ return typeof error === "object" && error !== null && Reflect.get(error, "_tag") === NOT_FOUND_TAG;
27
+ }
28
+ function createPluginSessionClient(session) {
29
+ return {
30
+ list: async (query) => session.list(query),
31
+ async get(sessionID) {
32
+ if (!sessionID.startsWith(SESSION_ID_PREFIX)) return null;
33
+ try {
34
+ return await session.get({ sessionID });
35
+ } catch (error) {
36
+ if (isSessionNotFound(error)) return null;
37
+ throw error;
38
+ }
39
+ },
40
+ messages: async (sessionID) => session.context({ sessionID })
41
+ };
42
+ }
43
+ // ../../node_modules/@bfra.me/es/lib/chunk-XGJ2KYBN.js
44
+ function ok(value) {
45
+ return {
46
+ success: true,
47
+ data: value
48
+ };
49
+ }
50
+ function err(error) {
51
+ return {
52
+ success: false,
53
+ error
54
+ };
55
+ }
56
+ // ../runtime/src/session/storage-mappers-v2.ts
57
+ const isRecord$1 = (v) => typeof v === "object" && v != null;
58
+ const readString = (v) => typeof v === "string" ? v : null;
59
+ const readNumber = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
60
+ /** Strips a `{data}` envelope. A bare payload passes through. */
61
+ function unwrapData(v) {
62
+ return isRecord$1(v) && !Array.isArray(v) && "data" in v ? v.data : v;
63
+ }
64
+ function mapSessionInfoV2(v) {
65
+ const payload = unwrapData(v);
66
+ if (!isRecord$1(payload) || Array.isArray(payload)) return null;
67
+ const id = readString(payload.id);
68
+ const projectID = readString(payload.projectID);
69
+ const time = payload.time;
70
+ const location = payload.location;
71
+ if (id == null || projectID == null || !isRecord$1(time) || !isRecord$1(location)) return null;
72
+ const created = readNumber(time.created);
73
+ const updated = readNumber(time.updated);
74
+ const directory = readString(location.directory);
75
+ if (created == null || updated == null || directory == null) return null;
76
+ const parentID = readString(payload.parentID);
77
+ const archived = readNumber(time.archived);
78
+ return {
79
+ id,
80
+ projectID,
81
+ directory,
82
+ ...parentID == null ? {} : { parentID },
83
+ title: readString(payload.title) ?? "",
84
+ time: {
85
+ created,
86
+ updated,
87
+ ...archived == null ? {} : { archived }
88
+ }
89
+ };
90
+ }
91
+ /**
92
+ * Maps one page of sessions. Returns `null` when the payload is not list-shaped, so a protocol change is not mistaken
93
+ * for "no sessions". Entries that fail to map are dropped.
94
+ */
95
+ function mapSessionPageV2(v) {
96
+ const items = Array.isArray(v) ? v : isRecord$1(v) && Array.isArray(v.data) ? v.data : null;
97
+ if (items == null) return null;
98
+ const sessions = [];
99
+ for (const item of items) {
100
+ const mapped = mapSessionInfoV2(item);
101
+ if (mapped != null) sessions.push(mapped);
102
+ }
103
+ const cursor = isRecord$1(v) ? v.cursor : void 0;
104
+ const nextCursor = isRecord$1(cursor) ? readString(cursor.next) : null;
105
+ return {
106
+ sessions,
107
+ ...nextCursor == null || nextCursor.length === 0 ? {} : { nextCursor }
108
+ };
109
+ }
110
+ // ../runtime/src/session/storage-message-mappers-v2.ts
111
+ const TODO_TOOL = "todowrite";
112
+ const TODO_STATUSES = [
113
+ "pending",
114
+ "in_progress",
115
+ "completed",
116
+ "cancelled"
117
+ ];
118
+ function textPart(messageID, index, kind, text) {
119
+ return {
120
+ id: `${messageID}:${index}`,
121
+ kind,
122
+ text
123
+ };
124
+ }
125
+ /** Joins the text items of a tool result. File items carry no searchable text. */
126
+ function readToolText(content) {
127
+ if (!Array.isArray(content)) return null;
128
+ const texts = content.filter(isRecord$1).flatMap((item) => {
129
+ const text = item.type === "text" ? readString(item.text) : null;
130
+ return text == null ? [] : [text];
131
+ });
132
+ return texts.length === 0 ? null : texts.join("\n");
133
+ }
134
+ function readTodos(input) {
135
+ if (!isRecord$1(input) || !Array.isArray(input.todos)) return null;
136
+ const todos = [];
137
+ for (const item of input.todos) {
138
+ if (!isRecord$1(item)) continue;
139
+ const content = readString(item.content);
140
+ if (content == null) continue;
141
+ const status = TODO_STATUSES.find((candidate) => candidate === item.status);
142
+ todos.push({
143
+ content,
144
+ status: status ?? "pending"
145
+ });
146
+ }
147
+ return todos;
148
+ }
149
+ function mapAssistantContent(messageID, content) {
150
+ if (!Array.isArray(content)) return { parts: [] };
151
+ const parts = [];
152
+ let todos;
153
+ for (const item of content) {
154
+ if (!isRecord$1(item)) continue;
155
+ const index = parts.length;
156
+ if (item.type === "text") {
157
+ const text = readString(item.text);
158
+ if (text != null) parts.push(textPart(messageID, index, "text", text));
159
+ } else if (item.type === "reasoning") {
160
+ const text = readString(item.text);
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") {
163
+ const name = readString(item.name);
164
+ const output = readToolText(item.state.content);
165
+ if (name != null && output != null) parts.push(textPart(messageID, index, "tool", `${name}: ${output}`));
166
+ if (name === TODO_TOOL) todos = readTodos(item.state.input) ?? todos;
167
+ }
168
+ }
169
+ return {
170
+ parts,
171
+ ...todos == null ? {} : { todos }
172
+ };
173
+ }
174
+ function mapMessageV2(v) {
175
+ if (!isRecord$1(v)) return null;
176
+ const id = readString(v.id);
177
+ const time = v.time;
178
+ const createdAt = isRecord$1(time) ? readNumber(time.created) : null;
179
+ if (id == null || createdAt == null) return null;
180
+ if (v.type === "user" || v.type === "synthetic") {
181
+ const text = readString(v.text);
182
+ return {
183
+ id,
184
+ role: "user",
185
+ createdAt,
186
+ parts: text == null ? [] : [textPart(id, 0, "text", text)]
187
+ };
188
+ }
189
+ if (v.type === "assistant") {
190
+ const agent = readString(v.agent);
191
+ return {
192
+ id,
193
+ role: "assistant",
194
+ ...agent == null ? {} : { agent },
195
+ createdAt,
196
+ ...mapAssistantContent(id, v.content)
197
+ };
198
+ }
199
+ if (v.type === "compaction" && v.status === "completed") {
200
+ const summary = readString(v.summary);
201
+ return {
202
+ id,
203
+ role: "assistant",
204
+ createdAt,
205
+ parts: summary == null ? [] : [textPart(id, 0, "text", summary)]
206
+ };
207
+ }
208
+ return null;
209
+ }
210
+ /** Maps a message list oldest-first, or `null` when the payload is not list-shaped. */
211
+ function mapMessagesV2(v) {
212
+ const items = unwrapData(v);
213
+ if (!Array.isArray(items)) return null;
214
+ const messages = [];
215
+ for (const item of items) {
216
+ const mapped = mapMessageV2(item);
217
+ if (mapped != null) messages.push(mapped);
218
+ }
219
+ return messages.toSorted((a, b) => a.createdAt - b.createdAt);
220
+ }
221
+ /** The todo list set by the most recent completed `todowrite` call, or an empty list. */
222
+ function latestTodosV2(messages) {
223
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
224
+ const todos = messages[index]?.todos;
225
+ if (todos != null) return todos;
226
+ }
227
+ return [];
228
+ }
229
+ // ../runtime/src/shared/errors.ts
230
+ /**
231
+ * Extract error message from unknown error.
232
+ * @param error - Unknown value from catch block
233
+ */
234
+ function toErrorMessage(error) {
235
+ try {
236
+ if (error instanceof Error) return error.message;
237
+ return String(error);
238
+ } catch {
239
+ return "[unprintable error]";
240
+ }
241
+ }
242
+ /**
243
+ * Wrap unknown error as Error instance.
244
+ * @param error - Unknown value from catch block
245
+ */
246
+ function toError(error) {
247
+ if (error instanceof Error) return error;
248
+ return new Error(toErrorMessage(error));
249
+ }
250
+ // ../runtime/src/session/storage-v2.ts
251
+ const SESSION_LIST_PAGE_SIZE = 100;
252
+ /** Lists root, unarchived sessions created in `directory` (exact string match), newest first, up to a page bound. */
253
+ async function listSessionsForDirectoryV2(client, directory, logger) {
254
+ return listRootSessionsV2(client, directory, logger, false);
255
+ }
256
+ async function listRootSessionsV2(client, directory, logger, archivedOnly) {
257
+ const sessions = [];
258
+ let cursor;
259
+ for (let page = 0; page < 10; page += 1) {
260
+ let payload;
261
+ try {
262
+ payload = await client.list({
263
+ directory,
264
+ limit: SESSION_LIST_PAGE_SIZE,
265
+ order: "desc",
266
+ parentID: null,
267
+ archived: archivedOnly,
268
+ ...cursor == null ? {} : { cursor }
269
+ });
270
+ } catch (error) {
271
+ logger.warning("V2 session list failed", {
272
+ source: "listSessionsForDirectoryV2",
273
+ error: toError(error).message
274
+ });
275
+ return err(toError(error));
276
+ }
277
+ const parsed = mapSessionPageV2(payload);
278
+ if (parsed == null) {
279
+ logger.warning("V2 session list returned a payload that is not a session list", {
280
+ source: "listSessionsForDirectoryV2",
281
+ type: typeof payload
282
+ });
283
+ return err(/* @__PURE__ */ new Error("session list response was not a session list"));
284
+ }
285
+ sessions.push(...parsed.sessions);
286
+ if (parsed.sessions.length === 0 || parsed.nextCursor == null || parsed.nextCursor === cursor) break;
287
+ cursor = parsed.nextCursor;
288
+ }
289
+ return ok(sessions);
290
+ }
291
+ /** Resolves to `ok(null)` when the session does not exist. */
292
+ async function getSessionV2(client, sessionID, logger) {
293
+ let payload;
294
+ try {
295
+ payload = await client.get(sessionID);
296
+ } catch (error) {
297
+ logger.warning("V2 session get failed", {
298
+ source: "getSessionV2",
299
+ error: toError(error).message
300
+ });
301
+ return err(toError(error));
302
+ }
303
+ if (payload == null) return ok(null);
304
+ const session = mapSessionInfoV2(payload);
305
+ if (session == null) {
306
+ logger.warning("V2 session get returned an unparseable payload", {
307
+ source: "getSessionV2",
308
+ type: typeof payload
309
+ });
310
+ return err(/* @__PURE__ */ new Error("session response was not a session"));
311
+ }
312
+ return ok(session);
313
+ }
314
+ async function getSessionMessagesV2(client, sessionID, logger) {
315
+ let payload;
316
+ try {
317
+ payload = await client.messages(sessionID);
318
+ } catch (error) {
319
+ logger.warning("V2 session messages failed", {
320
+ source: "getSessionMessagesV2",
321
+ error: toError(error).message
322
+ });
323
+ return err(toError(error));
324
+ }
325
+ const messages = mapMessagesV2(payload);
326
+ if (messages == null) {
327
+ logger.warning("V2 session messages returned a non-list payload", {
328
+ source: "getSessionMessagesV2",
329
+ type: typeof payload
330
+ });
331
+ return err(/* @__PURE__ */ new Error("session messages response was not a message list"));
332
+ }
333
+ return ok(messages);
334
+ }
335
+ const EXCERPT_CONTEXT_CHARS = 50;
336
+ async function listSessionsV2(client, directory, options, logger) {
337
+ const { limit, fromDate, toDate } = options;
338
+ logger.debug("Listing V2 sessions", {
339
+ directory,
340
+ limit
341
+ });
342
+ const listed = await listSessionsForDirectoryV2(client, directory, logger);
343
+ if (!listed.success) return listed;
344
+ const sorted = listed.data.filter((session) => {
345
+ if (session.parentID != null || session.time.archived != null) return false;
346
+ if (fromDate != null && session.time.created < fromDate.getTime()) return false;
347
+ if (toDate != null && session.time.created > toDate.getTime()) return false;
348
+ return true;
349
+ }).toSorted((a, b) => b.time.updated - a.time.updated);
350
+ const limited = limit == null ? sorted : sorted.slice(0, limit);
351
+ logger.info("Listed V2 sessions", {
352
+ count: limited.length,
353
+ directory
354
+ });
355
+ return ok(limited);
356
+ }
357
+ function uniqueAgents(messages) {
358
+ const agents = /* @__PURE__ */ new Set();
359
+ for (const message of messages) if (message.agent != null) agents.add(message.agent);
360
+ return [...agents];
361
+ }
362
+ function searchMessages(messages, pattern, caseSensitive) {
363
+ const matches = [];
364
+ for (const message of messages) for (const part of message.parts) {
365
+ const index = (caseSensitive ? part.text : part.text.toLowerCase()).indexOf(pattern);
366
+ if (index === -1) continue;
367
+ const start = Math.max(0, index - EXCERPT_CONTEXT_CHARS);
368
+ const end = Math.min(part.text.length, index + pattern.length + EXCERPT_CONTEXT_CHARS);
369
+ matches.push({
370
+ messageId: message.id,
371
+ partId: part.id,
372
+ excerpt: `...${part.text.slice(start, end)}...`,
373
+ role: message.role,
374
+ ...message.agent == null ? {} : { agent: message.agent }
375
+ });
376
+ }
377
+ return matches;
378
+ }
379
+ async function searchSessionsV2(query, client, directory, options, logger) {
380
+ const { limit = 20, caseSensitive = false, sessionId, excludeSessionIds = [] } = options;
381
+ const excluded = new Set(excludeSessionIds);
382
+ const pattern = caseSensitive ? query : query.toLowerCase();
383
+ logger.debug("Searching V2 sessions", {
384
+ directory,
385
+ limit,
386
+ caseSensitive
387
+ });
388
+ if (sessionId != null) {
389
+ if (excluded.has(sessionId)) return ok([]);
390
+ const messages = await getSessionMessagesV2(client, sessionId, logger);
391
+ if (!messages.success) return messages;
392
+ const matches = searchMessages(messages.data, pattern, caseSensitive);
393
+ return ok(matches.length === 0 ? [] : [{
394
+ sessionId,
395
+ matches: matches.slice(0, limit)
396
+ }]);
397
+ }
398
+ const listed = await listSessionsV2(client, directory, {}, logger);
399
+ if (!listed.success) return listed;
400
+ const results = [];
401
+ let totalMatches = 0;
402
+ let attempted = 0;
403
+ let succeeded = 0;
404
+ let firstReadError;
405
+ for (const session of listed.data.filter((s) => !excluded.has(s.id)).slice(0, 100)) {
406
+ if (totalMatches >= limit) break;
407
+ attempted += 1;
408
+ const messages = await getSessionMessagesV2(client, session.id, logger);
409
+ if (!messages.success) {
410
+ firstReadError ??= messages.error;
411
+ continue;
412
+ }
413
+ succeeded += 1;
414
+ const matches = searchMessages(messages.data, pattern, caseSensitive);
415
+ if (matches.length === 0) continue;
416
+ const kept = matches.slice(0, limit - totalMatches);
417
+ results.push({
418
+ sessionId: session.id,
419
+ matches: kept
420
+ });
421
+ totalMatches += kept.length;
422
+ }
423
+ if (attempted > 0 && succeeded === 0 && firstReadError != null) return err(/* @__PURE__ */ new Error(`could not read any of ${attempted} sessions: ${firstReadError.message}`));
424
+ logger.info("V2 session search complete", {
425
+ resultCount: results.length,
426
+ totalMatches
427
+ });
428
+ return ok(results);
429
+ }
430
+ /** Resolves to `ok(null)` when the session does not exist. */
431
+ async function getSessionInfoV2(client, sessionId, logger) {
432
+ const session = await getSessionV2(client, sessionId, logger);
433
+ if (!session.success) return session;
434
+ if (session.data == null) return ok(null);
435
+ const messages = await getSessionMessagesV2(client, sessionId, logger);
436
+ if (!messages.success) return err(messages.error);
437
+ const todos = latestTodosV2(messages.data);
438
+ return ok({
439
+ session: session.data,
440
+ messageCount: messages.data.length,
441
+ agents: uniqueAgents(messages.data),
442
+ hasTodos: todos.length > 0,
443
+ todoCount: todos.length,
444
+ completedTodos: todos.filter((todo) => todo.status === "completed").length
445
+ });
446
+ }
447
+ // src/session-tools.ts
448
+ const UNAVAILABLE_PREFIX = "session store unavailable";
449
+ const REASON_MAX_CHARS = 200;
450
+ const SESSION_TOOL_NAMES = {
451
+ list: "session_list",
452
+ read: "session_read",
453
+ search: "session_search",
454
+ info: "session_info"
455
+ };
456
+ /** No-op logger: plugins have no logging channel. */
457
+ const silentLogger = {
458
+ debug: () => {},
459
+ info: () => {},
460
+ warning: () => {},
461
+ error: () => {}
462
+ };
463
+ function unavailable(reason) {
464
+ return `${UNAVAILABLE_PREFIX}: ${reason}`;
465
+ }
466
+ /** One line, capped. Effect tagged errors can have an empty message, so fall back to the tag. */
467
+ function describeFailure(error) {
468
+ let raw;
469
+ if (error instanceof Error) {
470
+ const tag = Reflect.get(error, "_tag");
471
+ raw = error.message.length > 0 ? error.message : typeof tag === "string" ? tag : error.name;
472
+ } else raw = typeof error === "string" ? error : "unknown error";
473
+ const firstLine = raw.split("\n")[0] ?? "";
474
+ return firstLine.length > REASON_MAX_CHARS ? `${firstLine.slice(0, REASON_MAX_CHARS)}...` : firstLine;
475
+ }
476
+ function asString(value) {
477
+ return typeof value === "string" && value.length > 0 ? value : void 0;
478
+ }
479
+ function asNumber(value) {
480
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
481
+ }
482
+ function asBoolean(value) {
483
+ return typeof value === "boolean" ? value : void 0;
484
+ }
485
+ function parseDate(value) {
486
+ if (value == null) return void 0;
487
+ const parsed = new Date(value);
488
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed;
489
+ }
490
+ /** Parses a `to_date` bound to the END of that day (inclusive upper bound). */
491
+ function parseEndOfDayDate(value) {
492
+ const parsed = parseDate(value);
493
+ if (parsed == null) return void 0;
494
+ const endOfDay = new Date(parsed);
495
+ endOfDay.setUTCHours(23, 59, 59, 999);
496
+ return endOfDay;
497
+ }
498
+ /** Any limit below 1 (including negative values) means "no limit". */
499
+ function normalizeLimit(value) {
500
+ return value == null || value < 1 ? void 0 : value;
501
+ }
502
+ function formatTimestamp(ms) {
503
+ return new Date(ms).toISOString();
504
+ }
505
+ function titleOf(session) {
506
+ return session.title.length > 0 ? session.title : "(untitled)";
507
+ }
508
+ function formatMessageForTranscript(message) {
509
+ const text = message.parts.map((part) => part.text).join(" ");
510
+ return text.length > 0 ? `[${message.role}] ${text}` : `[${message.role}] (no content)`;
511
+ }
512
+ /** Renders messages oldest-first, capping total rendered size so a huge transcript can't blow the response. */
513
+ function renderTranscript(messages) {
514
+ const lines = [];
515
+ let size = 0;
516
+ let shown = 0;
517
+ for (const message of messages) {
518
+ const line = ` ${formatMessageForTranscript(message)}`;
519
+ if (size + line.length > 48e3) break;
520
+ lines.push(line);
521
+ size += line.length;
522
+ shown += 1;
523
+ }
524
+ if (shown < messages.length) lines.push(` ... transcript truncated (${shown} of ${messages.length} messages shown)`);
525
+ return lines;
526
+ }
527
+ function sessionHeader(session) {
528
+ return [
529
+ `Session ${session.id}`,
530
+ `Title: ${titleOf(session)}`,
531
+ `Created: ${formatTimestamp(session.time.created)}`,
532
+ `Updated: ${formatTimestamp(session.time.updated)}`
533
+ ];
534
+ }
535
+ const CONTEXT_WINDOW_NOTE = "Covers the session's active context window: messages since its last compaction, plus the compaction summary.";
536
+ const ListInput = Schema.Struct({
537
+ limit: Schema.optionalKey(Schema.Number).annotate({ description: "Maximum number of sessions to return." }),
538
+ from_date: Schema.optionalKey(Schema.String).annotate({ description: "Only include sessions created on or after this date (YYYY-MM-DD)." }),
539
+ to_date: Schema.optionalKey(Schema.String).annotate({ description: "Only include sessions created on or before this date (YYYY-MM-DD)." }),
540
+ project_path: Schema.optionalKey(Schema.String).annotate({ description: "Workspace/project directory to list sessions for." })
541
+ });
542
+ const ReadInput = Schema.Struct({
543
+ session_id: Schema.String.annotate({ description: "The session id to read (required)." }),
544
+ include_todos: Schema.optionalKey(Schema.Boolean).annotate({ description: "Include the session todo list." }),
545
+ include_transcript: Schema.optionalKey(Schema.Boolean).annotate({ description: "Include the message transcript." }),
546
+ limit: Schema.optionalKey(Schema.Number).annotate({ description: "Maximum number of transcript messages to include." })
547
+ });
548
+ const SearchInput = Schema.Struct({
549
+ query: Schema.String.annotate({ description: "Text to search for (required)." }),
550
+ session_id: Schema.optionalKey(Schema.String).annotate({ description: "Restrict the search to a single session id." }),
551
+ case_sensitive: Schema.optionalKey(Schema.Boolean).annotate({ description: "Match case-sensitively." }),
552
+ limit: Schema.optionalKey(Schema.Number).annotate({ description: "Maximum number of matches to return." })
553
+ });
554
+ const InfoInput = Schema.Struct({ session_id: Schema.String.annotate({ description: "The session id to summarize (required)." }) });
555
+ /**
556
+ * Builds the four tool definitions against an injected client. `directory` is the workspace the tools default to:
557
+ * `session_list` honours a `project_path` override, `session_search` always searches the workspace.
558
+ */
559
+ function createSessionTools(options) {
560
+ const { client, directory } = options;
561
+ const logger = silentLogger;
562
+ return {
563
+ list: {
564
+ name: SESSION_TOOL_NAMES.list,
565
+ description: "List recent OpenCode sessions for the current workspace, most recently updated first.",
566
+ input: ListInput,
567
+ async run(args) {
568
+ try {
569
+ const sessions = await listSessionsV2(client, asString(args.project_path) ?? directory, {
570
+ limit: normalizeLimit(asNumber(args.limit)),
571
+ fromDate: parseDate(asString(args.from_date)),
572
+ toDate: parseEndOfDayDate(asString(args.to_date))
573
+ }, logger);
574
+ if (!sessions.success) return unavailable(describeFailure(sessions.error));
575
+ if (sessions.data.length === 0) return "No sessions found.";
576
+ return sessions.data.map((session) => `${session.id} ${titleOf(session)} updated ${formatTimestamp(session.time.updated)}`).join("\n");
577
+ } catch (error) {
578
+ return unavailable(describeFailure(error));
579
+ }
580
+ }
581
+ },
582
+ read: {
583
+ name: SESSION_TOOL_NAMES.read,
584
+ description: `Read a session: header, optional todos, and optional transcript. ${CONTEXT_WINDOW_NOTE}`,
585
+ input: ReadInput,
586
+ async run(args) {
587
+ const sessionId = asString(args.session_id);
588
+ if (sessionId == null) return unavailable("session_id is required");
589
+ try {
590
+ const found = await getSessionV2(client, sessionId, logger);
591
+ if (!found.success) return unavailable(describeFailure(found.error));
592
+ if (found.data == null) return `session not found: ${sessionId}`;
593
+ const lines = sessionHeader(found.data);
594
+ const includeTodos = asBoolean(args.include_todos) === true;
595
+ const includeTranscript = asBoolean(args.include_transcript) === true;
596
+ if (!includeTodos && !includeTranscript) return lines.join("\n");
597
+ const messages = await getSessionMessagesV2(client, sessionId, logger);
598
+ if (!messages.success) return unavailable(describeFailure(messages.error));
599
+ if (includeTodos) {
600
+ const todos = latestTodosV2(messages.data);
601
+ lines.push("", "Todos:");
602
+ if (todos.length === 0) lines.push(" (none)");
603
+ else for (const todo of todos) lines.push(` [${todo.status}] ${todo.content}`);
604
+ }
605
+ if (includeTranscript) {
606
+ const limit = normalizeLimit(asNumber(args.limit));
607
+ const sliced = limit == null ? messages.data : messages.data.slice(0, limit);
608
+ lines.push("", "Transcript:");
609
+ if (sliced.length === 0) lines.push(" (empty)");
610
+ else lines.push(...renderTranscript(sliced));
611
+ }
612
+ return lines.join("\n");
613
+ } catch (error) {
614
+ return unavailable(describeFailure(error));
615
+ }
616
+ }
617
+ },
618
+ search: {
619
+ name: SESSION_TOOL_NAMES.search,
620
+ description: `Search prior session content for matching text, optionally scoped to one session. ${CONTEXT_WINDOW_NOTE}`,
621
+ input: SearchInput,
622
+ async run(args) {
623
+ const query = asString(args.query);
624
+ if (query == null) return unavailable("query is required");
625
+ try {
626
+ const scopedSessionId = asString(args.session_id);
627
+ if (scopedSessionId != null) {
628
+ const found = await getSessionV2(client, scopedSessionId, logger);
629
+ if (!found.success) return unavailable(describeFailure(found.error));
630
+ if (found.data == null) return `session not found: ${scopedSessionId}`;
631
+ }
632
+ const results = await searchSessionsV2(query, client, directory, {
633
+ limit: normalizeLimit(asNumber(args.limit)),
634
+ caseSensitive: asBoolean(args.case_sensitive),
635
+ sessionId: scopedSessionId
636
+ }, logger);
637
+ if (!results.success) return unavailable(describeFailure(results.error));
638
+ if (results.data.length === 0) return "No matches found.";
639
+ const lines = [];
640
+ for (const result of results.data) {
641
+ lines.push(`Session ${result.sessionId}:`);
642
+ for (const match of result.matches) lines.push(` [${match.role}${match.agent == null ? "" : `/${match.agent}`}] ${match.excerpt}`);
643
+ }
644
+ return lines.join("\n");
645
+ } catch (error) {
646
+ return unavailable(describeFailure(error));
647
+ }
648
+ }
649
+ },
650
+ info: {
651
+ name: SESSION_TOOL_NAMES.info,
652
+ description: `Summarize a session: id, title, timestamps, message and todo counts. ${CONTEXT_WINDOW_NOTE}`,
653
+ input: InfoInput,
654
+ async run(args) {
655
+ const sessionId = asString(args.session_id);
656
+ if (sessionId == null) return unavailable("session_id is required");
657
+ try {
658
+ const details = await getSessionInfoV2(client, sessionId, logger);
659
+ if (!details.success) return unavailable(describeFailure(details.error));
660
+ if (details.data == null) return `session not found: ${sessionId}`;
661
+ const { session, messageCount, agents, hasTodos, todoCount, completedTodos } = details.data;
662
+ return [
663
+ ...sessionHeader(session),
664
+ `Messages: ${messageCount}`,
665
+ `Agents: ${agents.length > 0 ? agents.join(", ") : "(none)"}`,
666
+ `Todos: ${hasTodos ? `${completedTodos}/${todoCount} completed` : "(none)"}`
667
+ ].join("\n");
668
+ } catch (error) {
669
+ return unavailable(describeFailure(error));
670
+ }
671
+ }
672
+ }
673
+ };
674
+ }
675
+ // src/task-reuse-guard.ts
676
+ /** Rejects `subagent` calls that resume a child session via `sessionID`, via the `execute.before` tool hook. */
677
+ /** The model-visible rejection text; it carries no ids or arguments. */
678
+ const TASK_REUSE_REJECTION = "Session reuse is disabled in this environment. Start a new task and include the context it needs.";
679
+ /** 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 !== "";
684
+ }
685
+ function rejectSubagentReuse(event) {
686
+ if (event.tool !== "subagent") return;
687
+ if (carriesResume(event.input)) throw new Error(TASK_REUSE_REJECTION);
688
+ }
689
+ // src/tracing/settings.ts
690
+ /**
691
+ * Host mode and tracing settings: one function decides whether tracing is on and where spans go, and fails closed.
692
+ *
693
+ * This module sits OUTSIDE the lazy tracing chunk: it decides whether the chunk loads at all, so it must stay small and
694
+ * import nothing from the OpenTelemetry SDK. Resolving to off never evaluates the chunk.
695
+ *
696
+ * Where settings come from, and nowhere else:
697
+ * - The launcher variable `OPENCODE_FROBOT_TRACING`, set by whatever started the server (the Action, the workspace).
698
+ * - Otherwise, only in a local session, a user-scope file under the user's config directory.
699
+ * Plugin options, project config, the checkout, restored state and session content are never read.
700
+ *
701
+ * The user file names the machines it is for (`hosts`, required): a file synced to another machine, or left behind on a
702
+ * shared one, does nothing there. And a remote collector in it must be `https`, with the platform's certificate
703
+ * verification left on: the exporter sends the file's headers (a credential) to that URL, and the file has no switch to
704
+ * relax verification, to follow a redirect, or to use plain `http` anywhere but a loopback literal.
705
+ */
706
+ /**
707
+ * Name of the launcher variable. `OPENCODE_`-prefixed so the Action's environment filter admits it, and not ending in a
708
+ * denied suffix (`_TOKEN`, `_KEY`, `_SECRET`, `_PASSWORD`, …). It carries no credential: only host, on/off, a loopback
709
+ * relay address and run identity.
710
+ */
711
+ const TRACING_LAUNCHER_ENV = "OPENCODE_FROBOT_TRACING";
712
+ /** Variables a headless server (the Action, the workspace, any `opencode serve`) always has and a local session lacks. */
713
+ const HEADLESS_MARKERS = ["OPENCODE_PASSWORD", "OPENCODE_CONFIG_CONTENT"];
714
+ /**
715
+ * True when the command line is `opencode … serve … --stdio`: a server a parent process embeds (an SDK client, a gateway,
716
+ * the Action). `opencode serve --stdio` deletes `OPENCODE_PASSWORD` and `OPENCODE_SERVER_PASSWORD` from the process
717
+ * environment before a plugin loads (measured on 2.3.2), so such a server started with only a password shows none of the
718
+ * markers above. The command line is what still says so. A `serve` started by hand, or the background service
719
+ * (`serve --service`; `--stdio` cannot be combined with it), is not embedded: the user's file is consent for those too.
720
+ * The subcommand is the first non-option word after the program path; `--stdio` must come after it.
721
+ */
722
+ function isEmbeddedServe(argv) {
723
+ const rest = argv.slice(2);
724
+ const serve = rest.indexOf("serve");
725
+ return serve !== -1 && rest.slice(serve + 1).includes("--stdio");
726
+ }
727
+ /** The user file, relative to the user's config directory. Not under `opencode/`: OpenCode reads nothing from here. */
728
+ const USER_SETTINGS_RELATIVE_PATH = path.join("fro-bot", "opencode-plugin", "tracing.json");
729
+ const SILENT_REASONS = /* @__PURE__ */ new Set([
730
+ "action-off",
731
+ "workspace-host",
732
+ "unsupported-platform",
733
+ "no-settings-file",
734
+ "machine-not-listed"
735
+ ]);
736
+ const off = (reason) => ({
737
+ mode: "off",
738
+ reason
739
+ });
740
+ function isRecord(value) {
741
+ return typeof value === "object" && value !== null && !Array.isArray(value);
742
+ }
743
+ /** True when `value` has exactly the listed keys, no more and no fewer. */
744
+ function hasExactKeys(value, keys) {
745
+ return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
746
+ }
747
+ function hasControlCharacter(value) {
748
+ for (let index = 0; index < value.length; index += 1) {
749
+ const code = value.charCodeAt(index);
750
+ if (code < 32 || code === 127) return true;
751
+ }
752
+ return false;
753
+ }
754
+ /** `127.0.0.0/8` literals or `[::1]`. A hostname such as `localhost` is not accepted: it resolves through the host. */
755
+ function isLoopbackHostname(hostname) {
756
+ if (hostname === "[::1]") return true;
757
+ const octets = hostname.split(".");
758
+ return octets.length === 4 && octets[0] === "127" && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);
759
+ }
760
+ function parseUrl(value) {
761
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return void 0;
762
+ if (hasControlCharacter(value)) return void 0;
763
+ try {
764
+ const url = new URL(value);
765
+ if (url.username !== "" || url.password !== "" || url.hash !== "") return void 0;
766
+ return url;
767
+ } catch {
768
+ return;
769
+ }
770
+ }
771
+ /** The launcher's relay: plain HTTP to a loopback literal with an explicit port. */
772
+ function parseRelayUrl(value) {
773
+ const url = parseUrl(value);
774
+ if (url === void 0 || url.protocol !== "http:" || !isLoopbackHostname(url.hostname) || url.port === "") return;
775
+ if (url.search !== "") return void 0;
776
+ return url.href;
777
+ }
778
+ /** A user-file endpoint: HTTPS, or plain HTTP to a loopback literal. */
779
+ function parseCollectorUrl(value) {
780
+ const url = parseUrl(value);
781
+ if (url === void 0) return void 0;
782
+ if (url.protocol === "https:") return url;
783
+ if (url.protocol === "http:" && isLoopbackHostname(url.hostname)) return url;
784
+ }
785
+ function parseIdentity(value) {
786
+ if (!isRecord(value) || !hasExactKeys(value, [
787
+ "repository",
788
+ "runId",
789
+ "attempt",
790
+ "job",
791
+ "trigger"
792
+ ])) return void 0;
793
+ const fields = [];
794
+ for (const key of [
795
+ "repository",
796
+ "runId",
797
+ "attempt",
798
+ "job",
799
+ "trigger"
800
+ ]) {
801
+ const field = value[key];
802
+ if (typeof field !== "string" || field.length === 0 || field.length > 200) return void 0;
803
+ if (hasControlCharacter(field)) return void 0;
804
+ fields.push(field);
805
+ }
806
+ const [repository = "", runId = "", attempt = "", job = "", trigger = ""] = fields;
807
+ return {
808
+ repository,
809
+ runId,
810
+ attempt,
811
+ job,
812
+ trigger
813
+ };
814
+ }
815
+ /** Resolves the launcher variable's value. Pure: no environment, no file. */
816
+ function resolveLauncher(raw) {
817
+ if (raw.length === 0 || raw.length > 4096) return off("launcher-malformed");
818
+ let document;
819
+ try {
820
+ document = JSON.parse(raw);
821
+ } catch {
822
+ return off("launcher-malformed");
823
+ }
824
+ if (!isRecord(document)) return off("launcher-malformed");
825
+ if (document.version !== 1) return off("launcher-unsupported");
826
+ if (document.host === "workspace") return off("workspace-host");
827
+ if (document.host !== "action") return off("launcher-unsupported");
828
+ if (document.tracing === "off") return off("action-off");
829
+ if (document.tracing !== "on") return off("launcher-malformed");
830
+ if (!hasExactKeys(document, [
831
+ "version",
832
+ "host",
833
+ "tracing",
834
+ "relay",
835
+ "identity"
836
+ ])) return off("launcher-malformed");
837
+ const endpoint = parseRelayUrl(document.relay);
838
+ if (endpoint === void 0) return off("launcher-relay-invalid");
839
+ const identity = parseIdentity(document.identity);
840
+ if (identity === void 0) return off("launcher-identity-invalid");
841
+ return {
842
+ mode: "on",
843
+ host: "action",
844
+ endpoint,
845
+ identity
846
+ };
847
+ }
848
+ /** Header names the exporter or the transport owns. A user file cannot set them. */
849
+ const REFUSED_HEADER_NAMES = /* @__PURE__ */ new Set([
850
+ "host",
851
+ "content-length",
852
+ "content-type",
853
+ "content-encoding",
854
+ "transfer-encoding",
855
+ "connection",
856
+ "keep-alive",
857
+ "upgrade",
858
+ "te",
859
+ "trailer",
860
+ "expect",
861
+ "proxy-authorization",
862
+ "proxy-authenticate"
863
+ ]);
864
+ const HEADER_NAME = /^[\w!#$%&'*+.^`|~-]+$/;
865
+ function parseHeaders(value) {
866
+ if (value === void 0) return {};
867
+ if (!isRecord(value)) return void 0;
868
+ const entries = Object.entries(value);
869
+ if (entries.length > 16) return void 0;
870
+ const headers = {};
871
+ for (const [name, headerValue] of entries) {
872
+ const lower = name.toLowerCase();
873
+ if (name.length > 64 || !HEADER_NAME.test(name) || REFUSED_HEADER_NAMES.has(lower)) return void 0;
874
+ if (typeof headerValue !== "string" || headerValue.length === 0 || headerValue.length > 4096) return;
875
+ if (hasControlCharacter(headerValue) || Object.hasOwn(headers, lower)) return void 0;
876
+ headers[lower] = headerValue;
877
+ }
878
+ return headers;
879
+ }
880
+ /** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */
881
+ function userSettingsFilePath(env) {
882
+ const configured = env.XDG_CONFIG_HOME;
883
+ if (configured !== void 0 && path.isAbsolute(configured)) return path.join(configured, USER_SETTINGS_RELATIVE_PATH);
884
+ const home = env.HOME !== void 0 && path.isAbsolute(env.HOME) ? env.HOME : os.homedir();
885
+ return path.join(home, ".config", USER_SETTINGS_RELATIVE_PATH);
886
+ }
887
+ function errorCode(error) {
888
+ return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
889
+ }
890
+ function isInside(child, parent) {
891
+ const relative = path.relative(parent, child);
892
+ if (relative === "") return true;
893
+ return !(relative === ".." || relative.startsWith(`..${path.sep}`)) && !path.isAbsolute(relative);
894
+ }
895
+ /**
896
+ * Reads the user file, checking the OPENED handle: a regular file, owned by the current user, private to its owner (no group
897
+ * or other permission bit at all: it can hold a collector credential, so readable is as bad as writable), small, and whose
898
+ * real path is outside the project. A symlink is resolved first and its target is what gets opened and checked.
899
+ */
900
+ function readSettingsFile(filePath, directory, uid) {
901
+ let realPath;
902
+ try {
903
+ realPath = realpathSync(filePath);
904
+ } catch (error) {
905
+ const code = errorCode(error);
906
+ return {
907
+ ok: false,
908
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "no-settings-file" : "settings-file-unreadable"
909
+ };
910
+ }
911
+ let realDirectory;
912
+ try {
913
+ realDirectory = realpathSync(directory);
914
+ } catch {
915
+ realDirectory = path.resolve(directory);
916
+ }
917
+ if (isInside(realPath, realDirectory)) return {
918
+ ok: false,
919
+ reason: "settings-file-unsafe"
920
+ };
921
+ let fd;
922
+ try {
923
+ fd = openSync(realPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
924
+ } catch {
925
+ return {
926
+ ok: false,
927
+ reason: "settings-file-unreadable"
928
+ };
929
+ }
930
+ try {
931
+ const stat = fstatSync(fd);
932
+ if (!stat.isFile() || stat.uid !== uid || (stat.mode & 63) !== 0 || stat.size > 16384) return {
933
+ ok: false,
934
+ reason: "settings-file-unsafe"
935
+ };
936
+ const buffer = Buffer.alloc(stat.size);
937
+ let offset = 0;
938
+ while (offset < buffer.length) {
939
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
940
+ if (read === 0) break;
941
+ offset += read;
942
+ }
943
+ return {
944
+ ok: true,
945
+ text: buffer.subarray(0, offset).toString("utf8")
946
+ };
947
+ } catch {
948
+ return {
949
+ ok: false,
950
+ reason: "settings-file-unreadable"
951
+ };
952
+ } finally {
953
+ closeSync(fd);
954
+ }
955
+ }
956
+ /** A name as compared: trimmed, lower case, without one trailing dot. */
957
+ const normalizeHostname = (value) => {
958
+ const lower = value.trim().toLowerCase();
959
+ return lower.endsWith(".") ? lower.slice(0, -1) : lower;
960
+ };
961
+ /** Letters, digits, dot, hyphen and underscore: what a machine name holds. No wildcard, port, path or space. */
962
+ const HOSTNAME_ENTRY = /^[\da-z._-]+$/;
963
+ /** The `hosts` list: one to 16 names, each normalized. Undefined when the list or any entry is not acceptable. */
964
+ function parseHosts(value) {
965
+ if (!Array.isArray(value) || value.length === 0 || value.length > 16) return void 0;
966
+ const hosts = [];
967
+ for (const entry of value) {
968
+ if (typeof entry !== "string" || entry.length > 255) return void 0;
969
+ const host = normalizeHostname(entry);
970
+ if (host.length === 0 || host.length > 253 || !HOSTNAME_ENTRY.test(host)) return void 0;
971
+ hosts.push(host);
972
+ }
973
+ return hosts;
974
+ }
975
+ /**
976
+ * Whether `machine` is one of `hosts`. An entry matches the whole name, or the part of the name before its first dot. That
977
+ * part never holds a dot, so an entry with a dot can only ever match the whole name: `build-box.example.test` does not
978
+ * match a machine called `build-box`. No wildcards, no prefix or suffix matching.
979
+ */
980
+ function namesMachine(hosts, machine) {
981
+ const name = normalizeHostname(machine);
982
+ if (name.length === 0) return false;
983
+ const short = name.split(".")[0];
984
+ return hosts.some((host) => host === name || host === short);
985
+ }
986
+ function resolveSettingsFile(text, hostname) {
987
+ let document;
988
+ try {
989
+ document = JSON.parse(text);
990
+ } catch {
991
+ return { settings: off("settings-file-invalid") };
992
+ }
993
+ if (!isRecord(document) || document.version !== 1) return { settings: off("settings-file-invalid") };
994
+ const allowed = Object.keys(document).every((key) => key === "version" || key === "endpoint" || key === "headers" || key === "hosts");
995
+ const url = parseCollectorUrl(document.endpoint);
996
+ const headers = parseHeaders(document.headers);
997
+ const hosts = parseHosts(document.hosts);
998
+ if (!allowed || url === void 0 || headers === void 0 || hosts === void 0) return { settings: off("settings-file-invalid") };
999
+ if (!namesMachine(hosts, hostname())) return { settings: off("machine-not-listed") };
1000
+ return {
1001
+ settings: {
1002
+ mode: "on",
1003
+ host: "local",
1004
+ endpoint: url.href,
1005
+ headers
1006
+ },
1007
+ host: url.host
1008
+ };
1009
+ }
1010
+ /**
1011
+ * Decides whether tracing is on. Never throws. Logs at most one line: an off with a reason worth knowing, or, for a local
1012
+ * session, the destination host. Lines carry fixed text and a host name, never a header, a path or a settings value.
1013
+ */
1014
+ function resolveTracingSettings(input) {
1015
+ const { env, directory, log } = input;
1016
+ const finish = (settings) => {
1017
+ if (settings.mode === "off" && !SILENT_REASONS.has(settings.reason)) log(`tracing off (${settings.reason})`);
1018
+ return settings;
1019
+ };
1020
+ try {
1021
+ const launcher = env[TRACING_LAUNCHER_ENV];
1022
+ if (launcher !== void 0) return finish(resolveLauncher(launcher));
1023
+ if (HEADLESS_MARKERS.some((marker) => env[marker] !== void 0) || isEmbeddedServe(input.argv ?? process.argv)) return finish(off("headless-host"));
1024
+ const platform = input.platform ?? process.platform;
1025
+ const uid = input.uid ?? process.getuid?.();
1026
+ if (platform === "win32" || uid === void 0) return finish(off("unsupported-platform"));
1027
+ const file = readSettingsFile(userSettingsFilePath(env), directory, uid);
1028
+ if (!file.ok) return finish(off(file.reason));
1029
+ const resolved = resolveSettingsFile(file.text, input.hostname ?? os.hostname);
1030
+ if (resolved.settings.mode === "on" && resolved.host !== void 0) log(`tracing on, destination host ${resolved.host}`);
1031
+ return finish(resolved.settings);
1032
+ } catch {
1033
+ return finish(off("settings-error"));
1034
+ }
1035
+ }
1036
+ // src/setup.ts
1037
+ /**
1038
+ * The only way into the tracing chunk. Called only when settings resolved to on, so with tracing off the dynamic import never
1039
+ * runs and the chunk and the SDK inside it are never evaluated. Every step (the import, SDK construction, hook
1040
+ * registration, and later the cleanup) is wrapped: a failure leaves the plugin exactly as it was, and the one log line
1041
+ * names the failure class only, since an error message can carry a path or URL.
1042
+ */
1043
+ async function startTracing(host, settings, env, log) {
1044
+ try {
1045
+ const handle = await (await import("./tracing-D4bUTAUS.mjs")).startTracing({
1046
+ session: host.session,
1047
+ tool: { hook: async (name, callback) => name === "execute.before" ? host.tool.hook(name, callback) : host.tool.hook(name, callback) },
1048
+ event: host.event
1049
+ }, settings, {
1050
+ env,
1051
+ log
1052
+ });
1053
+ return async () => {
1054
+ try {
1055
+ await handle.stop();
1056
+ } catch (error) {
1057
+ log(`tracing cleanup failed (${error instanceof Error ? error.name : "unknown error"})`);
1058
+ }
1059
+ };
1060
+ } catch (error) {
1061
+ log(`tracing could not start (${error instanceof Error ? error.name : "unknown error"})`);
1062
+ return;
1063
+ }
1064
+ }
1065
+ async function setupFroBotPlugin(host, options = {}) {
1066
+ await host.tool.hook("execute.before", async (event) => {
1067
+ rejectSubagentReuse(event);
1068
+ });
1069
+ const tools = createSessionTools({
1070
+ client: createPluginSessionClient(host.session),
1071
+ directory: host.location.directory
1072
+ });
1073
+ await host.tool.transform((editor) => {
1074
+ for (const spec of [
1075
+ tools.list,
1076
+ tools.read,
1077
+ tools.search,
1078
+ tools.info
1079
+ ]) {
1080
+ const tool = {
1081
+ name: spec.name,
1082
+ options: { codemode: false },
1083
+ description: spec.description,
1084
+ input: spec.input,
1085
+ execute: async (input) => ({ content: await spec.run(input) })
1086
+ };
1087
+ editor.add(tool);
1088
+ }
1089
+ });
1090
+ const log = options.log ?? logPluginLine;
1091
+ const settings = resolveTracingSettings({
1092
+ env: options.env ?? process.env,
1093
+ directory: host.location.directory,
1094
+ log
1095
+ });
1096
+ if (settings.mode !== "on") return void 0;
1097
+ return startTracing(host, settings, options.env ?? process.env, log);
1098
+ }
1099
+ // src/index.ts
1100
+ /** `@fro.bot/opencode-plugin`: the session tools and the subagent session-reuse guard. */
1101
+ var src_default = Plugin.define({
1102
+ id: FRO_BOT_PLUGIN_ID,
1103
+ setup: async (ctx) => setupFroBotPlugin(ctx)
1104
+ });
1105
+ export { FRO_BOT_PLUGIN_ID, src_default as default };
1106
+
1107
+ //# sourceMappingURL=index.mjs.map