@fro.bot/opencode-plugin 0.3.7 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,12 @@
1
1
  import { Buffer as Buffer$1 } from "node:buffer";
2
- import { readFileSync } from "node:fs";
2
+ import { constants, readFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
4
  import { inspect } from "node:util";
4
5
  import * as zlib from "node:zlib";
5
6
  import { Readable } from "node:stream";
6
7
  import { randomBytes } from "node:crypto";
8
+ import { open } from "node:fs/promises";
9
+ import { performance as performance$1 } from "node:perf_hooks";
7
10
  // ../../node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
8
11
  /** only globals that common to node and browsers are allowed */
9
12
  var _globalThis = typeof globalThis === "object" ? globalThis : global;
@@ -5073,6 +5076,304 @@ const actionIdentityAttributes = (identity, invocationId, serverUrl) => ({
5073
5076
  "langfuse.trace.metadata.invocation_id": invocationId
5074
5077
  }
5075
5078
  });
5079
+ // src/tracing/git-remote.ts
5080
+ /**
5081
+ * The repository a local session works in, as the `owner/repo` of its checkout's `origin` remote on github.com.
5082
+ *
5083
+ * A DECLARED label, never an input to anything: a checkout can point `origin` anywhere, so only a validated slug is ever
5084
+ * returned, and it is exported through the same scrub as every other attribute. It is read from the checkout's git files with
5085
+ * `node:fs/promises` alone (no `git` process, no network), asynchronously and under one time budget per directory, and nothing
5086
+ * ever waits for it: every failure, and an answer that is not ready, leave it unset.
5087
+ */
5088
+ /** A remote longer than this is not a remote anyone typed. */
5089
+ const MAX_REMOTE_CHARS = 512;
5090
+ /** GitHub's rules: an owner is 1 to 39 letters, digits and hyphens, not starting or ending with a hyphen. */
5091
+ const OWNER = /^[A-Z\d](?:[A-Z\d-]{0,37}[A-Z\d])?$/i;
5092
+ /** A repository is 1 to 100 letters, digits, hyphens, underscores and dots; `.`, `..` and `.git` are reserved. */
5093
+ const REPOSITORY = /^[\w.-]{1,100}$/;
5094
+ const RESERVED_REPOSITORIES = /* @__PURE__ */ new Set([
5095
+ ".",
5096
+ "..",
5097
+ ".git"
5098
+ ]);
5099
+ /**
5100
+ * The three github.com forms, and nothing else. Each captures owner and repo and allows an optional `.git` and trailing slash.
5101
+ * An https remote may carry userinfo (it is read past, never returned); an ssh remote's user is `git`. No port, query or fragment.
5102
+ */
5103
+ const REMOTE_FORMS = [
5104
+ /^https:\/\/(?:[^\s/@]+@)?github\.com\/([^\s/]+)\/([^\s/]+?)(?:\.git)?\/?$/i,
5105
+ /^ssh:\/\/git@github\.com\/([^\s/]+)\/([^\s/]+?)(?:\.git)?\/?$/i,
5106
+ /^git@github\.com:([^\s/]+)\/([^\s/]+?)(?:\.git)?\/?$/i
5107
+ ];
5108
+ /** `owner/repo` of a github.com remote, or `undefined` for any other host, form or name. */
5109
+ function slugFromRemote(remote) {
5110
+ if (remote.length === 0 || remote.length > MAX_REMOTE_CHARS) return void 0;
5111
+ for (const form of REMOTE_FORMS) {
5112
+ const match = form.exec(remote);
5113
+ if (match === null) continue;
5114
+ const [, owner, repository] = match;
5115
+ if (owner === void 0 || repository === void 0) return void 0;
5116
+ if (!OWNER.test(owner) || !REPOSITORY.test(repository) || RESERVED_REPOSITORIES.has(repository)) return void 0;
5117
+ return `${owner}/${repository}`;
5118
+ }
5119
+ }
5120
+ /** The most of a git config read. Past it, the rest is not looked at: a url there is not found rather than guessed. */
5121
+ const MAX_CONFIG_BYTES = 65536;
5122
+ /** A `.git` pointer file or `commondir` is a path. */
5123
+ const MAX_POINTER_BYTES = 4096;
5124
+ /** How many parent directories are tried for a `.git`. A session may start in a subdirectory of its checkout. */
5125
+ const MAX_PARENTS = 32;
5126
+ const NONBLOCKING = Number(constants.O_NONBLOCK) || 0;
5127
+ const NO_FOLLOW = Number(constants.O_NOFOLLOW) || 0;
5128
+ /**
5129
+ * Opens `path` once and says what it is, reading it only if it is a regular file (the first `limit` bytes).
5130
+ *
5131
+ * The open is `O_RDONLY | O_NONBLOCK | O_NOFOLLOW`: a named pipe opens at once instead of waiting for a writer (a wait would hold
5132
+ * one of the few threads the runtime does file work on, for as long as the pipe lives), and a symlink is refused, so nothing but the
5133
+ * path's own file is ever read. The kind comes from `fstat` of the handle, never from a look at the path before the open, so
5134
+ * there is no gap for the path to change in: a pipe, a directory or any other kind of file is closed unread. A missing path is
5135
+ * `missing`; every other failure is `unreadable`. Never throws.
5136
+ */
5137
+ async function probe(path, limit) {
5138
+ let handle;
5139
+ try {
5140
+ handle = await open(path, constants.O_RDONLY | NONBLOCKING | NO_FOLLOW);
5141
+ const stats = await handle.stat();
5142
+ if (stats.isDirectory()) return { kind: "directory" };
5143
+ if (!stats.isFile()) return { kind: "unreadable" };
5144
+ const buffer = Buffer$1.alloc(limit + 1);
5145
+ const { bytesRead } = await handle.read(buffer, 0, limit + 1, 0);
5146
+ return {
5147
+ kind: "file",
5148
+ content: {
5149
+ text: buffer.toString("utf8", 0, Math.min(bytesRead, limit)),
5150
+ truncated: bytesRead > limit
5151
+ }
5152
+ };
5153
+ } catch (error) {
5154
+ return { kind: error.code === "ENOENT" ? "missing" : "unreadable" };
5155
+ } finally {
5156
+ try {
5157
+ await handle?.close();
5158
+ } catch {}
5159
+ }
5160
+ }
5161
+ /** The first `limit` bytes of a REGULAR file as text, or `undefined` for anything else or any failure. Never throws, never waits. */
5162
+ async function readRegularFile(path, limit) {
5163
+ const found = await probe(path, limit);
5164
+ return found.kind === "file" ? found.content : void 0;
5165
+ }
5166
+ /** A path a git file names, resolved against the directory of that file when it is relative. */
5167
+ const resolveFrom = (base, path) => isAbsolute(path) ? path : resolve(base, path);
5168
+ /** The directory a `.git` file's `gitdir:` line points at, relative to the checkout when it is not absolute. */
5169
+ function gitdirPointer(checkout, content) {
5170
+ const pointer = content.text.split(/\r?\n/).find((line) => line.startsWith("gitdir:"))?.slice(7).trim();
5171
+ return pointer === void 0 || pointer === "" ? void 0 : resolveFrom(checkout, pointer);
5172
+ }
5173
+ /**
5174
+ * Where the `config` of a git directory lives: a linked worktree's `commondir` names the main one, relative to it. A `commondir`
5175
+ * that exists but is not a plain file (a named pipe, a link, a directory) leaves the config's place unknown, and the answer is
5176
+ * `undefined`: the git directory's own `config` is not the one git would use.
5177
+ */
5178
+ async function configPathOf(gitDirectory) {
5179
+ const found = await probe(join(gitDirectory, "commondir"), MAX_POINTER_BYTES);
5180
+ if (found.kind === "missing") return join(gitDirectory, "config");
5181
+ if (found.kind !== "file") return void 0;
5182
+ const common = found.content.text.trim();
5183
+ return common === "" ? void 0 : join(resolveFrom(gitDirectory, common), "config");
5184
+ }
5185
+ const isSpace = (character) => character === " " || character === " ";
5186
+ const isCommentStart = (character) => character === "#" || character === ";";
5187
+ const isSectionNameCharacter = (character) => /^[\w.-]$/.test(character);
5188
+ /**
5189
+ * A config section header: `[name]` or `[name "subsection"]`, then nothing or a `#`/`;` comment. In a subsection a backslash
5190
+ * takes the next character literally. `undefined` for a header that is not well formed, which opens no section.
5191
+ */
5192
+ function parseSection(line) {
5193
+ let index = 1;
5194
+ let name = "";
5195
+ while (index < line.length && isSectionNameCharacter(line.charAt(index))) {
5196
+ name += line.charAt(index);
5197
+ index += 1;
5198
+ }
5199
+ if (name === "") return void 0;
5200
+ let subsection;
5201
+ if (line.charAt(index) !== "]") {
5202
+ while (isSpace(line.charAt(index))) index += 1;
5203
+ if (line.charAt(index) !== "\"") return void 0;
5204
+ index += 1;
5205
+ subsection = "";
5206
+ for (;;) {
5207
+ if (index >= line.length) return void 0;
5208
+ const character = line.charAt(index);
5209
+ index += 1;
5210
+ if (character === "\"") break;
5211
+ if (character === "\\") {
5212
+ if (index >= line.length) return void 0;
5213
+ subsection += line.charAt(index);
5214
+ index += 1;
5215
+ continue;
5216
+ }
5217
+ subsection += character;
5218
+ }
5219
+ if (line.charAt(index) !== "]") return void 0;
5220
+ }
5221
+ const rest = line.slice(index + 1).trim();
5222
+ return rest === "" || isCommentStart(rest.charAt(0)) ? {
5223
+ name,
5224
+ subsection
5225
+ } : void 0;
5226
+ }
5227
+ /**
5228
+ * A config value as git reads it, kept to what is safe: surrounding whitespace goes, `"` toggles quoting, a `#` or `;` outside
5229
+ * quotes starts a comment, and the only escapes are `\"` and `\\`. `undefined` for anything else (another escape, a quote that
5230
+ * is never closed, a backslash at the end of the line): an odd value is not guessed at.
5231
+ */
5232
+ function parseValue(raw) {
5233
+ const text = raw.trimStart();
5234
+ let value = "";
5235
+ let quoted = false;
5236
+ let pending = "";
5237
+ for (let index = 0; index < text.length; index += 1) {
5238
+ const character = text.charAt(index);
5239
+ if (character === "\\") {
5240
+ const next = text.charAt(index + 1);
5241
+ if (next !== "\"" && next !== "\\") return void 0;
5242
+ value += pending + next;
5243
+ pending = "";
5244
+ index += 1;
5245
+ } else if (character === "\"") {
5246
+ quoted = !quoted;
5247
+ value += pending;
5248
+ pending = "";
5249
+ } else if (!quoted && isCommentStart(character)) break;
5250
+ else if (!quoted && isSpace(character)) pending += character;
5251
+ else {
5252
+ value += pending + character;
5253
+ pending = "";
5254
+ }
5255
+ }
5256
+ return quoted ? void 0 : value;
5257
+ }
5258
+ /**
5259
+ * The first `url` of the `[remote "origin"]` sections of a git config's text (git merges repeated sections), or `undefined`. Section names are case-insensitive
5260
+ * and subsection names are not, as in git: `[REMOTE "origin"]` is origin and `[remote "Origin"]` is not.
5261
+ */
5262
+ function originUrlOf(config) {
5263
+ let inOrigin = false;
5264
+ let found;
5265
+ const lines = config.text.split(/\r?\n/);
5266
+ if (config.truncated) lines.pop();
5267
+ for (const raw of lines) {
5268
+ const line = raw.trim();
5269
+ if (line.endsWith("\\") && (inOrigin || found === void 0)) return void 0;
5270
+ if (line.startsWith("[")) {
5271
+ if (found !== void 0) return found;
5272
+ const section = parseSection(line);
5273
+ inOrigin = section !== void 0 && section.name.toLowerCase() === "remote" && section.subsection === "origin";
5274
+ continue;
5275
+ }
5276
+ if (!inOrigin || found !== void 0 || isCommentStart(line.charAt(0))) continue;
5277
+ const separator = line.indexOf("=");
5278
+ if (separator === -1 || line.slice(0, separator).trim().toLowerCase() !== "url") continue;
5279
+ const value = parseValue(line.slice(separator + 1));
5280
+ if (value === void 0) return void 0;
5281
+ if (value !== "") found = value;
5282
+ }
5283
+ return found;
5284
+ }
5285
+ /**
5286
+ * The `origin` url of the checkout that holds `directory`: `.git` as a directory, or as a file naming a `gitdir` (a linked
5287
+ * worktree's `commondir` is followed for the config), found in `directory` or one of its parents. `undefined` for anything else,
5288
+ * and for any failure: this never throws. Every path is opened once and read through that handle only if it is a regular file (see
5289
+ * `probe`); a `.git` that is a symlink is not followed. It stops, with no answer, once `performance.now()` passes
5290
+ * `deadline`.
5291
+ */
5292
+ async function readOriginRemote(directory, deadline = Number.POSITIVE_INFINITY) {
5293
+ const expired = () => performance$1.now() > deadline;
5294
+ try {
5295
+ let current = resolve(directory);
5296
+ for (let depth = 0; depth <= MAX_PARENTS; depth += 1) {
5297
+ if (expired()) return void 0;
5298
+ const dotGit = await probe(join(current, ".git"), MAX_POINTER_BYTES);
5299
+ if (dotGit.kind === "unreadable") return void 0;
5300
+ if (dotGit.kind !== "missing") {
5301
+ const gitDirectory = dotGit.kind === "directory" ? join(current, ".git") : gitdirPointer(current, dotGit.content);
5302
+ if (gitDirectory === void 0 || expired()) return void 0;
5303
+ const configPath = await configPathOf(gitDirectory);
5304
+ if (configPath === void 0 || expired()) return void 0;
5305
+ const config = await readRegularFile(configPath, MAX_CONFIG_BYTES);
5306
+ return config === void 0 || expired() ? void 0 : originUrlOf(config);
5307
+ }
5308
+ const parent = dirname(current);
5309
+ if (parent === current) return void 0;
5310
+ current = parent;
5311
+ }
5312
+ return;
5313
+ } catch {
5314
+ return;
5315
+ }
5316
+ }
5317
+ /** How many directories a resolver remembers. A server sees a handful of projects; this only bounds a pathological run. */
5318
+ const MAX_CACHED_DIRECTORIES = 256;
5319
+ /** `work`'s result, or `undefined` once `ms` have passed or it has failed: a reader that never answers is a reader that found nothing. */
5320
+ async function within(work, ms) {
5321
+ return new Promise((settle) => {
5322
+ const timer = setTimeout(() => {
5323
+ settle(void 0);
5324
+ }, ms);
5325
+ timer.unref();
5326
+ Promise.resolve().then(work).then((value) => {
5327
+ clearTimeout(timer);
5328
+ settle(value);
5329
+ }, () => {
5330
+ clearTimeout(timer);
5331
+ settle(void 0);
5332
+ });
5333
+ });
5334
+ }
5335
+ /**
5336
+ * How many directories are being looked up for real at once. Discovery runs on the runtime's shared file-work threads (four by
5337
+ * default, shared with everything else OpenCode does), and a read on a stalled mount holds one for as long as the mount stalls, so
5338
+ * it takes one at most. A directory asked for while the slot is taken is skipped, not queued.
5339
+ */
5340
+ const MAX_LOOKUPS_IN_FLIGHT = 1;
5341
+ function createRepositoryResolver(options = {}) {
5342
+ const budgetMs = options.budgetMs ?? 250;
5343
+ const limit = options.limit ?? MAX_CACHED_DIRECTORIES;
5344
+ const read = options.read ?? (async (directory) => readOriginRemote(directory, performance$1.now() + budgetMs));
5345
+ const cache = /* @__PURE__ */ new Map();
5346
+ /**
5347
+ * The directories whose read has not returned, whatever the cache says: an entry the cache forgot, or whose budget ran out,
5348
+ * still has a read on a thread. A slot is held until that read settles, never until its budget ends.
5349
+ */
5350
+ const running = /* @__PURE__ */ new Set();
5351
+ const prefetch = (directory) => {
5352
+ if (cache.has(directory) || running.has(directory) || running.size >= MAX_LOOKUPS_IN_FLIGHT) return;
5353
+ if (cache.size >= limit) {
5354
+ const oldest = cache.keys().next();
5355
+ if (oldest.done !== true) cache.delete(oldest.value);
5356
+ }
5357
+ const entry = { slug: void 0 };
5358
+ cache.set(directory, entry);
5359
+ running.add(directory);
5360
+ const started = Promise.resolve().then(async () => read(directory));
5361
+ const release = () => {
5362
+ running.delete(directory);
5363
+ };
5364
+ started.then(release, release);
5365
+ within(async () => started, budgetMs).then((remote) => {
5366
+ entry.slug = remote === void 0 ? void 0 : slugFromRemote(remote);
5367
+ }).catch(() => {});
5368
+ };
5369
+ return {
5370
+ prefetch,
5371
+ peek: (directory) => {
5372
+ prefetch(directory);
5373
+ return cache.get(directory)?.slug;
5374
+ }
5375
+ };
5376
+ }
5076
5377
  // src/tracing/snapshot.ts
