nemo-fabric-adapters-opencode 0.6.0-rc.1 → 0.6.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -104,7 +104,7 @@ The adapter accepts plain-text input and returns the final response in
104
104
  `output.response`. It uses the Fabric workspace while disabling ambient OpenCode
105
105
  project configuration, user configuration, and instruction discovery.
106
106
 
107
- Streaming, Relay, tool policy, subagents, provider-specific model settings, and
107
+ Streaming, Relay, tool policy, NeMo Fabric subagent configuration, provider-specific model settings, and
108
108
  `max_tokens` are not supported.
109
109
 
110
110
  One Bun adapter process owns one embedded OpenCode host and session for each
@@ -123,3 +123,17 @@ OpenCode supports `live`, `active`, `ready` through `Fabric.check()`. Each level
123
123
  Checks remain independent of an invocation. A busy invocation is healthy. Checks use the caller deadline and never cancel an invocation, stop the runtime, or repair a failure. Health does not establish valid model credentials, provider access, MCP connectivity, or successful model output. At most one native request remains outstanding. A check returns `unknown/probe_timeout` while an earlier native request remains pending; later checks do not reuse a delayed reply. Reports contain only the generic health contract fields.
124
124
 
125
125
  Refer to the [SDK health-check overview](../../../docs/sdk/health-checks.mdx) for shared behavior and a comparison of native evidence across adapters.
126
+
127
+ ## Token Usage
128
+
129
+ When coverage cannot be proved, the evidence may include `scope_reasons` with bounded reason codes such as `background_shell`, `title_completion_unconfirmed`, or `observer_lost`. These diagnostics contain no native error messages, shell commands, or credentials and do not make partial counters complete.
130
+
131
+ With OpenCode 2.0.23, NeMo Fabric collects provider usage for OpenCode-managed Chat Completions requests it can attribute to an invocation. Input includes cached tokens. Output includes reasoning tokens. Do not add either breakdown again. Calls made directly by shell commands or external tools are outside this scope.
132
+
133
+ The adapter proves request ownership and waits for root and automatic title work. It reports each standard token count only when every owned request supplies a valid value for that field. Attributable foreground child work is included. Harbor receives these same inclusive counts. Standard total and cache counts are available only when every request reports those fields. Provider-reported cost stays unknown; OpenCode's locally calculated cost is not a provider-reported amount.
134
+
135
+ Collected observations are also preserved in `RunResult.usage.metadata["nvidia.fabric.opencode.usage_evidence.v1"]`. An empty `gaps` list means the input and output counts cover the proven scope. Observed cache and reasoning sums can still be partial if a request omits that breakdown. `scope_unverified` means ownership or completion could not be established. `missing_usage` marks missing or invalid counts, and `unfinished_work` marks requests that did not finish. Missing counts stay absent; reported zero stays zero. Partial sums can cover different sets of requests and must not be treated as complete totals.
136
+
137
+ When coverage cannot be proved, the evidence may include `scope_reasons` with bounded reason codes such as `background_shell`, `title_completion_unconfirmed`, or `observer_lost`. These diagnostics contain no native error messages, shell commands, or credentials and do not make partial counters complete.
138
+
139
+ Background shell or child work, an unresolved title, manual session changes, an interrupted event subscription, warming, or custom OpenCode plugins can prevent proof. The adapter retains attributable observations and leaves standard totals unknown. If earlier work can resume during a later invocation, that later invocation also leaves usage unknown. Unsupported model response protocols leave token counts unknown.
package/dist/cli.js CHANGED
@@ -22,4 +22,13 @@ await serve(async () => {
22
22
  import("./runtime.js"),
23
23
  ]);
24
24
  return new OpenCodeAdapterRuntime(new OpenCodeSdkSessionFactory());
25
+ }, {
26
+ software: {
27
+ packageJson: new URL("../package.json", import.meta.url),
28
+ harness: "opencode",
29
+ packages: [
30
+ { role: "framework", name: "@opencode/sdk" },
31
+ { role: "framework", name: "@opencode/core" },
32
+ ],
33
+ },
25
34
  });
@@ -1,3 +1,4 @@
1
+ import type { AgentUsage } from "nemo-fabric-adapter-contract";
1
2
  import type { AdapterStartInput } from "nemo-fabric-adapters-common";
2
3
  import type { OpenCodePromptOutcome, OpenCodeSessionFactory, OpenCodeSessionHandle } from "./runtime.js";
