opencode-self-improvement 0.15.14 → 0.15.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.14",
3
+ "version": "0.15.15",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -9,6 +9,7 @@ import { captureSessionID } from "../identity/host-events.ts";
9
9
  import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
10
10
  import { redactSecrets } from "../store/secrets.ts";
11
11
  import { parseCandidates, parseModelRef } from "./candidates.ts";
12
+ import { sessionModel, type SessionModelRef } from "./session-model.ts";
12
13
  import { lagSince } from "./lag.ts";
13
14
  import { buildCapturePrompt } from "./prompt.ts";
14
15
  import { flattenTranscript } from "./transcript.ts";
@@ -18,6 +19,9 @@ interface CaptureHost {
18
19
  event?: { subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown> };
19
20
  generate?: { text: (input: unknown) => Promise<{ text?: string } | string> };
20
21
  session?: { context?: (input: { sessionID: string }) => Promise<unknown> };
22
+ // Host default model (#139): the last-resort source for an omitted
23
+ // captureModel. Optional-call everywhere: older/fake hosts expose none.
24
+ model?: { default?: { get?: () => { providerID: string; modelID: string } | undefined } };
21
25
  }
22
26
 
23
27
  interface CaptureDependencies {
@@ -94,16 +98,24 @@ export function configureAutoCapture(
94
98
  let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
95
99
  let captureCleanup: Cleanup | undefined;
96
100
  if (ctx.options?.autoCapture === true) {
97
- const captureModel =
98
- typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
101
+ const captureModelOpt = ctx.options.captureModel;
102
+ // #139: an OMITTED captureModel no longer disables the subscription. It
103
+ // resolves per capture — the per-session ref last seen on session.context,
104
+ // else the host default — and only when both are missing does the pass
105
+ // skip. autoCapture:true is already the explicit opt-in; a second required
106
+ // config string was a syntax tax whose failure mode was a console.warn
107
+ // nobody reads. An explicit but INVALID captureModel keeps today's
108
+ // fail-closed setup behaviour: silently substituting another model than
109
+ // the one the user typed is worse than the tax it replaces.
110
+ const omitted = captureModelOpt === undefined;
99
111
  const captureMax = Number(ctx.options.captureMax) || 3;
100
112
  const captureOnCompact = ctx.options?.captureOnCompact !== false;
101
- const modelRef = parseModelRef(captureModel);
102
- if (!modelRef) {
103
- // Invalid/missing model: skip registering the whole subscription
113
+ const modelRef = omitted ? null : parseModelRef(captureModelOpt);
114
+ if (!omitted && !modelRef) {
115
+ // Invalid explicit model: skip registering the whole subscription
104
116
  // rather than guess (and warn once, at setup).
105
117
  console.warn(
106
- `[opencode-self-improvement] autoCapture is on but captureModel ${JSON.stringify(captureModel)} is invalid (expected "provider/id"); auto-capture disabled.`,
118
+ `[opencode-self-improvement] autoCapture is on but captureModel ${JSON.stringify(captureModelOpt)} is invalid (expected "provider/id"); auto-capture disabled.`,
107
119
  );
108
120
  } else if (!ctx.event?.subscribe || !ctx.generate?.text || !ctx.session?.context) {
109
121
  console.warn(
@@ -120,6 +132,21 @@ export function configureAutoCapture(
120
132
  // into the closure, and undefined degrades safely (empty transcript).
121
133
  const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
122
134
 
135
+ // #139 model resolution: explicit option (captured above) wins; else the
136
+ // ref this session's context hook last carried; else the host default.
137
+ // Warn-once per setup when even the last resort is empty — a per-event
138
+ // warn would spam the log for every turn of a model-less session.
139
+ let warnedNoModel = false;
140
+ const hostDefault = (): SessionModelRef | null => {
141
+ const d = ctx.model?.default?.get?.();
142
+ if (
143
+ d && typeof d.providerID === "string" && d.providerID &&
144
+ typeof d.modelID === "string" && d.modelID
145
+ )
146
+ return { providerID: d.providerID, id: d.modelID };
147
+ return null;
148
+ };
149
+
123
150
  // ONE capture pass, shared by both triggers. `seeded` is a transcript
124
151
  // already in hand — the compaction hook carries the PRE-compaction
125
152
  // messages, which is the whole point (Compaction Cliff: one round
@@ -145,12 +172,29 @@ export function configureAutoCapture(
145
172
  // zero-token promise of the capture tests.
146
173
  bindSessionProvisional(sid, instanceDir);
147
174
  const captureGate = gateContext(sid);
175
+ // #139: resolve the model BEFORE any skip so every capture evidence
176
+ // line below can carry model= (cost attributable to a named model —
177
+ // the real answer to the cost-surprise concern that justified the
178
+ // required captureModel). Resolution itself is token-free.
179
+ const model = modelRef ?? sessionModel(sid) ?? hostDefault();
180
+ const modelTag = model ? `${model.providerID}/${model.id}` : undefined;
148
181
  // #152: an instance with no workspace cannot say which repository the
149
182
  // mined rows belong to, and rows with no owner are exactly what the
150
183
  // store refuses. Skip BEFORE the model call — no tokens spent on a
151
184
  // capture that cannot be stored — and leave the reason in evidence.
152
185
  if (!writeTarget(sid).ok) {
153
- await record("auto_capture_refused", { session: sid, trigger }, true, sid, captureGate.evidenceContext);
186
+ await record("auto_capture_refused", { session: sid, trigger, ...(modelTag ? { model: modelTag } : {}) }, true, sid, captureGate.evidenceContext);
187
+ return;
188
+ }
189
+ if (!model) {
190
+ // Both inheritance sources empty: today's last resort, warn + skip.
191
+ if (!warnedNoModel) {
192
+ warnedNoModel = true;
193
+ console.warn(
194
+ "[opencode-self-improvement] autoCapture is on but captureModel is omitted and neither session.context nor the host default names a model; capture skipped (warned once).",
195
+ );
196
+ }
197
+ await record("auto_capture_refused", { session: sid, trigger, reason: "no_model" }, true, sid, captureGate.evidenceContext);
154
198
  return;
155
199
  }
156
200
  let transcript = seeded;
@@ -166,7 +210,7 @@ export function configureAutoCapture(
166
210
  // session context for idle), so both triggers' lag is comparable.
167
211
  const lagMs = lagSince(msgs);
168
212
  const out = await generateApi.text({
169
- model: modelRef,
213
+ model,
170
214
  // Redact the COMPLETE transcript, THEN apply the character budget
171
215
  // (#132). Cropping first can start the window INSIDE a credential:
172
216
  // a PEM body whose BEGIN marker fell off, or a token whose prefix
@@ -195,7 +239,7 @@ export function configureAutoCapture(
195
239
  // wrapper. Preserve any earlier gate retirements in the receipt.
196
240
  await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
197
241
  session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
198
- reason: String(err), retired: durable.join(",") || undefined,
242
+ reason: String(err), retired: durable.join(",") || undefined, model: modelTag,
199
243
  }, false, sid, captureGate.evidenceContext);
200
244
  continue;
201
245
  }
@@ -214,13 +258,14 @@ export function configureAutoCapture(
214
258
  scope: redactSecrets(c.scope),
215
259
  reason: outcome.reason ?? "",
216
260
  audit_error: outcome.evidenceError,
261
+ model: modelTag,
217
262
  },
218
263
  false,
219
264
  sid,
220
265
  captureGate.evidenceContext,
221
266
  );
222
267
  }
223
- await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty", captureGate.evidenceContext);
268
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty", captureGate.evidenceContext, modelTag);
224
269
  }
225
270
 
226
271
  void (async () => {
@@ -0,0 +1,45 @@
1
+ // Per-session model registry (#139). The SDK's SessionRequest declares a
2
+ // readonly `model: Model.Ref`, so EVERY session hook the plugin registers
3
+ // already carries the session's actual model — the session.context hook reads
4
+ // event.sessionID and never event.model, and auto-capture required a second
5
+ // config key (captureModel) it could have inherited for free. This module is
6
+ // the seam: events.ts records the ref the host delivered, capture/runtime.ts
7
+ // resolves an omitted captureModel through it before falling back to the host
8
+ // default. Module-level like `lastCaptureRun` in runtime.ts (#108): setup runs
9
+ // for more than one location, and a per-closure map would make those
10
+ // registrations strangers to the model the host just told them.
11
+ export interface SessionModelRef {
12
+ providerID: string;
13
+ id: string;
14
+ }
15
+
16
+ const lastModel = new Map<string, SessionModelRef>();
17
+
18
+ /**
19
+ * Record the model ref a session hook carried. Total: a malformed or absent
20
+ * `event.model` is ignored, never stored — the caller then falls through to
21
+ * the host default, exactly as if the hook had not run.
22
+ */
23
+ export function recordSessionModel(sid: string, model: unknown): void {
24
+ if (!model || typeof model !== "object") return;
25
+ const m = model as Record<string, unknown>;
26
+ const providerID = typeof m.providerID === "string" ? m.providerID.trim() : "";
27
+ const id = typeof m.id === "string" ? m.id.trim() : "";
28
+ if (!providerID || !id) return;
29
+ // Sessions churn and a long-lived server must not grow one entry per
30
+ // session forever; oldest-inserted go first (the cooldown map's rule).
31
+ if (lastModel.size > 2000) {
32
+ for (const k of [...lastModel.keys()].slice(0, 1000)) lastModel.delete(k);
33
+ }
34
+ lastModel.set(sid, { providerID, id });
35
+ }
36
+
37
+ /** The ref last seen for this session, or null when the host never delivered one. */
38
+ export function sessionModel(sid: string): SessionModelRef | null {
39
+ return lastModel.get(sid) ?? null;
40
+ }
41
+
42
+ /** Clear the registry (tests; also what a process restart does). */
43
+ export function resetSessionModels(): void {
44
+ lastModel.clear();
45
+ }
package/src/events.ts CHANGED
@@ -11,6 +11,7 @@ import { setCurrent } from "./core/state.ts";
11
11
  import { bindSessionProvisional, rememberSessionDir } from "./identity/repokey.ts";
12
12
  import { sessionIdentityEvent, sessionUsageEvent } from "./identity/host-events.ts";
13
13
  import { afterTool, markTurn, checkNewSession, onCompacting } from "./capture/triggers.ts";
14
+ import { recordSessionModel } from "./capture/session-model.ts";
14
15
  import { contextualPull } from "./inject/pull.ts";
15
16
  import { pullQuery } from "./recall/relevant.ts";
16
17
  import { compactionAnchor } from "./inject/anchor.ts";
@@ -108,6 +109,10 @@ export async function registerHooks(
108
109
  const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
109
110
  setCurrent({ sessionID: event?.sessionID });
110
111
  if (typeof sid === "string") sessions.touch(sid);
112
+ // #139: SessionRequest declares a readonly model, so the host already
113
+ // tells us which model this session runs on. Remember it: an omitted
114
+ // captureModel inherits it in capture/runtime.ts.
115
+ if (typeof sid === "string") recordSessionModel(sid, event?.model);
111
116
  // Resolve WHOSE repository this injection reads before the store
112
117
  // read below: an unbound session would otherwise fall to global-only
113
118
  // and silently lose its own frontier rows. SYNC provisional bind to
@@ -141,6 +141,10 @@ export async function recordCaptureLag(
141
141
  lagMs: number | null,
142
142
  outcome: string,
143
143
  context?: EvidenceContext,
144
+ // #139: the model the capture actually ran on, so a cost audit can join a
145
+ // lag line to the model that spent the tokens. Optional: metric tests and
146
+ // any caller without a resolved model keep the old shape.
147
+ model?: string,
144
148
  ): Promise<void> {
145
149
  await record(
146
150
  "capture_lag",
@@ -148,6 +152,7 @@ export async function recordCaptureLag(
148
152
  session,
149
153
  ...(lagMs !== null && Number.isFinite(lagMs) && lagMs >= 0 ? { lag: Math.round(lagMs) } : {}),
150
154
  outcome,
155
+ ...(model ? { model } : {}),
151
156
  },
152
157
  false,
153
158
  session,
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ import { formatMemory } from "./inject/format.ts"
37
37
  import { sharedTerms } from "./recall/shared-terms.ts";
38
38
  import { configureAutoCapture, CAPTURE_EVENT_TYPES } from "./capture/runtime.ts";
39
39
  export { resetCaptureCooldowns, TURN_END_EVENTS, CAPTURE_EVENT_TYPES, captureTriggerFor } from "./capture/runtime.ts";
40
+ export { resetSessionModels } from "./capture/session-model.ts";
40
41
  import { createInjectionEpochs } from "./inject/epochs.ts";
41
42
  import { createSessionContext } from "./identity/session-context.ts";
42
43
  import { registerMemoryTools } from "./tools/registry.ts";
@@ -208,9 +209,11 @@ const impl = {
208
209
  // a heartbeat with an unknown version still beats no heartbeat
209
210
  }
210
211
  const wantCapture = ctx.options?.autoCapture === true;
211
- const modelOk = !!parseModelRef(
212
- typeof ctx.options?.captureModel === "string" ? ctx.options.captureModel : "",
213
- );
212
+ // #139: an omitted captureModel is a valid arm — the capture inherits
213
+ // the session's model (session.context) or the host default. Only an
214
+ // explicit but malformed string is invalid_model.
215
+ const captureModelOpt = ctx.options?.captureModel;
216
+ const modelOk = captureModelOpt === undefined || !!parseModelRef(captureModelOpt);
214
217
  const capabilities = ["event.subscribe", "generate.text", "session.context"].filter((name) => {
215
218
  const [domain, method] = name.split(".");
216
219
  return typeof (ctx as unknown as Record<string, any>)?.[domain]?.[method] === "function";