5077
5378
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5078
5379
  const asString$1 = (value) => typeof value === "string" ? value : void 0;
@@ -5251,7 +5552,7 @@ function copyBounded(value, limit, limits) {
5251
5552
  chars: meter.chars
5252
5553
  };
5253
5554
  }
5254
- function resolve(context) {
5555
+ function resolve$1(context) {
5255
5556
  const limits = {
5256
5557
  ...DEFAULT_SNAPSHOT_LIMITS,
5257
5558
  ...context.limits
@@ -5444,7 +5745,7 @@ function omittedRequest(reason) {
5444
5745
  */
5445
5746
  function snapshotRequest(input, context = {}) {
5446
5747
  try {
5447
- const { limits, room } = resolve(context);
5748
+ const { limits, room } = resolve$1(context);
5448
5749
  if (room === void 0) return omittedRequest("pending-bound");
5449
5750
  const total = Math.min(limits.requestChars, room);
5450
5751
  const shared = { nodes: 0 };
@@ -5490,7 +5791,7 @@ function snapshotRequest(input, context = {}) {
5490
5791
  /** A user prompt's `text`. Attachments are not read. */
5491
5792
  function snapshotPrompt(prompt, context = {}) {
5492
5793
  try {
5493
- const { limits, room } = resolve(context);
5794
+ const { limits, room } = resolve$1(context);
5494
5795
  if (room === void 0) return Object.freeze({
5495
5796
  text: omittedContent("pending-bound"),
5496
5797
  size: 0
@@ -5518,7 +5819,7 @@ function snapshotPrompt(prompt, context = {}) {
5518
5819
  function snapshotToolArguments(input, context = {}) {
5519
5820
  try {
5520
5821
  if (input === void 0) return void 0;
5521
- const { limits, room } = resolve(context);
5822
+ const { limits, room } = resolve$1(context);
5522
5823
  if (room === void 0) return omittedContent("pending-bound");
5523
5824
  let value = input;
5524
5825
  if (typeof input === "string") {
@@ -5544,7 +5845,7 @@ function snapshotToolArguments(input, context = {}) {
5544
5845
  function snapshotToolResult(result, context = {}) {
5545
5846
  try {
5546
5847
  if (!isRecord$1(result)) return void 0;
5547
- const { limits, room } = resolve(context);
5848
+ const { limits, room } = resolve$1(context);
5548
5849
  if (room === void 0) return omittedContent("pending-bound");
5549
5850
  const meter = meterFor(Math.min(limits.valueChars, room), limits);
5550
5851
  const raw = readKey(result, "content");
@@ -5656,6 +5957,8 @@ function offeredToolNames(request) {
5656
5957
  function set(attributes, name, value) {
5657
5958
  if (value !== void 0) attributes[name] = value;
5658
5959
  }
5960
+ /** The Langfuse trace metadata key the Action's run identity also sets; the identity wins wherever both exist (local mode only sets it from the trace's pinned `repository`). */
5961
+ const REPOSITORY_ATTRIBUTE = "langfuse.trace.metadata.repository";
5659
5962
  function identityAttributes(record, options) {
5660
5963
  const attributes = {
5661
5964
  "session.id": record.sessionId,
@@ -5664,7 +5967,8 @@ function identityAttributes(record, options) {
5664
5967
  "langfuse.session.id": options.sessionId ?? record.rootSessionId
5665
5968
  };
5666
5969
  set(attributes, "gen_ai.agent.name", record.agent);
5667
- if (options.identity !== void 0) Object.assign(attributes, actionIdentityAttributes(options.identity, options.invocationId, options.serverUrl));
5970
+ if (options.identity === void 0) set(attributes, REPOSITORY_ATTRIBUTE, record.repository);
5971
+ else Object.assign(attributes, actionIdentityAttributes(options.identity, options.invocationId, options.serverUrl));
5668
5972
  return attributes;
5669
5973
  }
5670
5974
  /**
@@ -5891,24 +6195,37 @@ function toPendingSpan(record, options = {}) {
5891
6195
  const SESSION_ATTRIBUTE = "langfuse.session.id";
5892
6196
  /**
5893
6197
  * The trace's name in Langfuse, whose OTLP ingestion reads it from this attribute on the trace's root span (the span names
5894
- * `invoke_agent <agent>` name observations, not the trace). One fixed string for every trace, so it holds no content.
6198
+ * `invoke_agent <agent>` name observations, not the trace). One fixed string per mode (`traceName` replaces it in local mode), so it holds no content.
5895
6199
  */
5896
6200
  const TRACE_NAME_ATTRIBUTE = "langfuse.trace.name";
5897
- const TRACE_NAME = "fro-bot run";
5898
6201
  /**
5899
- * Names the trace on a span that is its root, and on nothing else. A span with no parent is the root: the turn model opens
5900
- * every trace with a parentless `invoke_agent` (a continuation of a closed trace included) and gives every other span a parent.
5901
- *
5902
- * Added after the scrub, never through it: the string is fixed text, and a scrubber that rewrote it (a registered value that
5903
- * happens to match a word of it) would split one name into several in Langfuse. A span that is not a root is returned as is.
6202
+ * OpenCode's own prefix for an automation session (`isRunSession` in core: such a session is an automation child that finishes
6203
+ * quietly). It is a naming convention, not proof of where a session came from: any caller may pick a session id.
5904
6204
  */
5905
- function withTraceName(span) {
5906
- if (span.parentSpanId !== void 0) return span;
5907
- return {
6205
+ const AUTOMATION_SESSION_PREFIX = "ses_aut_";
6206
+ const ENVIRONMENT_ATTRIBUTE = "langfuse.environment";
6207
+ const AUTOMATION_ENVIRONMENT = "automation";
6208
+ /**
6209
+ * What the trace says about itself, added to a span after its scrub: its name, on the span that is its root, and its environment,
6210
+ * on every span of an automation trace.
6211
+ *
6212
+ * A span with no parent is the root: the turn model opens every trace with a parentless `invoke_agent` (a continuation of a closed
6213
+ * trace included) and gives every other span a parent. The environment follows the trace's ROOT session, not the span's own, so a
6214
+ * subagent of an automation session is labelled with it; any other trace sets none, which Langfuse reads as `default`.
6215
+ *
6216
+ * Both values are fixed text, never passed through the scrub: a scrubber that rewrote one (a registered value that happens to
6217
+ * match a word of it) would split one name or environment into several in Langfuse. The one value that is not fixed, the local
6218
+ * repository, is set before the scrub. A span with nothing to add is returned as is.
6219
+ */
6220
+ function withTraceIdentity(span, record, options) {
6221
+ const added = {};
6222
+ if (record.rootSessionId.startsWith(AUTOMATION_SESSION_PREFIX)) added[ENVIRONMENT_ATTRIBUTE] = AUTOMATION_ENVIRONMENT;
6223
+ if (span.parentSpanId === void 0) added[TRACE_NAME_ATTRIBUTE] = options.traceName ?? "fro-bot run";
6224
+ return Object.keys(added).length === 0 ? span : {
5908
6225
  ...span,
5909
6226
  attributes: {
5910
6227
  ...span.attributes,
5911
- [TRACE_NAME_ATTRIBUTE]: TRACE_NAME
6228
+ ...added
5912
6229
  }
5913
6230
  };
5914
6231
  }
@@ -5932,11 +6249,11 @@ function sessionIdExportedAsGiven(span, sessionId) {
5932
6249
  */
5933
6250
  function toExportSpan(record, options, scrubber, limits) {
5934
6251
  const span = scrubSpan(toPendingSpan(record, options), scrubber, limits);
5935
- if (options.sessionId === void 0 || sessionIdExportedAsGiven(span, options.sessionId)) return withTraceName(span);
5936
- return withTraceName(scrubSpan(toPendingSpan(record, {
6252
+ if (options.sessionId === void 0 || sessionIdExportedAsGiven(span, options.sessionId)) return withTraceIdentity(span, record, options);
6253
+ return withTraceIdentity(scrubSpan(toPendingSpan(record, {
5937
6254
  ...options,
5938
6255
  sessionId: void 0
5939
- }), scrubber, limits));
6256
+ }), scrubber, limits), record, options);
5940
6257
  }
5941
6258
  // src/tracing/turn-model.ts
5942
6259
  const DEFAULT_LIMITS = {
@@ -6037,6 +6354,18 @@ function createTurnModel(options) {
6037
6354
  const emit = (record) => {
6038
6355
  out.push(record);
6039
6356
  };
6357
+ /** The repository every span of `trace` carries: asked for on the first call, then the same answer for the trace's life. */
6358
+ function repositoryOf(trace) {
6359
+ if (!trace.repositoryPinned) {
6360
+ trace.repositoryPinned = true;
6361
+ try {
6362
+ trace.repository = options.repositoryOf?.(trace.rootSessionId);
6363
+ } catch {
6364
+ trace.repository = void 0;
6365
+ }
6366
+ }
6367
+ return trace.repository;
6368
+ }
6040
6369
  function newInvoke(role, sessionId, start, parentSpanId) {
6041
6370
  return {
6042
6371
  spanId: ids.span(),
@@ -6078,7 +6407,9 @@ function createTurnModel(options) {
6078
6407
  lastActivity: start,
6079
6408
  activeExecutions: 0,
6080
6409
  openSpans: 0,
6081
- closed: false
6410
+ closed: false,
6411
+ repository: void 0,
6412
+ repositoryPinned: false
6082
6413
  };
6083
6414
  traces.add(trace);
6084
6415
  return trace;
@@ -6165,6 +6496,7 @@ function createTurnModel(options) {
6165
6496
  error: invoke.error,
6166
6497
  sessionId: invoke.sessionId,
6167
6498
  rootSessionId: trace.rootSessionId,
6499
+ repository: repositoryOf(trace),
6168
6500
  agent: invoke.agent,
6169
6501
  gaps: [...invoke.gaps],
6170
6502
  marks: [...invoke.marks, ...extraMarks],
@@ -6197,6 +6529,7 @@ function createTurnModel(options) {
6197
6529
  error: unbound ? void 0 : error,
6198
6530
  sessionId: request.sessionId,
6199
6531
  rootSessionId: request.trace.rootSessionId,
6532
+ repository: repositoryOf(request.trace),
6200
6533
  agent: request.agent ?? (unbound ? void 0 : request.stepAgent),
6201
6534
  gaps: unbound ? ["step-binding-uncertain", ...request.gaps.has("request") ? ["request"] : []] : [...request.gaps],
6202
6535
  marks: unbound ? [
@@ -6239,7 +6572,8 @@ function createTurnModel(options) {
6239
6572
  } : void 0,
6240
6573
  sessionId: tool.sessionId,
6241
6574
  rootSessionId: tool.trace.rootSessionId,
6242
- agent: tool.agent ?? tool.askedAgent ?? tool.ownerAgent,
6575
+ repository: repositoryOf(tool.trace),
6576
+ agent: tool.agent ?? (tool.offerBasis?.certain === false ? void 0 : tool.askedAgent) ?? tool.ownerAgent,
6243
6577
  gaps: [...tool.gaps],
6244
6578
  marks: [...extra.marks ?? []],
6245
6579
  tool: tool.tool,
@@ -6255,15 +6589,21 @@ function createTurnModel(options) {
6255
6589
  discarded: tool.discarded
6256
6590
  };
6257
6591
  const basis = tool.offerBasis;
6258
- if (record.offered !== void 0 && basis !== void 0 && !(basis.certain && basis.stepEnded)) {
6592
+ const unboundAgent = tool.agent ?? tool.ownerAgent;
6593
+ const dependsOnRequest = record.offered !== void 0 || tool.agent === void 0 && tool.askedAgent !== void 0;
6594
+ if (basis !== void 0 && dependsOnRequest && !(basis.certain && basis.stepEnded)) {
6259
6595
  if (basis.certain && !basis.closed && heldToolSpans < limits.maxHeldToolSpans) {
6260
- basis.held.push(record);
6596
+ basis.held.push({
6597
+ record,
6598
+ unboundAgent
6599
+ });
6261
6600
  heldToolSpans += 1;
6262
6601
  return;
6263
6602
  }
6264
6603
  emit({
6265
6604
  ...record,
6266
- offered: void 0
6605
+ offered: void 0,
6606
+ agent: unboundAgent
6267
6607
  });
6268
6608
  return;
6269
6609
  }
@@ -6276,9 +6616,11 @@ function createTurnModel(options) {
6276
6616
  basis.held = [];
6277
6617
  heldToolSpans = Math.max(0, heldToolSpans - held.length);
6278
6618
  const trusted = basis.certain && basis.stepEnded;
6279
- for (const record of held) emit(trusted ? record : {
6619
+ for (const { record, unboundAgent } of held) if (trusted) emit(record);
6620
+ else emit({
6280
6621
  ...record,
6281
- offered: void 0
6622
+ offered: void 0,
6623
+ agent: unboundAgent
6282
6624
  });
6283
6625
  }
6284
6626
  /** Closes a trace: its descendants first, then its root. `incomplete` marks every span that was still open. */
@@ -7348,6 +7690,10 @@ const FREE_TEXT_KEYS = /* @__PURE__ */ new Set([
7348
7690
  "result"
7349
7691
  ]);
7350
7692
  const MAX_IDENTIFIER_CHARS = 512;
7693
+ /** A directory longer than this is not kept: it names no repository. */
7694
+ const MAX_DIRECTORY_CHARS = 4096;
7695
+ /** Sessions whose directory is remembered at once. */
7696
+ const MAX_SESSION_DIRECTORIES = 1024;
7351
7697
  const isPlainRecord = (value) => typeof value === "object" && value !== null;
7352
7698
  /** What an observation holds in raw strings, by the audit above. Never throws. */
7353
7699
  function measure(observation) {
@@ -7402,17 +7748,51 @@ function createTracePipeline(options) {
7402
7748
  ...options.limits
7403
7749
  };
7404
7750
  const now = options.now ?? Date.now;
7751
+ /**
7752
+ * The directory each session was created in, from its `session.created` event. Bounded: the oldest is forgotten first, and a
7753
+ * session whose directory is forgotten, or was never seen, takes the host's.
7754
+ */
7755
+ const sessionDirectories = /* @__PURE__ */ new Map();
7756
+ const { repository } = options;
7405
7757
  const model = createTurnModel({
7406
7758
  ids: options.ids ?? randomIds(),
7407
- ...options.modelLimits === void 0 ? {} : { limits: options.modelLimits }
7759
+ ...options.modelLimits === void 0 ? {} : { limits: options.modelLimits },
7760
+ ...repository === void 0 ? {} : { repositoryOf: (rootSessionId) => {
7761
+ const directory = sessionDirectories.get(rootSessionId) ?? options.directory;
7762
+ return directory === void 0 ? void 0 : repository.peek(directory);
7763
+ } }
7408
7764
  });
7409
7765
  const attributeOptions = {
7410
7766
  identity: options.identity,
7411
7767
  rootSpan: options.rootSpan,
7412
7768
  sessionId: options.sessionId,
7413
7769
  invocationId: options.invocationId,
7414
- serverUrl: options.serverUrl
7770
+ serverUrl: options.serverUrl,
7771
+ traceName: options.traceName
7415
7772
  };
7773
+ /** Keeps a session's directory, and hands the observation on without it: the model has no use for a path. */
7774
+ function takeDirectory(observation) {
7775
+ try {
7776
+ if (!isPlainRecord(observation) || observation.kind !== "session.created") return observation;
7777
+ const { directory, sessionId } = observation;
7778
+ if (directory === void 0) return observation;
7779
+ if (repository !== void 0 && typeof directory === "string" && typeof sessionId === "string" && directory.length <= MAX_DIRECTORY_CHARS && sessionId.length <= MAX_IDENTIFIER_CHARS) {
7780
+ sessionDirectories.delete(sessionId);
7781
+ sessionDirectories.set(sessionId, directory);
7782
+ repository.prefetch(directory);
7783
+ if (sessionDirectories.size > MAX_SESSION_DIRECTORIES) {
7784
+ const oldest = sessionDirectories.keys().next();
7785
+ if (oldest.done !== true) sessionDirectories.delete(oldest.value);
7786
+ }
7787
+ }
7788
+ return {
7789
+ ...observation,
7790
+ directory: void 0
7791
+ };
7792
+ } catch {
7793
+ return observation;
7794
+ }
7795
+ }
7416
7796
  /** Observations waiting for the model, each with the raw text it holds against `maxInboxChars`. */
7417
7797
  const inbox = [];
7418
7798
  /**
@@ -7625,8 +8005,9 @@ function createTracePipeline(options) {
7625
8005
  }, limits.tickMs);
7626
8006
  tick.unref();
7627
8007
  return {
7628
- observe: (observation) => {
8008
+ observe: (arrived) => {
7629
8009
  if (stopped) return;
8010
+ const observation = takeDirectory(arrived);
7630
8011
  if (inbox.length - markers >= limits.maxInbox) {
7631
8012
  observationsDropped += 1;
7632
8013
  releaseObservation(observation);
@@ -7881,7 +8262,8 @@ function observeEvent(raw, snapshot = {}) {
7881
8262
  at,
7882
8263
  sessionId,
7883
8264
  parentSessionId: asString(data.parentID),
7884
- agent: asString(data.agent)
8265
+ agent: asString(data.agent),
8266
+ directory: asString(asRecord(data.location)?.directory)
7885
8267
  };
7886
8268
  case "session.inbox.enqueued": {
7887
8269
  const inboxId = asString(data.inboxID);
@@ -8128,6 +8510,8 @@ async function registerObservers(host, emit, now = Date.now, snapshot = {}) {
8128
8510
  * nearby collector needs for one batch. A batch still in flight at the bound is abandoned and counted as dropped.
8129
8511
  */
8130
8512
  const CLEANUP_BOUND_MS = 3e3;
8513
+ /** What a local session's trace is called in Langfuse. The Action's turn traces keep `fro-bot run`. */
8514
+ const LOCAL_TRACE_NAME = "opencode session";
8131
8515
  /** The `service.name` of every span this plugin exports. The Action's own spans carry a different one. */
8132
8516
  const PLUGIN_SERVICE_NAME = "fro-bot-opencode-plugin";
8133
8517
  /** A version as a resource value: short, printable, no spaces. Anything else is not trusted as a label. */
@@ -8180,6 +8564,8 @@ async function startTracing(host, settings, options) {
8180
8564
  log("tracing stopped exporting after repeated failures");
8181
8565
  }
8182
8566
  });
8567
+ const repository = local ? createRepositoryResolver() : void 0;
8568
+ if (options.directory !== void 0) repository?.prefetch(options.directory);
8183
8569
  const ledger = createSnapshotLedger(options.pending);
8184
8570
  const pipeline = createTracePipeline({
8185
8571
  sink: exporter,
@@ -8191,7 +8577,11 @@ async function startTracing(host, settings, options) {
8191
8577
  sessionId: settings.sessionId,
8192
8578
  invocationId: settings.invocationId,
8193
8579
  serverUrl: settings.serverUrl
8194
- } : {},
8580
+ } : {
8581
+ traceName: LOCAL_TRACE_NAME,
8582
+ directory: options.directory,
8583
+ repository
8584
+ },
8195
8585
  ...options.now === void 0 ? {} : { now: options.now }
8196
8586
  });
8197
8587
  let stopObserving;
@@ -8227,4 +8617,4 @@ async function startTracing(host, settings, options) {
8227
8617
  }
8228
8618
  export { startTracing };
8229
8619
 
8230
- //# sourceMappingURL=tracing-B58yZAvo.mjs.map
8620
+ //# sourceMappingURL=tracing-BeMbWlwI.mjs.map