opencode-self-improvement 0.15.12 → 0.15.13

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.
@@ -0,0 +1,150 @@
1
+ // Per-setup session binding and caller context (#168). The host object is kept
2
+ // intact so optional API methods retain their receiver and are read at call time.
3
+ import type { GateContext } from "../gate/gate.ts";
4
+ import { captureEvidenceContext, record } from "../evidence/record.ts";
5
+ import { unresolvedWriteMessage } from "../store/files/append.ts";
6
+ import { readerFromSid } from "../store/model/visibility.ts";
7
+ import { getCurrent } from "../core/state.ts";
8
+ import { SESSION_CAP, SessionLru } from "../core/lru.ts";
9
+ import { writeEvidence, hasGateCheck, hasEngagement } from "../capture/triggers.ts";
10
+ import { bindSessionProvisional, writeTarget, sessionDir, sessionDirFirm, rememberSessionDir } from "./repokey.ts";
11
+ import { toolIdentity, sessionDirectoryFromMessages, sessionDirectoryFromRow } from "./host-events.ts";
12
+
13
+ interface SessionLookupHost {
14
+ session?: {
15
+ context?: (input: { sessionID: string }) => Promise<unknown>;
16
+ get?: (input: { sessionID: string }) => Promise<unknown>;
17
+ };
18
+ }
19
+
20
+ export function createSessionContext(
21
+ ctx: SessionLookupHost,
22
+ { instanceDir, liveRoot }: { instanceDir: string | undefined; liveRoot: string },
23
+ ) {
24
+ const gateContext = (sid?: string): GateContext => {
25
+ // Every session-scoped member resolves for the CALLER's session when it
26
+ // knows one (#116): capture awaits a model call between setCurrent and
27
+ // persistence, and on a multi-session server the global current moves
28
+ // during that await. Falling back to getCurrent() is exactly today's
29
+ // behavior for callers whose current IS their session (tool hooks).
30
+ const bound = sid ?? getCurrent().sid;
31
+ return {
32
+ sessionID: sid,
33
+ reader: readerFromSid(sid),
34
+ writeAt: writeTarget(bound),
35
+ evidenceContext: captureEvidenceContext(sid),
36
+ // NOTE (re-review): this one lookup is intentionally NON-firm — a
37
+ // provisional binding may supply the gate's verification TREE. The
38
+ // tree is where a referenced file is checked to exist, not who the
39
+ // caller is: "as far as the flow can know" is the right confidence
40
+ // level, and a wrong guess fails a code-reference gate loudly rather
41
+ // than leaking across repositories. Identity itself never resolves
42
+ // through here (readers and stamps use the firm-or-provisional split
43
+ // in repokey/memory); do not mistake this for one.
44
+ liveRoot: sessionDir(bound) ?? liveRoot,
45
+ ...writeEvidence(bound),
46
+ hasGateCheck: hasGateCheck(bound),
47
+ hasEngagement: hasEngagement(bound),
48
+ };
49
+ };
50
+
51
+ // A durable write needs an OWNER (#152). Reads already fail closed for a
52
+ // session whose repository never resolved — it sees global rows and nothing
53
+ // else — so such a session may not write either: the alternatives were the
54
+ // last setup's repository or an unstamped (hence global) row. This answers
55
+ // at the entry, where the model can be told what to do, and records the
56
+ // refusal so "why is nothing stored" is answerable from memory_evidence.
57
+ // appendMemory throws the same rule at the choke point; the two share one
58
+ // message so they cannot drift.
59
+ const ownerlessWriter = (sid: string | undefined): string | null => {
60
+ const target = writeTarget(sid);
61
+ return target.ok ? null : target.sid;
62
+ };
63
+
64
+ const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
65
+ await record("write_refused", { op }, true, sid);
66
+ return { content: unresolvedWriteMessage(sid) };
67
+ };
68
+
69
+ // Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
70
+ // the first await of the call comes after this. The V2 host hands every
71
+ // execute a per-call ToolContext carrying sessionID; the harness and any
72
+ // host that omits it fall back to the ambient current, which is correct
73
+ // exactly because execute.before ran immediately before this tool with
74
+ // no await between (#116's documented fallback). Never re-read the global
75
+ // after an await to learn who is calling (#127).
76
+ const toolIds = (context?: unknown): { sid: string; call: string } => {
77
+ const { sessionID: fromCtx, callID: call } = toolIdentity(context);
78
+ // Entry binding: a session this instance has never seen is resolved to
79
+ // THIS workspace (provisional — a firm event/API identity still
80
+ // replaces it), so the tool's reader partitions by the repository the
81
+ // call reached, not by the last setup's module scope (#127).
82
+ if (fromCtx && fromCtx !== "?") {
83
+ bindSessionProvisional(fromCtx, instanceDir);
84
+ }
85
+ return {
86
+ sid: fromCtx ?? getCurrent().sid,
87
+ call: call ?? getCurrent().call,
88
+ };
89
+ };
90
+
91
+ // Identity-event race backstop: a resumed session's FIRST turn can write
92
+ // before the subscription has delivered its execution.started, and the
93
+ // module-scope fallback is the last setup instance — possibly another
94
+ // workspace. Bind once from the session context API for unmapped sids —
95
+ // but note host 2.1.4 sends message payloads WITHOUT any location field,
96
+ // so this path is a legacy-shape best-effort; the session-row fallback
97
+ // below is what actually resolves serve-host sessions.
98
+ // One-shot: never overwrites an event-bound entry.
99
+ const bindingSids = new Set<string>();
100
+ async function bindSessionFromMessages(sid: string | undefined): Promise<void> {
101
+ if (!sid || sid === "?" || sessionDirFirm(sid) || bindingSids.has(sid)) return;
102
+ bindingSids.add(sid);
103
+ try {
104
+ const msgs = await ctx.session?.context?.({ sessionID: sid });
105
+ const dir = sessionDirectoryFromMessages(msgs);
106
+ if (dir !== undefined) rememberSessionDir(sid, dir);
107
+ } catch {
108
+ // no context access or host error: the event stream still binds later
109
+ } finally {
110
+ bindingSids.delete(sid);
111
+ }
112
+ }
113
+
114
+ // Serve-host reality (recorded on 2.1.4 `serve --service`): the plugin
115
+ // instance loads AFTER the session was created, so `session.created` — the
116
+ // only event carrying a location — is never delivered; `execution.started`
117
+ // arrives with just {sessionID}. The session ROW is the remaining source
118
+ // of truth: the host's session get returns `location.directory`. One
119
+ // lookup per session; a miss is remembered so a host without the API is
120
+ // not re-asked on every turn (bounded LRU, same cap as the scope cache).
121
+ const apiBindTried = new Set<string>();
122
+ const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) => apiBindTried.delete(evicted));
123
+ async function bindSessionFromApi(sid: string | undefined): Promise<void> {
124
+ if (!sid || sid === "?" || sessionDirFirm(sid) || apiBindTried.has(sid)) return;
125
+ apiBindTried.add(sid);
126
+ apiBindOrder.touch(sid);
127
+ try {
128
+ const got = await ctx.session?.get?.({ sessionID: sid });
129
+ const dir = sessionDirectoryFromRow(got);
130
+ if (dir !== undefined) rememberSessionDir(sid, dir);
131
+ } catch {
132
+ // no session.get on this host (or unknown session): stay unbound
133
+ }
134
+ }
135
+
136
+ // Identity must resolve BEFORE a row is stamped or a read is partitioned:
137
+ // try the (legacy) message payloads, then the session row. A session the
138
+ // host cannot describe (fresh, or a host without the lookup) is bound to
139
+ // THIS instance's workspace — the caller's repository as the flow knows
140
+ // it, and strictly better than an unbound read inheriting the module
141
+ // scope of whoever loaded last (#127's multi-setup residue).
142
+ async function bindSessionIdentity(sid: string | undefined): Promise<void> {
143
+ if (!sid || sid === "?" || sessionDirFirm(sid)) return;
144
+ await bindSessionFromMessages(sid);
145
+ if (!sessionDirFirm(sid)) await bindSessionFromApi(sid);
146
+ bindSessionProvisional(sid, instanceDir);
147
+ }
148
+
149
+ return { gateContext, ownerlessWriter, refuseOwnerlessWrite, toolIds, bindSessionFromApi, bindSessionIdentity };
150
+ }