@fro.bot/opencode-plugin 0.1.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/dist/index.mjs CHANGED
@@ -1,8 +1,24 @@
1
1
  import { Plugin } from "@opencode/plugin";
2
+ import process from "node:process";
2
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";
3
8
  // src/plugin-id.ts
4
9
  /** Stable plugin id; the surfaces look it up in `GET /api/plugin` to confirm the plugin is active. */
5
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
+ }
6
22
  // src/session-client.ts
7
23
  const SESSION_ID_PREFIX = "ses";
8
24
  const NOT_FOUND_TAG = "Session.NotFoundError";
@@ -38,21 +54,21 @@ function err(error) {
38
54
  };
39
55
  }
40
56
  // ../runtime/src/session/storage-mappers-v2.ts
41
- const isRecord = (v) => typeof v === "object" && v != null;
57
+ const isRecord$1 = (v) => typeof v === "object" && v != null;
42
58
  const readString = (v) => typeof v === "string" ? v : null;
43
59
  const readNumber = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
44
60
  /** Strips a `{data}` envelope. A bare payload passes through. */
45
61
  function unwrapData(v) {
46
- return isRecord(v) && !Array.isArray(v) && "data" in v ? v.data : v;
62
+ return isRecord$1(v) && !Array.isArray(v) && "data" in v ? v.data : v;
47
63
  }
