opencode-self-improvement 0.33.9 → 0.33.11
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 +1 -1
- package/docs/internals/use-ledger.md +45 -4
- package/package.json +1 -1
- package/src/capture/attest.ts +168 -0
- package/src/capture/runtime.ts +112 -72
- package/src/consolidate/propose.ts +27 -29
- package/src/consolidate/render.ts +5 -1
- package/src/events.ts +128 -26
- package/src/index.ts +6 -3
- package/src/inject/pull-receipts.ts +215 -0
- package/src/inject/pull.ts +10 -9
- package/src/portable/decay.ts +4 -5
- package/src/status/report.ts +35 -2
- package/src/store/lock.ts +79 -101
- package/src/telemetry/ledger.ts +54 -6
- package/src/telemetry/record.ts +134 -0
- package/src/tools/merge-review.ts +70 -7
- package/src/tools/schema.ts +6 -0
- package/src/tools/status-tool.ts +4 -0
|
@@ -26,7 +26,11 @@
|
|
|
26
26
|
// 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
|
|
27
27
|
// proposal through memory_merge_review (supersede-not-delete, recoverable).
|
|
28
28
|
// 4. The most recently used member is never a loser (the rule, inherited).
|
|
29
|
-
import
|
|
29
|
+
import {
|
|
30
|
+
MAX_KEYWORDS,
|
|
31
|
+
type Memory,
|
|
32
|
+
normalizeKeywords,
|
|
33
|
+
} from "../store/model/memory.ts";
|
|
30
34
|
import type { UseSignal } from "../telemetry/ledger.ts";
|
|
31
35
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
32
36
|
import { formatMemory } from "../inject/format.ts";
|
|
@@ -36,7 +40,17 @@ import { scoreMemories, words } from "../recall/score.ts";
|
|
|
36
40
|
export const DEFAULT_JACCARD = 0.55;
|
|
37
41
|
|
|
38
42
|
/** Aliases are useful up to a point; a merged row that hoards 60 words is noise. */
|
|
39
|
-
export const MAX_MERGED_KW =
|
|
43
|
+
export const MAX_MERGED_KW = MAX_KEYWORDS;
|
|
44
|
+
|
|
45
|
+
/** Copying aliases must preserve the original rows' visibility. */
|
|
46
|
+
export function sameConsolidationScope(a: Memory, b: Memory): boolean {
|
|
47
|
+
return (
|
|
48
|
+
a.type === b.type &&
|
|
49
|
+
a.scope === b.scope &&
|
|
50
|
+
(a.repo ?? "global") === (b.repo ?? "global") &&
|
|
51
|
+
a.repoPath === b.repoPath
|
|
52
|
+
);
|
|
53
|
+
}
|
|
40
54
|
|
|
41
55
|
export interface ReadSet {
|
|
42
56
|
/** The terms a real read used, exactly as the ledger recorded them. */
|
|
@@ -106,7 +120,7 @@ export function clustersFor(
|
|
|
106
120
|
for (let j = i + 1; j < pool.length; j++) {
|
|
107
121
|
const a = pool[i]!;
|
|
108
122
|
const b = pool[j]!;
|
|
109
|
-
if (a
|
|
123
|
+
if (!sameConsolidationScope(a, b)) continue;
|
|
110
124
|
if (jaccard(toks[i]!, toks[j]!) >= min) union(i, j);
|
|
111
125
|
}
|
|
112
126
|
}
|
|
@@ -160,36 +174,20 @@ export interface MergePlan {
|
|
|
160
174
|
reasons: string[];
|
|
161
175
|
}
|
|
162
176
|
|
|
163
|
-
/**
|
|
164
|
-
function
|
|
177
|
+
/** One printed resolution step. Replay and persistence use the same keyword budget. */
|
|
178
|
+
export function absorbAliases(survivor: Memory, loser: Memory): Memory {
|
|
165
179
|
const have = new Set(
|
|
166
180
|
words(`${survivor.content} ${(survivor.kw ?? []).join(" ")}`),
|
|
167
181
|
);
|
|
168
|
-
const out = [...(survivor.kw ?? [])];
|
|
169
|
-
for (const m of cluster) {
|
|
170
|
-
if (m.ts === survivor.ts) continue;
|
|
171
|
-
for (const k of m.kw ?? []) if (!out.includes(k)) out.push(k);
|
|
172
|
-
// Only distinctive words the absorbed row was FOUND by, in practice: its
|
|
173
|
-
// own vocabulary minus what the survivor already carries.
|
|
174
|
-
for (const w of words(m.content)) {
|
|
175
|
-
if (!have.has(w) && !out.includes(w)) out.push(w);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
return out.slice(0, MAX_MERGED_KW);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function buildMerged(cluster: Memory[], survivor: Memory): Memory {
|
|
182
|
-
const kw = inheritedKw(cluster, survivor);
|
|
183
182
|
return {
|
|
184
183
|
...survivor,
|
|
185
|
-
kw:
|
|
186
|
-
|
|
187
|
-
...
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
].slice(0, 12),
|
|
184
|
+
kw: normalizeKeywords([
|
|
185
|
+
...(survivor.kw ?? []),
|
|
186
|
+
...(loser.kw ?? []),
|
|
187
|
+
...words(loser.content).filter((word) => !have.has(word)),
|
|
188
|
+
]),
|
|
189
|
+
// The surviving prose keeps its own provenance.
|
|
190
|
+
tags: [...new Set([...(survivor.tags ?? []), "consolidated"])],
|
|
193
191
|
};
|
|
194
192
|
}
|
|
195
193
|
|
|
@@ -246,7 +244,7 @@ export function proposeCluster(
|
|
|
246
244
|
): MergePlan {
|
|
247
245
|
const survivor = survivorFor(cluster, use);
|
|
248
246
|
const losers = cluster.filter((m) => m !== survivor);
|
|
249
|
-
const merged =
|
|
247
|
+
const merged = losers.reduce(absorbAliases, survivor);
|
|
250
248
|
const reads = readsFor(cluster, allReads);
|
|
251
249
|
|
|
252
250
|
// The bar the ticket sets: the merged row must catch at least as many of the
|
|
@@ -23,7 +23,10 @@ export function renderProposals(report: ProposalReport): string {
|
|
|
23
23
|
),
|
|
24
24
|
` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
|
|
25
25
|
` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
|
|
26
|
-
|
|
26
|
+
...p.losers.map(
|
|
27
|
+
(loser) =>
|
|
28
|
+
` resolve: memory_merge_review(loser="${loser.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}", consolidate=true)`,
|
|
29
|
+
),
|
|
27
30
|
"",
|
|
28
31
|
);
|
|
29
32
|
}
|
|
@@ -32,6 +35,7 @@ export function renderProposals(report: ProposalReport): string {
|
|
|
32
35
|
`injected ${report.injectedBefore}c → ${report.injectedAfter}c`,
|
|
33
36
|
);
|
|
34
37
|
out.push(
|
|
38
|
+
"Run each proposal's resolve commands from top to bottom to retain the keywords used in its read estimate.",
|
|
35
39
|
"Resolving is supersede-not-delete: absorbed rows stay recoverable via memory_undo.",
|
|
36
40
|
);
|
|
37
41
|
return out.join("\n");
|
package/src/events.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Host hook registration and measured-usage listener. Setup owns the
|
|
2
2
|
// returned controller and supplies the live compaction-capture callback.
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
3
4
|
import type { PluginCtx } from "./core/host.ts";
|
|
4
5
|
import type { guarded as Guarded } from "./core/hooks.ts";
|
|
5
6
|
import type { createInjectionEpochs } from "./inject/epochs.ts";
|
|
@@ -27,13 +28,28 @@ import { recordSessionModel } from "./capture/session-model.ts";
|
|
|
27
28
|
import {
|
|
28
29
|
contextualPull,
|
|
29
30
|
PULL_SHIPPED,
|
|
31
|
+
PULL_HEADER,
|
|
30
32
|
type PullScope,
|
|
31
33
|
pullQueryFor,
|
|
32
34
|
writePullIntoResult,
|
|
33
35
|
} from "./inject/pull.ts";
|
|
34
|
-
import {
|
|
36
|
+
import { createPullReceipts, type PullLoss } from "./inject/pull-receipts.ts";
|
|
37
|
+
import { formatMemory } from "./inject/format.ts";
|
|
38
|
+
import { peekTurn } from "./core/state.ts";
|
|
39
|
+
import { captureEvidenceContext, record } from "./telemetry/record.ts";
|
|
35
40
|
import { compactionAnchor } from "./inject/anchor.ts";
|
|
36
41
|
|
|
42
|
+
/** Placement and observation clocks for a deferred pull receipt. */
|
|
43
|
+
export interface RideAt {
|
|
44
|
+
lockWaitMs: number;
|
|
45
|
+
tool: string;
|
|
46
|
+
evidence: ReturnType<typeof captureEvidenceContext>;
|
|
47
|
+
placedAt: number;
|
|
48
|
+
observedAt: number;
|
|
49
|
+
turn?: number;
|
|
50
|
+
turnKey?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
37
53
|
interface HookDependencies {
|
|
38
54
|
guarded: typeof Guarded;
|
|
39
55
|
sessions: ReturnType<typeof createInjectionEpochs>;
|
|
@@ -44,6 +60,7 @@ interface HookDependencies {
|
|
|
44
60
|
sid: string,
|
|
45
61
|
rows: Memory[],
|
|
46
62
|
query: string,
|
|
63
|
+
at?: RideAt,
|
|
47
64
|
) => Promise<void>;
|
|
48
65
|
bindSessionIdentity: (sid: string | undefined) => Promise<void>;
|
|
49
66
|
bindSessionFromApi: (sid: string | undefined) => Promise<void>;
|
|
@@ -82,6 +99,26 @@ function resultMeta(result: unknown): Record<string, unknown> {
|
|
|
82
99
|
return {};
|
|
83
100
|
}
|
|
84
101
|
|
|
102
|
+
// Counts only: a lost pull names its tool and how many rows, never the rows'
|
|
103
|
+
// text or the tool's output. `trimmed` is the same failure `pull_undelivered`
|
|
104
|
+
// already names at placement, seen one step later.
|
|
105
|
+
async function reportPullLosses(losses: PullLoss[]): Promise<void> {
|
|
106
|
+
for (const loss of losses)
|
|
107
|
+
await record(
|
|
108
|
+
loss.reason === "trimmed" ? "pull_undelivered" : "pull_unconfirmed",
|
|
109
|
+
{
|
|
110
|
+
tool: loss.held.tool,
|
|
111
|
+
rows: loss.rows,
|
|
112
|
+
...(loss.reason === "trimmed"
|
|
113
|
+
? { stage: "request" }
|
|
114
|
+
: { reason: loss.reason }),
|
|
115
|
+
},
|
|
116
|
+
false,
|
|
117
|
+
loss.held.sid,
|
|
118
|
+
loss.held.evidence,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
85
122
|
export async function registerHooks(
|
|
86
123
|
ctx: PluginCtx,
|
|
87
124
|
{
|
|
@@ -98,6 +135,9 @@ export async function registerHooks(
|
|
|
98
135
|
getCompactCapture,
|
|
99
136
|
}: HookDependencies,
|
|
100
137
|
) {
|
|
138
|
+
// Pulls placed on a tool result, waiting for the request that carries them.
|
|
139
|
+
const receipts = createPullReceipts();
|
|
140
|
+
|
|
101
141
|
// Bookkeeping: track the active session/tool/call before a tool runs.
|
|
102
142
|
await ctx.tool?.hook("execute.before", (event: any) =>
|
|
103
143
|
guarded("tool.execute.before", async () => {
|
|
@@ -125,6 +165,7 @@ export async function registerHooks(
|
|
|
125
165
|
if (typeof event?.sessionID === "string") {
|
|
126
166
|
bindSessionProvisional(event.sessionID, instanceDir);
|
|
127
167
|
}
|
|
168
|
+
const evidence = captureEvidenceContext(input.sessionID);
|
|
128
169
|
const out = {
|
|
129
170
|
output: resultText(event?.result),
|
|
130
171
|
metadata: resultMeta(event?.result),
|
|
@@ -133,50 +174,111 @@ export async function registerHooks(
|
|
|
133
174
|
// Capture the text BEFORE the pull appends to it, so the write-back can
|
|
134
175
|
// place just the appended block instead of duplicating the tool output.
|
|
135
176
|
const textBefore = typeof out.output === "string" ? out.output : "";
|
|
177
|
+
const header = `${PULL_HEADER} [${randomBytes(8).toString("hex")}]`;
|
|
136
178
|
const pulled = await contextualPull(
|
|
137
179
|
input,
|
|
138
180
|
out as { output?: unknown },
|
|
139
181
|
budget,
|
|
140
182
|
await useSignals(),
|
|
141
183
|
pullScope,
|
|
184
|
+
header,
|
|
142
185
|
);
|
|
143
|
-
// Deliver FIRST, credit AFTER: the ledger counts rows the model was shown.
|
|
144
|
-
// The old order credited every computed pull, so a result shape the host
|
|
145
|
-
// no longer hands back as a string (v2.3.0 sends a parts ARRAY) left 456
|
|
146
|
-
// `src=pull` credits against zero bytes delivered — the exact overclaim
|
|
147
|
-
// this ledger exists to avoid. `pull_undelivered` makes the failure
|
|
148
|
-
// readable instead of merely smaller.
|
|
149
186
|
const shown =
|
|
150
187
|
pulled.length > 0 && typeof out.output === "string"
|
|
151
188
|
? writePullIntoResult(event?.result, textBefore, out.output)
|
|
152
189
|
: false;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
190
|
+
// Placed is not yet delivered: a later plugin's execute.after hook can
|
|
191
|
+
// still trim this result. Hold the credit; the next request for
|
|
192
|
+
// this session settles it against the tool-result it actually carries.
|
|
193
|
+
// Turn and time are read NOW, so the credit names the turn the ride
|
|
194
|
+
// landed on and throttles on the placement's own clock.
|
|
195
|
+
const sid = String(event?.sessionID ?? "");
|
|
196
|
+
const callID = typeof input.callID === "string" ? input.callID : "";
|
|
197
|
+
if (shown && sid && callID) {
|
|
198
|
+
const observed = peekTurn(sid);
|
|
199
|
+
await reportPullLosses(
|
|
200
|
+
receipts.hold({
|
|
201
|
+
sid,
|
|
202
|
+
callID,
|
|
203
|
+
header,
|
|
204
|
+
evidence,
|
|
205
|
+
tool: String(event?.tool ?? ""),
|
|
206
|
+
rows: pulled,
|
|
207
|
+
lines: pulled.map(formatMemory),
|
|
208
|
+
query: pullQueryFor(
|
|
209
|
+
String(event?.tool ?? ""),
|
|
210
|
+
input.args,
|
|
211
|
+
textBefore,
|
|
212
|
+
pullScope,
|
|
213
|
+
),
|
|
214
|
+
at: Date.now(),
|
|
215
|
+
turn: observed?.turn,
|
|
216
|
+
turnKey: observed?.key,
|
|
217
|
+
}),
|
|
218
|
+
);
|
|
219
|
+
} else if (shown)
|
|
220
|
+
// No session or call ID: no request can be matched to this placement,
|
|
221
|
+
// so it is reported and never credited.
|
|
222
|
+
await record(
|
|
223
|
+
"pull_unconfirmed",
|
|
224
|
+
{
|
|
225
|
+
tool: String(event?.tool ?? ""),
|
|
226
|
+
rows: pulled.length,
|
|
227
|
+
reason: "no_call",
|
|
228
|
+
},
|
|
229
|
+
false,
|
|
230
|
+
input.sessionID,
|
|
231
|
+
evidence,
|
|
167
232
|
);
|
|
168
233
|
else if (pulled.length)
|
|
169
234
|
await record(
|
|
170
235
|
"pull_undelivered",
|
|
171
236
|
{ tool: String(event?.tool ?? ""), rows: pulled.length },
|
|
172
237
|
false,
|
|
238
|
+
input.sessionID,
|
|
239
|
+
evidence,
|
|
173
240
|
);
|
|
174
241
|
}),
|
|
175
242
|
);
|
|
176
243
|
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
244
|
+
// One context hook, two guarded sections, so a failure in one cannot skip
|
|
245
|
+
// the other.
|
|
246
|
+
//
|
|
247
|
+
// Pull receipts run first: this request's messages are what the host
|
|
248
|
+
// is about to send, after every execute.after hook has run. The held pulls
|
|
249
|
+
// whose tool-result reached it are credited, only for the rows whose line
|
|
250
|
+
// survived. Settled synchronously on entry, so two requests cannot both
|
|
251
|
+
// credit one placement; a failed ledger write is not retried from here.
|
|
252
|
+
//
|
|
253
|
+
// Then the tiny system digest + open-thread frontier block, injected into
|
|
254
|
+
// the system prompt.
|
|
255
|
+
await ctx.session?.hook("context", async (event: any) => {
|
|
256
|
+
await guarded("session.context (pull receipt)", async () => {
|
|
257
|
+
const sid =
|
|
258
|
+
typeof event?.sessionID === "string" ? event.sessionID : undefined;
|
|
259
|
+
const observedAt = Date.now();
|
|
260
|
+
const { credits, losses } = receipts.settle(
|
|
261
|
+
sid,
|
|
262
|
+
event?.messages,
|
|
263
|
+
observedAt,
|
|
264
|
+
);
|
|
265
|
+
// All pull receipts in this request share one lock-wait budget.
|
|
266
|
+
const deadline = performance.now() + 50;
|
|
267
|
+
for (const { held, rows } of credits) {
|
|
268
|
+
const lockWaitMs = Math.max(0, Math.ceil(deadline - performance.now()));
|
|
269
|
+
await noteHits("pull", held.sid, rows, held.query, {
|
|
270
|
+
lockWaitMs,
|
|
271
|
+
tool: held.tool,
|
|
272
|
+
evidence: held.evidence,
|
|
273
|
+
placedAt: held.at,
|
|
274
|
+
observedAt,
|
|
275
|
+
turn: held.turn,
|
|
276
|
+
turnKey: held.turnKey,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
await reportPullLosses(losses);
|
|
280
|
+
});
|
|
281
|
+
await guarded("session.context (systemDigest)", async () => {
|
|
180
282
|
// Route store reads in this hook through the right session's scope:
|
|
181
283
|
// the sid is captured from the event BEFORE any await and carried
|
|
182
284
|
// explicitly — the global current set here is legacy bookkeeping
|
|
@@ -199,8 +301,8 @@ export async function registerHooks(
|
|
|
199
301
|
await sessions.deliver(sid, (text) =>
|
|
200
302
|
event?.system?.push?.({ type: "text", text }),
|
|
201
303
|
);
|
|
202
|
-
})
|
|
203
|
-
);
|
|
304
|
+
});
|
|
305
|
+
});
|
|
204
306
|
|
|
205
307
|
// Memory-first injection, frozen per epoch (cache-safe). Remember the
|
|
206
308
|
// latest user prompt here; the request-time context hook builds or
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// OpenCode V2 session/tool API. Slash commands are installed as markdown by
|
|
8
8
|
// src/command.ts. The default export `{ id, setup(ctx) }` is checked against
|
|
9
9
|
// the SDK's Plugin type using a type-only import (see the note on `plugin`).
|
|
10
|
-
import { registerHooks } from "./events.ts";
|
|
10
|
+
import { registerHooks, type RideAt } from "./events.ts";
|
|
11
11
|
import { forgetUsage } from "./identity/host-events.ts";
|
|
12
12
|
import { guarded, setGuardedFailureReporter } from "./core/hooks.ts";
|
|
13
13
|
import type { PluginCtx } from "./core/host.ts";
|
|
@@ -190,6 +190,8 @@ const impl = {
|
|
|
190
190
|
sid: string,
|
|
191
191
|
rows: Memory[],
|
|
192
192
|
query: string,
|
|
193
|
+
// Deferred pull credits retain the original turn and throttle window.
|
|
194
|
+
at?: RideAt,
|
|
193
195
|
): Promise<void> => {
|
|
194
196
|
if (!rows.length || !query.trim()) return;
|
|
195
197
|
const terms: string[] = [];
|
|
@@ -199,15 +201,16 @@ const impl = {
|
|
|
199
201
|
// the turn is what joins a ride to the outcome of that same turn.
|
|
200
202
|
// Read, never created-for: markTurn has already run for any session that
|
|
201
203
|
// can reach a read path, so this does not seed state.
|
|
202
|
-
const observed = peekTurn(sid);
|
|
204
|
+
const observed = at ? { turn: at.turn, key: at.turnKey } : peekTurn(sid);
|
|
203
205
|
await recordHits(
|
|
204
206
|
src,
|
|
205
207
|
sid,
|
|
206
208
|
rows,
|
|
207
209
|
terms,
|
|
208
|
-
Date.now(),
|
|
210
|
+
at?.placedAt ?? Date.now(),
|
|
209
211
|
observed?.turn,
|
|
210
212
|
observed?.key,
|
|
213
|
+
at,
|
|
211
214
|
);
|
|
212
215
|
};
|
|
213
216
|
// The host listener owns measured usage; the epoch controller drops it
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Pull receipts track complete memory rows in a tool result observed by
|
|
2
|
+
// this plugin’s session.context hook. Later request transformations are opaque.
|
|
3
|
+
import type { Memory } from "../store/model/memory.ts";
|
|
4
|
+
import type { EvidenceContext } from "../telemetry/record.ts";
|
|
5
|
+
|
|
6
|
+
export interface HeldPull {
|
|
7
|
+
sid: string;
|
|
8
|
+
callID: string;
|
|
9
|
+
header: string;
|
|
10
|
+
evidence: EvidenceContext;
|
|
11
|
+
tool: string;
|
|
12
|
+
rows: Memory[];
|
|
13
|
+
/** formatMemory(row) for each row, in the same order, as it was placed. */
|
|
14
|
+
lines: string[];
|
|
15
|
+
/** The query the pull searched; never logged, only reduced to shared terms. */
|
|
16
|
+
query: string;
|
|
17
|
+
/** Placement time for expiry and the existing per-row-set throttle. */
|
|
18
|
+
at: number;
|
|
19
|
+
/** Placement turn, read when the block was placed, not when it is credited. */
|
|
20
|
+
turn?: number;
|
|
21
|
+
turnKey?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PullCredit {
|
|
25
|
+
held: HeldPull;
|
|
26
|
+
/** The held rows whose lines survived into the request, in placed order. */
|
|
27
|
+
rows: Memory[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface PullLoss {
|
|
31
|
+
held: HeldPull;
|
|
32
|
+
/** How many of the held rows got no credit. */
|
|
33
|
+
rows: number;
|
|
34
|
+
/**
|
|
35
|
+
* trimmed — the call's tool-result reached the request without these lines.
|
|
36
|
+
* expired — no request carried the call's tool-result within the TTL.
|
|
37
|
+
* evicted — pushed out by the retention cap before any request carried it.
|
|
38
|
+
*/
|
|
39
|
+
reason: "trimmed" | "expired" | "evicted" | "replaced";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Upper bound on one instance's held placements, across all sessions. */
|
|
43
|
+
export const MAX_HELD_PULLS = 256;
|
|
44
|
+
/**
|
|
45
|
+
* How long a placement waits for a request. The next request follows the
|
|
46
|
+
* step's last tool result, so a placement this old belongs to a session that
|
|
47
|
+
* ended, compacted the call away or never asked again; crediting it later
|
|
48
|
+
* would be stale.
|
|
49
|
+
*/
|
|
50
|
+
export const HELD_PULL_TTL_MS = 30 * 60_000;
|
|
51
|
+
|
|
52
|
+
function resultText(result: unknown): string | undefined {
|
|
53
|
+
if (typeof result === "string") return result;
|
|
54
|
+
if (!result || typeof result !== "object") return undefined;
|
|
55
|
+
const r = result as { type?: unknown; value?: unknown };
|
|
56
|
+
if ((r.type === "text" || r.type === "error") && typeof r.value === "string")
|
|
57
|
+
return r.value;
|
|
58
|
+
if (r.type === "content" && Array.isArray(r.value)) {
|
|
59
|
+
return r.value
|
|
60
|
+
.map((p) =>
|
|
61
|
+
p?.type === "text" && typeof p.text === "string" ? p.text : "",
|
|
62
|
+
)
|
|
63
|
+
.filter(Boolean)
|
|
64
|
+
.join("\n");
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Each copy must independently prove its rows. Replayed copies cannot combine
|
|
70
|
+
// their line counts to identify otherwise ambiguous rows.
|
|
71
|
+
function observedRows(
|
|
72
|
+
messages: unknown,
|
|
73
|
+
pending: Map<string, HeldPull>,
|
|
74
|
+
): Map<HeldPull, Set<Memory>> {
|
|
75
|
+
const observed = new Map<HeldPull, Set<Memory>>();
|
|
76
|
+
if (!Array.isArray(messages)) return observed;
|
|
77
|
+
for (const msg of messages) {
|
|
78
|
+
if (msg?.role !== "tool" || !Array.isArray(msg.content)) continue;
|
|
79
|
+
for (const part of msg.content) {
|
|
80
|
+
if (part?.type !== "tool-result") continue;
|
|
81
|
+
const entry = pending.get(part.id);
|
|
82
|
+
if (!entry || entry.tool !== part.name) continue;
|
|
83
|
+
const rows = survivingRows(entry, resultText(part.result) ?? "");
|
|
84
|
+
if (!rows) continue;
|
|
85
|
+
const kept = observed.get(entry) ?? new Set<Memory>();
|
|
86
|
+
for (const row of rows) kept.add(row);
|
|
87
|
+
observed.set(entry, kept);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return observed;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The placement header distinguishes this block from quoted output and earlier calls.
|
|
94
|
+
function survivingRows(entry: HeldPull, text: string): Memory[] | undefined {
|
|
95
|
+
const lines = text.split(/\r?\n/);
|
|
96
|
+
const start = lines.indexOf(entry.header);
|
|
97
|
+
if (start < 0) return undefined;
|
|
98
|
+
const visible = new Map<string, number>();
|
|
99
|
+
const inBlock = new Map<string, number>();
|
|
100
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
101
|
+
const line = lines[i]!;
|
|
102
|
+
if (line === entry.header) {
|
|
103
|
+
inBlock.clear();
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const count = (inBlock.get(line) ?? 0) + 1;
|
|
107
|
+
inBlock.set(line, count);
|
|
108
|
+
// A formatter can repeat a clipped block inside a single tool result.
|
|
109
|
+
// Keep the highest count in one block; separate copies cannot prove twins.
|
|
110
|
+
if (count > (visible.get(line) ?? 0)) visible.set(line, count);
|
|
111
|
+
}
|
|
112
|
+
const required = new Map<string, number>();
|
|
113
|
+
for (const line of entry.lines)
|
|
114
|
+
required.set(line, (required.get(line) ?? 0) + 1);
|
|
115
|
+
return entry.rows.filter((_, i) => {
|
|
116
|
+
const line = entry.lines[i]!;
|
|
117
|
+
return (visible.get(line) ?? 0) >= required.get(line)!;
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface PullReceipts {
|
|
122
|
+
/**
|
|
123
|
+
* Hold one placement until a request shows it. Returns the placements the
|
|
124
|
+
* cap pushed out, for the caller to report.
|
|
125
|
+
*/
|
|
126
|
+
hold(entry: HeldPull): PullLoss[];
|
|
127
|
+
/**
|
|
128
|
+
* Settle the placements one request can answer. `sid` and `messages` come
|
|
129
|
+
* from one session.context event. A matching placement header settles the
|
|
130
|
+
* entry before any await. A missing header leaves the placement pending.
|
|
131
|
+
*/
|
|
132
|
+
settle(
|
|
133
|
+
sid: string | undefined,
|
|
134
|
+
messages: unknown,
|
|
135
|
+
now?: number,
|
|
136
|
+
): { credits: PullCredit[]; losses: PullLoss[] };
|
|
137
|
+
/** Placements still waiting for a request. */
|
|
138
|
+
size(): number;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* One receipt book per plugin instance: two instances in one process each
|
|
143
|
+
* hold their own placements, so neither can settle or replace the other's.
|
|
144
|
+
*/
|
|
145
|
+
export function createPullReceipts({
|
|
146
|
+
max = MAX_HELD_PULLS,
|
|
147
|
+
ttlMs = HELD_PULL_TTL_MS,
|
|
148
|
+
}: {
|
|
149
|
+
max?: number;
|
|
150
|
+
ttlMs?: number;
|
|
151
|
+
} = {}): PullReceipts {
|
|
152
|
+
// Insertion-ordered: the first entry is always the oldest placement.
|
|
153
|
+
const held = new Map<string, HeldPull>();
|
|
154
|
+
const keyOf = (sid: string, callID: string) => `${sid}\u0000${callID}`;
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
hold(entry) {
|
|
158
|
+
const key = keyOf(entry.sid, entry.callID);
|
|
159
|
+
// A repeated call ID replaces the earlier placement; the newest result
|
|
160
|
+
// is the one the host will send.
|
|
161
|
+
const lost: PullLoss[] = [];
|
|
162
|
+
const previous = held.get(key);
|
|
163
|
+
if (previous) {
|
|
164
|
+
held.delete(key);
|
|
165
|
+
lost.push({
|
|
166
|
+
held: previous,
|
|
167
|
+
rows: previous.rows.length,
|
|
168
|
+
reason: "replaced",
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
held.set(key, entry);
|
|
172
|
+
for (const [oldest, value] of held) {
|
|
173
|
+
if (held.size <= max) break;
|
|
174
|
+
held.delete(oldest);
|
|
175
|
+
lost.push({ held: value, rows: value.rows.length, reason: "evicted" });
|
|
176
|
+
}
|
|
177
|
+
return lost;
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
settle(sid, messages, now = Date.now()) {
|
|
181
|
+
const credits: PullCredit[] = [];
|
|
182
|
+
const losses: PullLoss[] = [];
|
|
183
|
+
for (const [key, entry] of held) {
|
|
184
|
+
if (now - entry.at <= ttlMs) continue;
|
|
185
|
+
held.delete(key);
|
|
186
|
+
losses.push({
|
|
187
|
+
held: entry,
|
|
188
|
+
rows: entry.rows.length,
|
|
189
|
+
reason: "expired",
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
if (typeof sid !== "string" || held.size === 0)
|
|
193
|
+
return { credits, losses };
|
|
194
|
+
const pending = new Map<string, HeldPull>();
|
|
195
|
+
for (const entry of held.values()) {
|
|
196
|
+
if (entry.sid === sid) pending.set(entry.callID, entry);
|
|
197
|
+
}
|
|
198
|
+
if (!pending.size) return { credits, losses };
|
|
199
|
+
for (const [entry, visible] of observedRows(messages, pending)) {
|
|
200
|
+
held.delete(keyOf(entry.sid, entry.callID));
|
|
201
|
+
const rows = entry.rows.filter((row) => visible.has(row));
|
|
202
|
+
if (rows.length) credits.push({ held: entry, rows });
|
|
203
|
+
if (rows.length < entry.rows.length)
|
|
204
|
+
losses.push({
|
|
205
|
+
held: entry,
|
|
206
|
+
rows: entry.rows.length - rows.length,
|
|
207
|
+
reason: "trimmed",
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return { credits, losses };
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
size: () => held.size,
|
|
214
|
+
};
|
|
215
|
+
}
|
package/src/inject/pull.ts
CHANGED
|
@@ -9,6 +9,10 @@ import { formatMemory } from "./format.ts";
|
|
|
9
9
|
import { type UseSignals, argText } from "../recall/relevant.ts";
|
|
10
10
|
import { scoreMemories } from "../recall/score.ts";
|
|
11
11
|
|
|
12
|
+
// The pull block's first line. Exported so a receipt can find the block in
|
|
13
|
+
// the tool-result the host is about to send (src/inject/pull-receipts.ts).
|
|
14
|
+
export const PULL_HEADER = `## Related durable memory (pull)${FRAME}`;
|
|
15
|
+
|
|
12
16
|
export interface TransformOutput {
|
|
13
17
|
system: string[];
|
|
14
18
|
}
|
|
@@ -34,20 +38,17 @@ export interface PullOutput {
|
|
|
34
38
|
// string in `content`, which is the shape this function was originally written
|
|
35
39
|
// against, and a string `output` is covered too.
|
|
36
40
|
//
|
|
37
|
-
// Returns true only when the bytes were placed.
|
|
38
|
-
//
|
|
39
|
-
//
|
|
41
|
+
// Returns true only when the bytes were placed. A pull that found nowhere to
|
|
42
|
+
// write showed the model nothing. Placement is still not delivery: a later
|
|
43
|
+
// plugin's hook can trim the result, so the caller only HOLDS the credit and
|
|
44
|
+
// the next request settles it (src/inject/pull-receipts.ts).
|
|
40
45
|
export function writePullIntoResult(
|
|
41
46
|
result: unknown,
|
|
42
47
|
before: string,
|
|
43
48
|
after: string,
|
|
44
49
|
): boolean {
|
|
45
50
|
if (!result || typeof result !== "object") return false;
|
|
46
|
-
//
|
|
47
|
-
// If the value no longer carries it — another hook rewrote the result between
|
|
48
|
-
// the pull and here — there is no safe place for the block: assigning would
|
|
49
|
-
// clobber the other hook and appending the whole value would duplicate the
|
|
50
|
-
// tool output. Report failure and let the caller log `pull_undelivered`.
|
|
51
|
+
// Compare the two local strings to isolate the suffix this hook appended.
|
|
51
52
|
if (!after.startsWith(before)) return false;
|
|
52
53
|
const block = after.slice(before.length);
|
|
53
54
|
if (!block) return false;
|
|
@@ -244,6 +245,7 @@ export async function contextualPull(
|
|
|
244
245
|
budget = injectBudget(),
|
|
245
246
|
use?: UseSignals,
|
|
246
247
|
scope: PullScope = PULL_SHIPPED,
|
|
248
|
+
header = PULL_HEADER,
|
|
247
249
|
): Promise<Memory[]> {
|
|
248
250
|
const tool = typeof input.tool === "string" ? input.tool : "";
|
|
249
251
|
const own = typeof output.output === "string" ? output.output : "";
|
|
@@ -279,7 +281,6 @@ export async function contextualPull(
|
|
|
279
281
|
if (!merged.length) return [];
|
|
280
282
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
281
283
|
if (typeof output.output !== "string") return [];
|
|
282
|
-
const header = `## Related durable memory (pull)${FRAME}`;
|
|
283
284
|
const lines = merged.map(formatMemory);
|
|
284
285
|
const kept = fittingLineIndices(lines, budget - header.length);
|
|
285
286
|
if (!kept.length) return [];
|