3
4
  type OpenCodeEmbedOptions = {
@@ -12,7 +13,7 @@ interface EndpointProxy {
12
13
  }
13
14
  type EndpointProxyFactory = (baseUrl: string) => Promise<EndpointProxy>;
14
15
  /** Extract the terminal assistant outcome after OpenCode reports a session idle. */
15
- export declare function extractOpenCodePromptOutcome(messages: unknown[], existingMessageIds?: ReadonlySet<string>): OpenCodePromptOutcome;
16
+ export declare function extractOpenCodePromptOutcome(messages: unknown[], existingMessageIds?: ReadonlySet<string>, invocationUsage?: AgentUsage): OpenCodePromptOutcome;
16
17
  export declare function loadOpenCodeSdk(resolveModule?: ModuleResolver, loadModule?: ModuleLoader): Promise<typeof import("@opencode/sdk")>;
17
18
  export declare class OpenCodeSdkSessionFactory implements OpenCodeSessionFactory {
18
19
  private readonly sdkLoader;
@@ -7,6 +7,8 @@ import { tmpdir } from "node:os";
7
7
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
8
8
  import { selectModel, selectSystemInstruction } from "./configuration.js";
9
9
  import { ModelEndpointProxy } from "./model-endpoint-proxy.js";
10
+ import { OpenCodePromptFailure } from "./runtime.js";
11
+ import { OpenCodeUsageCollector } from "./usage.js";
10
12
  // Fabric invokes OpenCode non-interactively. Session rules are evaluated after
11
13
  // OpenCode's agent defaults, so they override upstream "ask" rules without
12
14
  // changing the permissions of other OpenCode sessions in the process.
@@ -24,6 +26,7 @@ const MCP_CONNECTION_POLL_INTERVAL_MS = 50;
24
26
  const SKILL_DISCOVERY_TIMEOUT_MS = 5_000;
25
27
  const SKILL_DISCOVERY_POLL_INTERVAL_MS = 50;
26
28
  const HTTP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
29
+ const ACCOUNTING_WAIT_LIMIT_MS = 2_000;
27
30
  function loopbackHostname(hostname) {
28
31
  return hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/u.test(hostname);
29
32
  }
@@ -375,61 +378,6 @@ async function waitForMcpConnections(client, workspace, servers) {
375
378
  function isRecord(value) {
376
379
  return typeof value === "object" && value !== null && !Array.isArray(value);
377
380
  }
378
- function usage(message) {
379
- const tokens = isRecord(message.tokens) ? message.tokens : undefined;
380
- const input = tokens?.input;
381
- const output = tokens?.output;
382
- const cost = message.cost;
383
- if (typeof input !== "number" && typeof output !== "number" && typeof cost !== "number") {
384
- return undefined;
385
- }
386
- const result = {};
387
- if (typeof input === "number") {
388
- result.input_tokens = input;
389
- }
390
- if (typeof output === "number") {
391
- result.output_tokens = output;
392
- }
393
- if (typeof input === "number" && typeof output === "number") {
394
- result.total_tokens = input + output;
395
- }
396
- if (typeof cost === "number") {
397
- result.cost_usd = cost;
398
- }
399
- return result;
400
- }
401
- function totalUsage(messages) {
402
- let inputTokens = 0;
403
- let outputTokens = 0;
404
- let costUsd = 0;
405
- let hasInputTokens = false;
406
- let hasOutputTokens = false;
407
- let hasCostUsd = false;
408
- for (const message of messages) {
409
- const current = usage(message);
410
- if (current?.input_tokens !== undefined && current.input_tokens !== null) {
411
- inputTokens += current.input_tokens;
412
- hasInputTokens = true;
413
- }
414
- if (current?.output_tokens !== undefined && current.output_tokens !== null) {
415
- outputTokens += current.output_tokens;
416
- hasOutputTokens = true;
417
- }
418
- if (current?.cost_usd !== undefined && current.cost_usd !== null) {
419
- costUsd += current.cost_usd;
420
- hasCostUsd = true;
421
- }
422
- }
423
- if (!hasInputTokens && !hasOutputTokens && !hasCostUsd) {
424
- return undefined;
425
- }
426
- return {
427
- ...(hasInputTokens ? { input_tokens: inputTokens } : {}),
428
- ...(hasOutputTokens ? { output_tokens: outputTokens } : {}),
429
- ...(hasInputTokens && hasOutputTokens ? { total_tokens: inputTokens + outputTokens } : {}),
430
- ...(hasCostUsd ? { cost_usd: costUsd } : {}),
431
- };
432
- }
433
381
  function patch(diffs) {
434
382
  if (!Array.isArray(diffs)) {
435
383
  return undefined;
@@ -447,7 +395,7 @@ function messageIds(messages) {
447
395
  .filter((id) => typeof id === "string"));
448
396
  }
449
397
  /** Extract the terminal assistant outcome after OpenCode reports a session idle. */
450
- export function extractOpenCodePromptOutcome(messages, existingMessageIds) {
398
+ export function extractOpenCodePromptOutcome(messages, existingMessageIds, invocationUsage) {
451
399
  const assistantMessages = [];
452
400
  for (const message of messages) {
453
401
  if (!isRecord(message) || message.type !== "assistant") {
@@ -461,9 +409,8 @@ export function extractOpenCodePromptOutcome(messages, existingMessageIds) {
461
409
  }
462
410
  const terminal = assistantMessages.at(-1);
463
411
  if (terminal === undefined) {
464
- return {};
412
+ return invocationUsage === undefined ? {} : { usage: invocationUsage };
465
413
  }
466
- const invocationUsage = totalUsage(assistantMessages);
467
414
  if (terminal.finish === "error" || terminal.error !== undefined) {
468
415
  return {
469
416
  errorMessage: "OpenCode model invocation failed",
@@ -471,7 +418,7 @@ export function extractOpenCodePromptOutcome(messages, existingMessageIds) {
471
418
  };
472
419
  }
473
420
  if (!Array.isArray(terminal.content)) {
474
- return {};
421
+ return invocationUsage === undefined ? {} : { usage: invocationUsage };
475
422
  }
476
423
  const text = terminal.content
477
424
  .filter((part) => isRecord(part) && part.type === "text")
@@ -580,6 +527,174 @@ function leaseEnvironment(input, credentialName) {
580
527
  replaceEnvironment(values);
581
528
  return { release: () => replaceEnvironment(original) };
582
529
  }
530
+ /** Join the SDK's independent title worker without changing its behavior. */
531
+ class OpenCodeAccountingBoundary {
532
+ id;
533
+ client;
534
+ workspace;
535
+ collector;
536
+ controller = new AbortController();
537
+ waiters = new Set();
538
+ running = false;
539
+ connected = false;
540
+ watching = false;
541
+ uncertain = false;
542
+ prepareFailure = "observer_unavailable";
543
+ renames = 0;
544
+ terminals = 0;
545
+ constructor(id, client, workspace, collector) {
546
+ this.id = id;
547
+ this.client = client;
548
+ this.workspace = workspace;
549
+ this.collector = collector;
550
+ // Older injected clients still return useful partial evidence.
551
+ if (typeof client.events?.subscribe !== "function" || typeof client.config?.get !== "function" || typeof client.sessions.get !== "function")
552
+ return;
553
+ this.running = true;
554
+ void this.observe();
555
+ }
556
+ changed() {
557
+ for (const waiter of this.waiters)
558
+ waiter();
559
+ }
560
+ invalidate(reason) {
561
+ this.uncertain = true;
562
+ this.collector.markUncertain(reason);
563
+ this.changed();
564
+ }
565
+ async observe() {
566
+ try {
567
+ for await (const event of this.client.events.subscribe({ signal: this.controller.signal })) {
568
+ if (event.type === "server.connected")
569
+ this.connected = true;
570
+ if (this.watching && (event.type === "config.updated" || event.type === "wellknown.updated"))
571
+ this.invalidate("configuration_changed");
572
+ if (isRecord(event.data) && event.data.sessionID === this.id) {
573
+ if (event.type === "session.renamed")
574
+ this.renames++;
575
+ if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed" || event.type === "session.execution.interrupted")
576
+ this.terminals++;
577
+ }
578
+ this.changed();
579
+ }
580
+ }
581
+ catch {
582
+ // Losing the lifecycle stream loses the title completion proof.
583
+ }
584
+ finally {
585
+ this.running = false;
586
+ if (!this.controller.signal.aborted)
587
+ this.invalidate("observer_lost");
588
+ this.changed();
589
+ }
590
+ }
591
+ limit(deadlineMillis) {
592
+ const limit = Date.now() + ACCOUNTING_WAIT_LIMIT_MS;
593
+ return typeof deadlineMillis === "number" && Number.isFinite(deadlineMillis) ? Math.min(deadlineMillis, limit) : limit;
594
+ }
595
+ async waitFor(predicate, deadline) {
596
+ if (predicate())
597
+ return true;
598
+ if (!this.running || this.uncertain || deadline <= Date.now())
599
+ return false;
600
+ return new Promise(resolve => {
601
+ const finish = (result) => {
602
+ clearTimeout(timer);
603
+ this.waiters.delete(check);
604
+ resolve(result);
605
+ };
606
+ const check = () => {
607
+ if (!this.running || this.uncertain)
608
+ finish(false);
609
+ else if (predicate())
610
+ finish(true);
611
+ };
612
+ const timer = setTimeout(() => finish(false), Math.max(0, deadline - Date.now()));
613
+ this.waiters.add(check);
614
+ check();
615
+ });
616
+ }
617
+ async readScope(deadline) {
618
+ if (deadline <= Date.now())
619
+ return undefined;
620
+ const controller = new AbortController();
621
+ let timer;
622
+ try {
623
+ const result = Promise.all([
624
+ this.client.config.get({ location: { directory: this.workspace } }, { signal: controller.signal }),
625
+ this.client.sessions.get({ sessionID: this.id }, { signal: controller.signal }),
626
+ ]).then(([entries, session]) => session.id === this.id ? { entries, title: session.title } : undefined).catch(() => undefined);
627
+ return await Promise.race([result, new Promise(resolve => {
628
+ timer = setTimeout(() => resolve(undefined), Math.max(0, deadline - Date.now()));
629
+ })]);
630
+ }
631
+ finally {
632
+ clearTimeout(timer);
633
+ controller.abort();
634
+ }
635
+ }
636
+ supported(entries) {
637
+ // Remote WellKnown documents still load when project/global discovery is off.
638
+ // Additional configuration can install unjoined model work or custom plugins.
639
+ if (!Array.isArray(entries) || entries.length !== 1)
640
+ return false;
641
+ const entry = entries[0];
642
+ if (!isRecord(entry) || entry.type !== "document" || !isRecord(entry.info))
643
+ return false;
644
+ const { warming, plugins } = entry.info;
645
+ return (warming === undefined || warming === false) && (plugins === undefined || Array.isArray(plugins) && plugins.length === 0);
646
+ }
647
+ async prepare(deadlineMillis) {
648
+ const limit = this.limit(deadlineMillis);
649
+ if (!await this.waitFor(() => this.connected, limit)) {
650
+ this.prepareFailure = "observer_unavailable";
651
+ return undefined;
652
+ }
653
+ this.watching = true;
654
+ const scope = await this.readScope(limit);
655
+ if (scope === undefined) {
656
+ this.prepareFailure = "prepare_scope_read_failed";
657
+ return undefined;
658
+ }
659
+ if (!this.running || this.uncertain)
660
+ return undefined;
661
+ const supported = this.supported(scope.entries);
662
+ return {
663
+ renames: this.renames,
664
+ terminals: this.terminals,
665
+ supported,
666
+ // This conservative check also covers the SDK's legacy timestamped fallback.
667
+ needsTitle: typeof scope.title !== "string" || scope.title.length === 0 || scope.title.startsWith("New session -"),
668
+ };
669
+ }
670
+ async finish(scope, deadlineMillis) {
671
+ if (scope === undefined) {
672
+ this.invalidate(this.prepareFailure);
673
+ return false;
674
+ }
675
+ if (!scope.supported) {
676
+ this.invalidate("unsupported_configuration");
677
+ return false;
678
+ }
679
+ const limit = this.limit(deadlineMillis);
680
+ const settled = await this.waitFor(() => this.terminals > scope.terminals && (!scope.needsTitle || this.renames > scope.renames), limit);
681
+ if (!settled) {
682
+ this.invalidate(this.terminals <= scope.terminals ? "root_execution_unconfirmed" : "title_completion_unconfirmed");
683
+ return false;
684
+ }
685
+ const current = await this.readScope(limit);
686
+ if (current === undefined)
687
+ this.invalidate("final_scope_read_failed");
688
+ else if (!this.supported(current.entries))
689
+ this.invalidate("unsupported_configuration");
690
+ return current !== undefined && this.supported(current.entries) && this.running && !this.uncertain;
691
+ }
692
+ close() {
693
+ this.controller.abort();
694
+ this.running = false;
695
+ this.changed();
696
+ }
697
+ }
583
698
  class OpenCodeSdkSessionHandle {
584
699
  healthObservation;
585
700
  id;
@@ -587,13 +702,17 @@ class OpenCodeSdkSessionHandle {
587
702
  environment;
588
703
  endpointProxy;
589
704
  skillsRoot;
705
+ usageCollector;
706
+ accountingBoundary;
590
707
  stopped = false;
591
- constructor(id, client, environment, endpointProxy, skillsRoot) {
708
+ constructor(id, client, environment, endpointProxy, skillsRoot, usageCollector = new OpenCodeUsageCollector(), workspace = "") {
592
709
  this.id = id;
593
710
  this.client = client;
594
711
  this.environment = environment;
595
712
  this.endpointProxy = endpointProxy;
596
713
  this.skillsRoot = skillsRoot;
714
+ this.usageCollector = usageCollector;
715
+ this.accountingBoundary = new OpenCodeAccountingBoundary(id, client, workspace, usageCollector);
597
716
  }
598
717
  async check(level) {
599
718
  const source = level === "live" ? "fabric.adapter.liveness" : level === "active" ? "fabric.adapter.interface" : "fabric.adapter.readiness";
@@ -618,16 +737,20 @@ class OpenCodeSdkSessionHandle {
618
737
  return { outcome: "unknown", reason_code: this.stopped || this.id !== sessionId ? "observation_changed" : "probe_error", source, observed_at: null, activity: "unknown" };
619
738
  }
620
739
  }
621
- async prompt(text) {
740
+ async prompt(text, deadlineMillis) {
622
741
  let promptMayHaveBeenSubmitted = false;
742
+ let evidence;
623
743
  try {
624
744
  const historyBeforePrompt = await this.client.sessions.context({ sessionID: this.id });
625
745
  const existingMessageIds = messageIds(historyBeforePrompt);
746
+ evidence = this.usageCollector.begin(this.id);
747
+ const scope = await this.accountingBoundary.prepare(deadlineMillis);
626
748
  promptMayHaveBeenSubmitted = true;
627
749
  await this.client.sessions.prompt({ sessionID: this.id, text });
628
750
  await this.client.sessions.wait({ sessionID: this.id });
629
751
  const historyAfterPrompt = await this.client.sessions.context({ sessionID: this.id });
630
- const outcome = extractOpenCodePromptOutcome(historyAfterPrompt, existingMessageIds);
752
+ const scopeProven = await this.accountingBoundary.finish(scope, deadlineMillis);
753
+ const outcome = extractOpenCodePromptOutcome(historyAfterPrompt, existingMessageIds, this.usageCollector.end(evidence, scopeProven));
631
754
  try {
632
755
  const sessionPatch = patch(await this.client.sessions.diff({ sessionID: this.id }));
633
756
  return { ...outcome, ...(sessionPatch === undefined ? {} : { patch: sessionPatch }) };
@@ -637,6 +760,10 @@ class OpenCodeSdkSessionHandle {
637
760
  }
638
761
  }
639
762
  catch {
763
+ if (evidence !== undefined) {
764
+ this.usageCollector.markUncertain("prompt_failed");
765
+ throw new OpenCodePromptFailure(this.usageCollector.end(evidence));
766
+ }
640
767
  throw new LifecycleError("opencode_session_failed", "OpenCode session communication failed", {
641
768
  retryable: !promptMayHaveBeenSubmitted,
642
769
  });
@@ -647,6 +774,7 @@ class OpenCodeSdkSessionHandle {
647
774
  return;
648
775
  }
649
776
  this.stopped = true;
777
+ this.accountingBoundary.close();
650
778
  try {
651
779
  await this.client.sessions.remove({ sessionID: this.id });
652
780
  }
@@ -707,7 +835,9 @@ export class OpenCodeSdkSessionFactory {
707
835
  const createEmbeddedClient = this.sdkLoader === loadOpenCodeSdk
708
836
  ? await loadEmbeddedOpenCodeCreate()
709
837
  : sdk.OpenCode.create;
838
+ const usageCollector = new OpenCodeUsageCollector();
710
839
  client = await createEmbeddedClient({
840
+ plugins: [usageCollector.plugin()],
711
841
  config: { directory: workspace, project: false, content: configContent },
712
842
  fs: { filewatcher: false },
713
843
  models: { fetch: false },
@@ -720,7 +850,7 @@ export class OpenCodeSdkSessionFactory {
720
850
  });
721
851
  sessionId = session.id;
722
852
  await waitForMcpConnections(client, workspace, Object.keys(mcpServers));
723
- return new OpenCodeSdkSessionHandle(session.id, client, environment, endpointProxy, runtimeSkills.root);
853
+ return new OpenCodeSdkSessionHandle(session.id, client, environment, endpointProxy, runtimeSkills.root, usageCollector, workspace);
724
854
  }
725
855
  catch (error) {
726
856
  if (client !== undefined) {
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AdapterCheckResult, CheckLevel, AgentRunRequest, AgentRunResult, AgentUsage, RuntimeContext } from "nemo-fabric-adapter-contract";
2
- import { type AdapterRuntime, type AdapterStartInput } from "nemo-fabric-adapters-common";
2
+ import { LifecycleError, type AdapterRuntime, type AdapterStartInput } from "nemo-fabric-adapters-common";
3
3
  export interface OpenCodePromptOutcome {
4
4
  text?: string;
5
5
  errorMessage?: string;
@@ -9,12 +9,16 @@ export interface OpenCodePromptOutcome {
9
9
  export interface OpenCodeSessionHandle {
10
10
  id: string;
11
11
  check(level: CheckLevel): Promise<AdapterCheckResult>;
12
- prompt(text: string): Promise<OpenCodePromptOutcome>;
12
+ prompt(text: string, deadlineMillis?: number | null): Promise<OpenCodePromptOutcome>;
13
13
  stop(): Promise<void>;
14
14
  }
15
15
  export interface OpenCodeSessionFactory {
16
16
  create(input: AdapterStartInput): Promise<OpenCodeSessionHandle>;
17
17
  }
18
+ export declare class OpenCodePromptFailure extends LifecycleError {
19
+ readonly usage: AgentUsage;
20
+ constructor(usage: AgentUsage);
21
+ }
18
22
  export declare class OpenCodeAdapterRuntime implements AdapterRuntime {
19
23
  private readonly factory;
20
24
  private generation;
package/dist/runtime.js CHANGED
@@ -6,6 +6,13 @@ import { createHash } from "node:crypto";
6
6
  import { mkdir, writeFile } from "node:fs/promises";
7
7
  import { join } from "node:path";
8
8
  import { unobservedHealth, LifecycleError } from "nemo-fabric-adapters-common";
9
+ export class OpenCodePromptFailure extends LifecycleError {
10
+ usage;
11
+ constructor(usage) {
12
+ super("opencode_session_failed", "OpenCode session communication failed", { retryable: false });
13
+ this.usage = usage;
14
+ }
15
+ }
9
16
  function failed(code, message, usage, artifacts) {
10
17
  return {
11
18
  status: "failed",
@@ -96,10 +103,12 @@ export class OpenCodeAdapterRuntime {
96
103
  try {
97
104
  let outcome;
98
105
  try {
99
- outcome = await session.prompt(request.input);
106
+ outcome = await session.prompt(request.input, context.deadline_millis);
100
107
  }
101
108
  catch (error) {
102
109
  await this.invalidate(session);
110
+ if (error instanceof OpenCodePromptFailure)
111
+ return failed(error.code, error.message, error.usage);
103
112
  if (error instanceof LifecycleError) {
104
113
  throw error;
105
114
  }
@@ -0,0 +1,39 @@
1
+ import type { AgentUsage } from "nemo-fabric-adapter-contract";
2
+ type CreateOptions = NonNullable<Parameters<(typeof import("@opencode/sdk"))["OpenCode"]["create"]>[0]>;
3
+ type Plugin = NonNullable<CreateOptions["plugins"]>[number];
4
+ type Counter = "input_tokens" | "output_tokens" | "total_tokens" | "cached_input_tokens" | "reasoning_tokens";
5
+ type Counts = Partial<Record<Counter, number>>;
6
+ export type ScopeReason = "observer_unavailable" | "observer_lost" | "configuration_changed" | "prepare_scope_read_failed" | "unsupported_configuration" | "root_execution_unconfirmed" | "title_completion_unconfirmed" | "final_scope_read_failed" | "child_ancestry_unverified" | "child_ownership_changed" | "manual_session_change" | "tool_result_unavailable" | "background_shell" | "background_subagent" | "unsupported_protocol" | "auxiliary_generation" | "unsupported_request_kind" | "prompt_failed" | "unfinished_work";
7
+ interface Call {
8
+ counts: Counts;
9
+ settled: boolean;
10
+ missing: boolean;
11
+ invalid: boolean;
12
+ }
13
+ /** Freeze request-owned evidence only after the caller proves its scope. */
14
+ export declare class OpenCodeInvocationUsage {
15
+ readonly calls: Call[];
16
+ readonly children: Set<string>;
17
+ readonly tools: Map<string, number>;
18
+ readonly scopeReasons: Set<ScopeReason>;
19
+ uncertain: boolean;
20
+ closed: boolean;
21
+ private frozen?;
22
+ unfinished(): boolean;
23
+ finish(scopeProven?: boolean): AgentUsage;
24
+ }
25
+ export declare class OpenCodeUsageCollector {
26
+ private root?;
27
+ private active?;
28
+ private titleOwner?;
29
+ private continuationUncertain;
30
+ private readonly continuationReasons;
31
+ private readonly requests;
32
+ private readonly sessions;
33
+ begin(root: string): OpenCodeInvocationUsage;
34
+ markUncertain(reason?: ScopeReason): void;
35
+ end(usage: OpenCodeInvocationUsage, scopeProven?: boolean): AgentUsage;
36
+ private owner;
37
+ plugin(): Plugin;
38
+ }
39
+ export {};
package/dist/usage.js ADDED
@@ -0,0 +1,366 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ const KEY = "nvidia.fabric.opencode.usage_evidence.v1";
4
+ const MAX_EVENT_CHARACTERS = 1 << 20;
5
+ const counters = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "reasoning_tokens"];
6
+ function record(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8
+ }
9
+ function count(value) {
10
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
11
+ }
12
+ /** Freeze request-owned evidence only after the caller proves its scope. */
13
+ export class OpenCodeInvocationUsage {
14
+ calls = [];
15
+ children = new Set();
16
+ tools = new Map();
17
+ scopeReasons = new Set();
18
+ uncertain = false;
19
+ closed = false;
20
+ frozen;
21
+ unfinished() {
22
+ return this.children.size > 0 || this.tools.size > 0 || this.calls.some((call) => !call.settled);
23
+ }
24
+ finish(scopeProven = false) {
25
+ if (this.frozen !== undefined)
26
+ return this.frozen;
27
+ this.closed = true;
28
+ const observed = {};
29
+ const complete = {};
30
+ const gaps = new Set();
31
+ if (!scopeProven || this.uncertain)
32
+ gaps.add("scope_unverified");
33
+ let overflow = false;
34
+ for (const field of counters) {
35
+ const values = this.calls.flatMap((call) => call.counts[field] === undefined ? [] : [call.counts[field]]);
36
+ if (values.length === 0)
37
+ continue;
38
+ const sum = values.reduce((total, value) => total + value, 0);
39
+ if (!Number.isSafeInteger(sum)) {
40
+ overflow = true;
41
+ continue;
42
+ }
43
+ observed[field] = sum;
44
+ if (field !== "reasoning_tokens" && scopeProven && !this.uncertain && !this.unfinished() &&
45
+ this.calls.every((call) => !call.invalid && call.counts[field] !== undefined))
46
+ complete[field] = sum;
47
+ }
48
+ if (complete.input_tokens !== undefined)
49
+ complete.input_tokens_include_cache = true;
50
+ if (this.calls.length === 0 || overflow || this.calls.some((call) => call.missing))
51
+ gaps.add("missing_usage");
52
+ if (this.unfinished())
53
+ gaps.add("unfinished_work");
54
+ this.frozen = { ...complete, extensions: { [KEY]: { observed, gaps: [...gaps], ...(this.scopeReasons.size === 0 ? {} : { scope_reasons: [...this.scopeReasons] }) } } };
55
+ return this.frozen;
56
+ }
57
+ }
58
+ /** Observe only bytes consumed by OpenCode, without buffering the full stream. */
59
+ function observeResponse(call, response) {
60
+ if (!response.ok || response.body === null) {
61
+ call.settled = true;
62
+ return response;
63
+ }
64
+ const streaming = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "text/event-stream";
65
+ const decoder = new TextDecoder();
66
+ let buffer = "";
67
+ let event = "";
68
+ let overflow = false;
69
+ let parseLoss = false;
70
+ let terminal = false;
71
+ let finished = false;
72
+ let discardLineFeed = false;
73
+ const report = (data) => {
74
+ if (terminal)
75
+ return;
76
+ if (data === "\n" || data.trim() === ": keepalive")
77
+ return;
78
+ if (data.trim() === "[DONE]") {
79
+ terminal = true;
80
+ call.settled = true;
81
+ return;
82
+ }
83
+ let value;
84
+ try {
85
+ value = JSON.parse(data);
86
+ }
87
+ catch {
88
+ parseLoss = true;
89
+ return;
90
+ }
91
+ if (!record(value))
92
+ return;
93
+ if (Array.isArray(value.choices) && value.choices.some((choice) => record(choice) && typeof choice.finish_reason === "string")) {
94
+ finished = true;
95
+ }
96
+ if (!record(value.usage))
97
+ return;
98
+ const raw = value.usage;
99
+ const input = record(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};
100
+ const output = record(raw.completion_tokens_details) ? raw.completion_tokens_details : {};
101
+ const values = {
102
+ input_tokens: raw.prompt_tokens,
103
+ output_tokens: raw.completion_tokens,
104
+ total_tokens: raw.total_tokens,
105
+ cached_input_tokens: input.cached_tokens,
106
+ reasoning_tokens: output.reasoning_tokens,
107
+ };
108
+ // Repeated streaming usage frames are snapshots of one physical request.
109
+ call.counts = Object.fromEntries(counters.flatMap((field) => {
110
+ const value = count(values[field]);
111
+ return value === undefined ? [] : [[field, value]];
112
+ }));
113
+ call.missing = count(raw.prompt_tokens) === undefined || count(raw.completion_tokens) === undefined;
114
+ };
115
+ const feed = (chunk) => {
116
+ if (terminal)
117
+ return;
118
+ if (streaming && discardLineFeed && chunk.length > 0) {
119
+ discardLineFeed = false;
120
+ if (chunk.startsWith("\n"))
121
+ chunk = chunk.slice(1);
122
+ }
123
+ buffer += chunk;
124
+ if (!streaming) {
125
+ if (buffer.length > MAX_EVENT_CHARACTERS) {
126
+ buffer = "";
127
+ overflow = true;
128
+ parseLoss = true;
129
+ }
130
+ return;
131
+ }
132
+ let newline;
133
+ while (!terminal && (newline = buffer.search(/[\r\n]/u)) !== -1) {
134
+ const line = buffer.slice(0, newline);
135
+ const carriageReturn = buffer[newline] === "\r";
136
+ buffer = buffer.slice(newline + 1);
137
+ if (carriageReturn) {
138
+ // CRLF is one separator even when its bytes arrive in separate chunks.
139
+ if (buffer.length === 0)
140
+ discardLineFeed = true;
141
+ else if (buffer.startsWith("\n"))
142
+ buffer = buffer.slice(1);
143
+ }
144
+ if (line === "") {
145
+ if (event.length > 0 && !overflow)
146
+ report(event);
147
+ event = "";
148
+ overflow = false;
149
+ }
150
+ else if (line.startsWith("data:")) {
151
+ event += `${line.slice(5).replace(/^ /u, "")}\n`;
152
+ if (event.length > MAX_EVENT_CHARACTERS) {
153
+ event = "";
154
+ overflow = true;
155
+ parseLoss = true;
156
+ }
157
+ }
158
+ }
159
+ if (terminal)
160
+ buffer = "";
161
+ else if (buffer.length > MAX_EVENT_CHARACTERS) {
162
+ buffer = "";
163
+ overflow = true;
164
+ parseLoss = true;
165
+ }
166
+ };
167
+ const reader = response.body.getReader();
168
+ const body = new ReadableStream({
169
+ async pull(controller) {
170
+ try {
171
+ const next = await reader.read();
172
+ if (next.done) {
173
+ feed(decoder.decode());
174
+ if (streaming)
175
+ feed("\n\n");
176
+ else if (!overflow)
177
+ report(buffer);
178
+ call.missing ||= parseLoss;
179
+ call.invalid ||= parseLoss;
180
+ call.settled = !streaming || terminal || finished;
181
+ controller.close();
182
+ }
183
+ else {
184
+ feed(decoder.decode(next.value, { stream: true }));
185
+ controller.enqueue(next.value);
186
+ }
187
+ }
188
+ catch (error) {
189
+ call.settled = false;
190
+ call.missing ||= parseLoss;
191
+ call.invalid ||= parseLoss;
192
+ controller.error(error);
193
+ }
194
+ },
195
+ async cancel(reason) {
196
+ // OpenCode discards the unused tail after [DONE], not after finish_reason.
197
+ call.settled = terminal;
198
+ call.missing ||= parseLoss;
199
+ call.invalid ||= parseLoss;
200
+ await reader.cancel(reason);
201
+ },
202
+ }, { highWaterMark: 0 });
203
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
204
+ }
205
+ export class OpenCodeUsageCollector {
206
+ root;
207
+ active;
208
+ titleOwner;
209
+ continuationUncertain = false;
210
+ continuationReasons = new Set();
211
+ requests = new WeakMap();
212
+ sessions = new Map();
213
+ begin(root) {
214
+ this.root = root;
215
+ const usage = new OpenCodeInvocationUsage();
216
+ // Earlier child or background shell work can wake the root during a later prompt.
217
+ // Without an invocation ID in that wakeup, its root requests are ambiguous.
218
+ this.active = this.continuationUncertain ? undefined : usage;
219
+ if (!this.continuationUncertain)
220
+ this.titleOwner = usage;
221
+ usage.uncertain = this.continuationUncertain;
222
+ for (const reason of this.continuationReasons)
223
+ usage.scopeReasons.add(reason);
224
+ return usage;
225
+ }
226
+ markUncertain(reason) {
227
+ this.continuationUncertain = true;
228
+ if (reason !== undefined) {
229
+ this.continuationReasons.add(reason);
230
+ this.active?.scopeReasons.add(reason);
231
+ }
232
+ if (this.active !== undefined)
233
+ this.active.uncertain = true;
234
+ }
235
+ end(usage, scopeProven = false) {
236
+ if (usage.closed)
237
+ return usage.finish(scopeProven);
238
+ if (usage.unfinished())
239
+ this.markUncertain("unfinished_work");
240
+ if (this.active === usage)
241
+ this.active = undefined;
242
+ return usage.finish(scopeProven);
243
+ }
244
+ owner(sessionID) {
245
+ return sessionID === this.root ? this.active : this.sessions.get(sessionID);
246
+ }
247
+ plugin() {
248
+ return {
249
+ id: "nemo-fabric-usage",
250
+ setup: async (context) => {
251
+ const registrations = await Promise.all([
252
+ context.session.hook("prompt", async (event) => {
253
+ if (event.sessionID === this.root)
254
+ return;
255
+ try {
256
+ const visited = new Set();
257
+ let sessionID = event.sessionID;
258
+ while (sessionID !== undefined) {
259
+ if (visited.has(sessionID)) {
260
+ this.markUncertain("child_ancestry_unverified");
261
+ return;
262
+ }
263
+ visited.add(sessionID);
264
+ const session = await context.session.get({ sessionID });
265
+ sessionID = session.parentID;
266
+ const owner = sessionID === undefined ? undefined : this.owner(sessionID);
267
+ if (owner === undefined)
268
+ continue;
269
+ const previous = this.sessions.get(event.sessionID);
270
+ if (previous !== undefined && previous !== owner && previous.unfinished()) {
271
+ owner.uncertain = true;
272
+ owner.scopeReasons.add("child_ownership_changed");
273
+ this.markUncertain("child_ownership_changed");
274
+ return;
275
+ }
276
+ this.sessions.set(event.sessionID, owner);
277
+ owner.children.add(event.sessionID);
278
+ return;
279
+ }
280
+ }
281
+ catch {
282
+ this.markUncertain("child_ancestry_unverified");
283
+ }
284
+ }),
285
+ context.tool.hook("execute.before", (event) => {
286
+ const owner = this.owner(event.sessionID);
287
+ if (owner === undefined)
288
+ return;
289
+ const key = `${event.sessionID}:${event.tool}:${event.id ?? ""}`;
290
+ owner.tools.set(key, (owner.tools.get(key) ?? 0) + 1);
291
+ if (event.tool === "opencode_session_rename" || event.tool === "opencode_session_move") {
292
+ owner.uncertain = true;
293
+ owner.scopeReasons.add("manual_session_change");
294
+ this.markUncertain("manual_session_change");
295
+ }
296
+ }),
297
+ context.tool.hook("execute.after", (event) => {
298
+ const owner = this.owner(event.sessionID);
299
+ if (owner === undefined)
300
+ return;
301
+ const key = `${event.sessionID}:${event.tool}:${event.id ?? ""}`;
302
+ const pending = owner.tools.get(key) ?? 0;
303
+ if (pending <= 1)
304
+ owner.tools.delete(key);
305
+ else
306
+ owner.tools.set(key, pending - 1);
307
+ if (event.tool !== "shell" && event.tool !== "subagent")
308
+ return;
309
+ const output = event.result?.output;
310
+ if (event.status !== "completed" || !record(output)) {
311
+ owner.uncertain = true;
312
+ owner.scopeReasons.add("tool_result_unavailable");
313
+ return;
314
+ }
315
+ if (output.status === "running") {
316
+ owner.uncertain = true;
317
+ const reason = event.tool === "shell" ? "background_shell" : "background_subagent";
318
+ owner.scopeReasons.add(reason);
319
+ this.markUncertain(reason);
320
+ }
321
+ else if (event.tool === "subagent" && output.status === "completed" && typeof output.sessionID === "string") {
322
+ owner.children.delete(output.sessionID);
323
+ }
324
+ }),
325
+ context.session.hook("experimental.ws.handshake", (event) => {
326
+ const owner = this.owner(event.sessionID);
327
+ if (owner !== undefined) {
328
+ owner.uncertain = true;
329
+ owner.scopeReasons.add("unsupported_protocol");
330
+ }
331
+ }),
332
+ context.session.hook("http.request", (event) => {
333
+ const owner = event.sessionID === this.root && event.kind === "title" ? this.titleOwner : this.owner(event.sessionID);
334
+ if (owner === undefined)
335
+ return;
336
+ if (event.kind === "generate") {
337
+ owner.uncertain = true;
338
+ owner.scopeReasons.add("auxiliary_generation");
339
+ this.markUncertain("auxiliary_generation");
340
+ return;
341
+ }
342
+ if (event.kind !== "primary" && event.kind !== "compaction" && event.kind !== "title") {
343
+ owner.uncertain = true;
344
+ owner.scopeReasons.add("unsupported_request_kind");
345
+ }
346
+ const call = { counts: {}, settled: false, missing: true, invalid: false };
347
+ owner.calls.push(call);
348
+ this.requests.set(event.request, call);
349
+ }),
350
+ context.session.hook("http.response", (event) => {
351
+ const call = this.requests.get(event.request);
352
+ if (call === undefined)
353
+ return;
354
+ if (!new URL(event.request.url).pathname.replace(/\/$/u, "").endsWith("/chat/completions")) {
355
+ call.settled = true;
356
+ call.invalid = true;
357
+ return;
358
+ }
359
+ event.response = observeResponse(call, event.response);
360
+ }),
361
+ ]);
362
+ return async () => { await Promise.all(registrations.map((registration) => registration.dispose())); };
363
+ },
364
+ };
365
+ }
366
+ }
@@ -62,6 +62,66 @@
62
62
  },
63
63
  "additionalProperties": false
64
64
  },
65
+ "extension_schemas": {
66
+ "usage": {
67
+ "type": "object",
68
+ "properties": {
69
+ "nvidia.fabric.opencode.usage_evidence.v1": {
70
+ "type": "object",
71
+ "properties": {
72
+ "observed": {
73
+ "type": "object",
74
+ "properties": {
75
+ "input_tokens": {"type": "integer", "minimum": 0, "maximum": 9007199254740991},
76
+ "output_tokens": {"type": "integer", "minimum": 0, "maximum": 9007199254740991},
77
+ "total_tokens": {"type": "integer", "minimum": 0, "maximum": 9007199254740991},
78
+ "cached_input_tokens": {"type": "integer", "minimum": 0, "maximum": 9007199254740991},
79
+ "reasoning_tokens": {"type": "integer", "minimum": 0, "maximum": 9007199254740991}
80
+ },
81
+ "additionalProperties": false
82
+ },
83
+ "scope_reasons": {
84
+ "type": "array",
85
+ "items": {
86
+ "enum": [
87
+ "observer_unavailable",
88
+ "observer_lost",
89
+ "configuration_changed",
90
+ "prepare_scope_read_failed",
91
+ "unsupported_configuration",
92
+ "root_execution_unconfirmed",
93
+ "title_completion_unconfirmed",
94
+ "final_scope_read_failed",
95
+ "child_ancestry_unverified",
96
+ "child_ownership_changed",
97
+ "manual_session_change",
98
+ "tool_result_unavailable",
99
+ "background_shell",
100
+ "background_subagent",
101
+ "unsupported_protocol",
102
+ "auxiliary_generation",
103
+ "unsupported_request_kind",
104
+ "prompt_failed",
105
+ "unfinished_work"
106
+ ]
107
+ },
108
+ "uniqueItems": true,
109
+ "description": "Bounded reasons invocation ownership or completion could not be proved; contains no native messages, commands, or credentials."
110
+ },
111
+ "gaps": {
112
+ "type": "array",
113
+ "items": {"enum": ["scope_unverified", "missing_usage", "unfinished_work"]},
114
+ "uniqueItems": true
115
+ }
116
+ },
117
+ "required": ["observed", "gaps"],
118
+ "additionalProperties": false
119
+ }
120
+ },
121
+ "required": ["nvidia.fabric.opencode.usage_evidence.v1"],
122
+ "additionalProperties": false
123
+ }
124
+ },
65
125
  "capabilities": {
66
126
  "metadata": {"health_checks": ["live", "active", "ready"]},
67
127
  "streaming": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemo-fabric-adapters-opencode",
3
- "version": "0.6.0-rc.1",
3
+ "version": "0.6.0-rc.2",
4
4
  "description": "OpenCode v2 SDK harness adapter for NVIDIA NeMo Fabric.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -42,8 +42,8 @@
42
42
  "bun": ">=1.4.2"
43
43
  },
44
44
  "dependencies": {
45
- "nemo-fabric-adapter-contract": "0.6.0-rc.1",
46
- "nemo-fabric-adapters-common": "0.6.0-rc.1"
45
+ "nemo-fabric-adapter-contract": "0.6.0-rc.2",
46
+ "nemo-fabric-adapters-common": "0.6.0-rc.2"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "@opencode/core": "2.0.23",