48
64
  function mapSessionInfoV2(v) {
49
65
  const payload = unwrapData(v);
50
- if (!isRecord(payload) || Array.isArray(payload)) return null;
66
+ if (!isRecord$1(payload) || Array.isArray(payload)) return null;
51
67
  const id = readString(payload.id);
52
68
  const projectID = readString(payload.projectID);
53
69
  const time = payload.time;
54
70
  const location = payload.location;
55
- if (id == null || projectID == null || !isRecord(time) || !isRecord(location)) return null;
71
+ if (id == null || projectID == null || !isRecord$1(time) || !isRecord$1(location)) return null;
56
72
  const created = readNumber(time.created);
57
73
  const updated = readNumber(time.updated);
58
74
  const directory = readString(location.directory);
@@ -77,15 +93,15 @@ function mapSessionInfoV2(v) {
77
93
  * for "no sessions". Entries that fail to map are dropped.
78
94
  */
79
95
  function mapSessionPageV2(v) {
80
- const items = Array.isArray(v) ? v : isRecord(v) && Array.isArray(v.data) ? v.data : null;
96
+ const items = Array.isArray(v) ? v : isRecord$1(v) && Array.isArray(v.data) ? v.data : null;
81
97
  if (items == null) return null;
82
98
  const sessions = [];
83
99
  for (const item of items) {
84
100
  const mapped = mapSessionInfoV2(item);
85
101
  if (mapped != null) sessions.push(mapped);
86
102
  }
87
- const cursor = isRecord(v) ? v.cursor : void 0;
88
- const nextCursor = isRecord(cursor) ? readString(cursor.next) : null;
103
+ const cursor = isRecord$1(v) ? v.cursor : void 0;
104
+ const nextCursor = isRecord$1(cursor) ? readString(cursor.next) : null;
89
105
  return {
90
106
  sessions,
91
107
  ...nextCursor == null || nextCursor.length === 0 ? {} : { nextCursor }
@@ -109,17 +125,17 @@ function textPart(messageID, index, kind, text) {
109
125
  /** Joins the text items of a tool result. File items carry no searchable text. */
110
126
  function readToolText(content) {
111
127
  if (!Array.isArray(content)) return null;
112
- const texts = content.filter(isRecord).flatMap((item) => {
128
+ const texts = content.filter(isRecord$1).flatMap((item) => {
113
129
  const text = item.type === "text" ? readString(item.text) : null;
114
130
  return text == null ? [] : [text];
115
131
  });
116
132
  return texts.length === 0 ? null : texts.join("\n");
117
133
  }
118
134
  function readTodos(input) {
119
- if (!isRecord(input) || !Array.isArray(input.todos)) return null;
135
+ if (!isRecord$1(input) || !Array.isArray(input.todos)) return null;
120
136
  const todos = [];
121
137
  for (const item of input.todos) {
122
- if (!isRecord(item)) continue;
138
+ if (!isRecord$1(item)) continue;
123
139
  const content = readString(item.content);
124
140
  if (content == null) continue;
125
141
  const status = TODO_STATUSES.find((candidate) => candidate === item.status);
@@ -135,7 +151,7 @@ function mapAssistantContent(messageID, content) {
135
151
  const parts = [];
136
152
  let todos;
137
153
  for (const item of content) {
138
- if (!isRecord(item)) continue;
154
+ if (!isRecord$1(item)) continue;
139
155
  const index = parts.length;
140
156
  if (item.type === "text") {
141
157
  const text = readString(item.text);
@@ -143,7 +159,7 @@ function mapAssistantContent(messageID, content) {
143
159
  } else if (item.type === "reasoning") {
144
160
  const text = readString(item.text);
145
161
  if (text != null) parts.push(textPart(messageID, index, "reasoning", text));
146
- } else if (item.type === "tool" && isRecord(item.state) && item.state.status === "completed") {
162
+ } else if (item.type === "tool" && isRecord$1(item.state) && item.state.status === "completed") {
147
163
  const name = readString(item.name);
148
164
  const output = readToolText(item.state.content);
149
165
  if (name != null && output != null) parts.push(textPart(messageID, index, "tool", `${name}: ${output}`));
@@ -156,10 +172,10 @@ function mapAssistantContent(messageID, content) {
156
172
  };
157
173
  }
158
174
  function mapMessageV2(v) {
159
- if (!isRecord(v)) return null;
175
+ if (!isRecord$1(v)) return null;
160
176
  const id = readString(v.id);
161
177
  const time = v.time;
162
- const createdAt = isRecord(time) ? readNumber(time.created) : null;
178
+ const createdAt = isRecord$1(time) ? readNumber(time.created) : null;
163
179
  if (id == null || createdAt == null) return null;
164
180
  if (v.type === "user" || v.type === "synthetic") {
165
181
  const text = readString(v.text);
@@ -235,6 +251,9 @@ function toError(error) {
235
251
  const SESSION_LIST_PAGE_SIZE = 100;
236
252
  /** Lists root, unarchived sessions created in `directory` (exact string match), newest first, up to a page bound. */
237
253
  async function listSessionsForDirectoryV2(client, directory, logger) {
254
+ return listRootSessionsV2(client, directory, logger, false);
255
+ }
256
+ async function listRootSessionsV2(client, directory, logger, archivedOnly) {
238
257
  const sessions = [];
239
258
  let cursor;
240
259
  for (let page = 0; page < 10; page += 1) {
@@ -245,7 +264,7 @@ async function listSessionsForDirectoryV2(client, directory, logger) {
245
264
  limit: SESSION_LIST_PAGE_SIZE,
246
265
  order: "desc",
247
266
  parentID: null,
248
- archived: false,
267
+ archived: archivedOnly,
249
268
  ...cursor == null ? {} : { cursor }
250
269
  });
251
270
  } catch (error) {
@@ -667,8 +686,433 @@ function rejectSubagentReuse(event) {
667
686
  if (event.tool !== "subagent") return;
668
687
  if (carriesResume(event.input)) throw new Error(TASK_REUSE_REJECTION);
669
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 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));
750
+ }
751
+ function hasControlCharacter(value) {
752
+ for (let index = 0; index < value.length; index += 1) {
753
+ const code = value.charCodeAt(index);
754
+ if (code < 32 || code === 127) return true;
755
+ }
756
+ return false;
757
+ }
758
+ /** `127.0.0.0/8` literals or `[::1]`. A hostname such as `localhost` is not accepted: it resolves through the host. */
759
+ function isLoopbackHostname(hostname) {
760
+ if (hostname === "[::1]") return true;
761
+ const octets = hostname.split(".");
762
+ return octets.length === 4 && octets[0] === "127" && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);
763
+ }
764
+ function parseUrl(value) {
765
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return void 0;
766
+ if (hasControlCharacter(value)) return void 0;
767
+ try {
768
+ const url = new URL(value);
769
+ if (url.username !== "" || url.password !== "" || url.hash !== "") return void 0;
770
+ return url;
771
+ } catch {
772
+ return;
773
+ }
774
+ }
775
+ /** The launcher's relay: plain HTTP to a loopback literal with an explicit port. */
776
+ function parseRelayUrl(value) {
777
+ const url = parseUrl(value);
778
+ if (url === void 0 || url.protocol !== "http:" || !isLoopbackHostname(url.hostname) || url.port === "") return;
779
+ if (url.search !== "") return void 0;
780
+ return url.href;
781
+ }
782
+ /** A user-file endpoint: HTTPS, or plain HTTP to a loopback literal. */
783
+ function parseCollectorUrl(value) {
784
+ const url = parseUrl(value);
785
+ if (url === void 0) return void 0;
786
+ if (url.protocol === "https:") return url;
787
+ if (url.protocol === "http:" && isLoopbackHostname(url.hostname)) return url;
788
+ }
789
+ function parseIdentity(value) {
790
+ if (!isRecord(value) || !hasExactKeys(value, [
791
+ "repository",
792
+ "runId",
793
+ "attempt",
794
+ "job",
795
+ "trigger"
796
+ ])) return void 0;
797
+ const fields = [];
798
+ for (const key of [
799
+ "repository",
800
+ "runId",
801
+ "attempt",
802
+ "job",
803
+ "trigger"
804
+ ]) {
805
+ const field = value[key];
806
+ if (typeof field !== "string" || field.length === 0 || field.length > 200) return void 0;
807
+ if (hasControlCharacter(field)) return void 0;
808
+ fields.push(field);
809
+ }
810
+ const [repository = "", runId = "", attempt = "", job = "", trigger = ""] = fields;
811
+ return {
812
+ repository,
813
+ runId,
814
+ attempt,
815
+ job,
816
+ trigger
817
+ };
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
+ }
858
+ /** Resolves the launcher variable's value. Pure: no environment, no file. */
859
+ function resolveLauncher(raw) {
860
+ if (raw.length === 0 || raw.length > 4096) return off("launcher-malformed");
861
+ let document;
862
+ try {
863
+ document = JSON.parse(raw);
864
+ } catch {
865
+ return off("launcher-malformed");
866
+ }
867
+ if (!isRecord(document)) return off("launcher-malformed");
868
+ if (document.version !== 1) return off("launcher-unsupported");
869
+ if (document.host === "workspace") return off("workspace-host");
870
+ if (document.host !== "action") return off("launcher-unsupported");
871
+ if (document.tracing === "off") return off("action-off");
872
+ if (document.tracing !== "on") return off("launcher-malformed");
873
+ if (!hasKeys(document, [
874
+ "version",
875
+ "host",
876
+ "tracing",
877
+ "relay",
878
+ "identity"
879
+ ], [
880
+ "rootSpan",
881
+ "sessionId",
882
+ "invocationId"
883
+ ])) return off("launcher-malformed");
884
+ const endpoint = parseRelayUrl(document.relay);
885
+ if (endpoint === void 0) return off("launcher-relay-invalid");
886
+ const identity = parseIdentity(document.identity);
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");
890
+ return {
891
+ mode: "on",
892
+ host: "action",
893
+ endpoint,
894
+ identity,
895
+ ...run
896
+ };
897
+ }
898
+ /** Header names the exporter or the transport owns. A user file cannot set them. */
899
+ const REFUSED_HEADER_NAMES = /* @__PURE__ */ new Set([
900
+ "host",
901
+ "content-length",
902
+ "content-type",
903
+ "content-encoding",
904
+ "transfer-encoding",
905
+ "connection",
906
+ "keep-alive",
907
+ "upgrade",
908
+ "te",
909
+ "trailer",
910
+ "expect",
911
+ "proxy-authorization",
912
+ "proxy-authenticate"
913
+ ]);
914
+ const HEADER_NAME = /^[\w!#$%&'*+.^`|~-]+$/;
915
+ function parseHeaders(value) {
916
+ if (value === void 0) return {};
917
+ if (!isRecord(value)) return void 0;
918
+ const entries = Object.entries(value);
919
+ if (entries.length > 16) return void 0;
920
+ const headers = {};
921
+ for (const [name, headerValue] of entries) {
922
+ const lower = name.toLowerCase();
923
+ if (name.length > 64 || !HEADER_NAME.test(name) || REFUSED_HEADER_NAMES.has(lower)) return void 0;
924
+ if (typeof headerValue !== "string" || headerValue.length === 0 || headerValue.length > 4096) return;
925
+ if (hasControlCharacter(headerValue) || Object.hasOwn(headers, lower)) return void 0;
926
+ headers[lower] = headerValue;
927
+ }
928
+ return headers;
929
+ }
930
+ /** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */
931
+ function userSettingsFilePath(env) {
932
+ const configured = env.XDG_CONFIG_HOME;
933
+ if (configured !== void 0 && path.isAbsolute(configured)) return path.join(configured, USER_SETTINGS_RELATIVE_PATH);
934
+ const home = env.HOME !== void 0 && path.isAbsolute(env.HOME) ? env.HOME : os.homedir();
935
+ return path.join(home, ".config", USER_SETTINGS_RELATIVE_PATH);
936
+ }
937
+ function errorCode(error) {
938
+ return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
939
+ }
940
+ function isInside(child, parent) {
941
+ const relative = path.relative(parent, child);
942
+ if (relative === "") return true;
943
+ return !(relative === ".." || relative.startsWith(`..${path.sep}`)) && !path.isAbsolute(relative);
944
+ }
945
+ /**
946
+ * Reads the user file, checking the OPENED handle: a regular file, owned by the current user, private to its owner (no group
947
+ * or other permission bit at all: it can hold a collector credential, so readable is as bad as writable), small, and whose
948
+ * real path is outside the project. A symlink is resolved first and its target is what gets opened and checked.
949
+ */
950
+ function readSettingsFile(filePath, directory, uid) {
951
+ let realPath;
952
+ try {
953
+ realPath = realpathSync(filePath);
954
+ } catch (error) {
955
+ const code = errorCode(error);
956
+ return {
957
+ ok: false,
958
+ reason: code === "ENOENT" || code === "ENOTDIR" ? "no-settings-file" : "settings-file-unreadable"
959
+ };
960
+ }
961
+ let realDirectory;
962
+ try {
963
+ realDirectory = realpathSync(directory);
964
+ } catch {
965
+ realDirectory = path.resolve(directory);
966
+ }
967
+ if (isInside(realPath, realDirectory)) return {
968
+ ok: false,
969
+ reason: "settings-file-unsafe"
970
+ };
971
+ let fd;
972
+ try {
973
+ fd = openSync(realPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
974
+ } catch {
975
+ return {
976
+ ok: false,
977
+ reason: "settings-file-unreadable"
978
+ };
979
+ }
980
+ try {
981
+ const stat = fstatSync(fd);
982
+ if (!stat.isFile() || stat.uid !== uid || (stat.mode & 63) !== 0 || stat.size > 16384) return {
983
+ ok: false,
984
+ reason: "settings-file-unsafe"
985
+ };
986
+ const buffer = Buffer.alloc(stat.size);
987
+ let offset = 0;
988
+ while (offset < buffer.length) {
989
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
990
+ if (read === 0) break;
991
+ offset += read;
992
+ }
993
+ return {
994
+ ok: true,
995
+ text: buffer.subarray(0, offset).toString("utf8")
996
+ };
997
+ } catch {
998
+ return {
999
+ ok: false,
1000
+ reason: "settings-file-unreadable"
1001
+ };
1002
+ } finally {
1003
+ closeSync(fd);
1004
+ }
1005
+ }
1006
+ /** A name as compared: trimmed, lower case, without one trailing dot. */
1007
+ const normalizeHostname = (value) => {
1008
+ const lower = value.trim().toLowerCase();
1009
+ return lower.endsWith(".") ? lower.slice(0, -1) : lower;
1010
+ };
1011
+ /** Letters, digits, dot, hyphen and underscore: what a machine name holds. No wildcard, port, path or space. */
1012
+ const HOSTNAME_ENTRY = /^[\da-z._-]+$/;
1013
+ /** The `hosts` list: one to 16 names, each normalized. Undefined when the list or any entry is not acceptable. */
1014
+ function parseHosts(value) {
1015
+ if (!Array.isArray(value) || value.length === 0 || value.length > 16) return void 0;
1016
+ const hosts = [];
1017
+ for (const entry of value) {
1018
+ if (typeof entry !== "string" || entry.length > 255) return void 0;
1019
+ const host = normalizeHostname(entry);
1020
+ if (host.length === 0 || host.length > 253 || !HOSTNAME_ENTRY.test(host)) return void 0;
1021
+ hosts.push(host);
1022
+ }
1023
+ return hosts;
1024
+ }
1025
+ /**
1026
+ * Whether `machine` is one of `hosts`. An entry matches the whole name, or the part of the name before its first dot. That
1027
+ * part never holds a dot, so an entry with a dot can only ever match the whole name: `build-box.example.test` does not
1028
+ * match a machine called `build-box`. No wildcards, no prefix or suffix matching.
1029
+ */
1030
+ function namesMachine(hosts, machine) {
1031
+ const name = normalizeHostname(machine);
1032
+ if (name.length === 0) return false;
1033
+ const short = name.split(".")[0];
1034
+ return hosts.some((host) => host === name || host === short);
1035
+ }
1036
+ function resolveSettingsFile(text, hostname) {
1037
+ let document;
1038
+ try {
1039
+ document = JSON.parse(text);
1040
+ } catch {
1041
+ return { settings: off("settings-file-invalid") };
1042
+ }
1043
+ if (!isRecord(document) || document.version !== 1) return { settings: off("settings-file-invalid") };
1044
+ const allowed = Object.keys(document).every((key) => key === "version" || key === "endpoint" || key === "headers" || key === "hosts");
1045
+ const url = parseCollectorUrl(document.endpoint);
1046
+ const headers = parseHeaders(document.headers);
1047
+ const hosts = parseHosts(document.hosts);
1048
+ if (!allowed || url === void 0 || headers === void 0 || hosts === void 0) return { settings: off("settings-file-invalid") };
1049
+ if (!namesMachine(hosts, hostname())) return { settings: off("machine-not-listed") };
1050
+ return {
1051
+ settings: {
1052
+ mode: "on",
1053
+ host: "local",
1054
+ endpoint: url.href,
1055
+ headers
1056
+ },
1057
+ host: url.host
1058
+ };
1059
+ }
1060
+ /**
1061
+ * Decides whether tracing is on. Never throws. Logs at most one line: an off with a reason worth knowing, or, for a local
1062
+ * session, the destination host. Lines carry fixed text and a host name, never a header, a path or a settings value.
1063
+ */
1064
+ function resolveTracingSettings(input) {
1065
+ const { env, directory, log } = input;
1066
+ const finish = (settings) => {
1067
+ if (settings.mode === "off" && !SILENT_REASONS.has(settings.reason)) log(`tracing off (${settings.reason})`);
1068
+ return settings;
1069
+ };
1070
+ try {
1071
+ const launcher = env[TRACING_LAUNCHER_ENV];
1072
+ if (launcher !== void 0) return finish(resolveLauncher(launcher));
1073
+ if (HEADLESS_MARKERS.some((marker) => env[marker] !== void 0) || isEmbeddedServe(input.argv ?? process.argv)) return finish(off("headless-host"));
1074
+ const platform = input.platform ?? process.platform;
1075
+ const uid = input.uid ?? process.getuid?.();
1076
+ if (platform === "win32" || uid === void 0) return finish(off("unsupported-platform"));
1077
+ const file = readSettingsFile(userSettingsFilePath(env), directory, uid);
1078
+ if (!file.ok) return finish(off(file.reason));
1079
+ const resolved = resolveSettingsFile(file.text, input.hostname ?? os.hostname);
1080
+ if (resolved.settings.mode === "on" && resolved.host !== void 0) log(`tracing on, destination host ${resolved.host}`);
1081
+ return finish(resolved.settings);
1082
+ } catch {
1083
+ return finish(off("settings-error"));
1084
+ }
1085
+ }
670
1086
  // src/setup.ts
671
- async function setupFroBotPlugin(host) {
1087
+ /**
1088
+ * The only way into the tracing chunk. Called only when settings resolved to on, so with tracing off the dynamic import never
1089
+ * runs and the chunk and the SDK inside it are never evaluated. Every step (the import, SDK construction, hook
1090
+ * registration, and later the cleanup) is wrapped: a failure leaves the plugin exactly as it was, and the one log line
1091
+ * names the failure class only, since an error message can carry a path or URL.
1092
+ */
1093
+ async function startTracing(host, settings, env, log) {
1094
+ try {
1095
+ const handle = await (await import("./tracing-DMDmxAqE.mjs")).startTracing({
1096
+ session: host.session,
1097
+ tool: { hook: async (name, callback) => name === "execute.before" ? host.tool.hook(name, callback) : host.tool.hook(name, callback) },
1098
+ event: host.event
1099
+ }, settings, {
1100
+ env,
1101
+ log
1102
+ });
1103
+ return async () => {
1104
+ try {
1105
+ await handle.stop();
1106
+ } catch (error) {
1107
+ log(`tracing cleanup failed (${error instanceof Error ? error.name : "unknown error"})`);
1108
+ }
1109
+ };
1110
+ } catch (error) {
1111
+ log(`tracing could not start (${error instanceof Error ? error.name : "unknown error"})`);
1112
+ return;
1113
+ }
1114
+ }
1115
+ async function setupFroBotPlugin(host, options = {}) {
672
1116
  await host.tool.hook("execute.before", async (event) => {
673
1117
  rejectSubagentReuse(event);
674
1118
  });
@@ -693,6 +1137,14 @@ async function setupFroBotPlugin(host) {
693
1137
  editor.add(tool);
694
1138
  }
695
1139
  });
1140
+ const log = options.log ?? logPluginLine;
1141
+ const settings = resolveTracingSettings({
1142
+ env: options.env ?? process.env,
1143
+ directory: host.location.directory,
1144
+ log
1145
+ });
1146
+ if (settings.mode !== "on") return void 0;
1147
+ return startTracing(host, settings, options.env ?? process.env, log);
696
1148
  }
697
1149
  // src/index.ts
698
1150
  /** `@fro.bot/opencode-plugin`: the session tools and the subagent session-reuse guard. */