@gamaze/hicortex 0.28.0 → 0.29.0
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/assets/dashboard.html +1756 -3330
- package/assets/viz.html +229 -2
- package/dist/init.d.ts +28 -0
- package/dist/init.js +45 -0
- package/opencode-plugin/hicortex/index.ts +562 -364
- package/package.json +2 -2
- package/server.json +2 -2
|
@@ -1,77 +1,124 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Hicortex plugin for the opencode coding agent (#347) — recall +
|
|
3
|
-
* lessons injection + memory tools, no capture.
|
|
2
|
+
* Hicortex plugin for the opencode coding agent (#347, #646) — recall +
|
|
3
|
+
* identity + lessons injection + memory tools, no capture.
|
|
4
4
|
*
|
|
5
|
-
* The Pi-extension architecture on opencode's plugin API: one
|
|
6
|
-
* file (Node built-ins only, global fetch) that gives
|
|
7
|
-
* memory experience as CC/Pi
|
|
5
|
+
* The Pi-extension architecture on opencode 2.x's plugin API: one
|
|
6
|
+
* dependency-free file (Node built-ins only, global fetch) that gives
|
|
7
|
+
* opencode agents the same memory experience as CC/Pi.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* never mutated). Tool-loop requests of the same turn
|
|
17
|
-
* re-inject the stashed block. The channel was chosen
|
|
18
|
-
* by live verification on opencode 1.18.20: parts
|
|
19
|
-
* appended via the chat.message hook never reach the
|
|
20
|
-
* model call (0/3 runs completed), while a synthetic
|
|
21
|
-
* message from messages.transform provably does — and
|
|
22
|
-
* is NOT persisted to opencode's session store.
|
|
23
|
-
* experimental.chat.system.transform → append the `## Identity` (gated on
|
|
24
|
-
* the server-resolved clients containing "opencode")
|
|
25
|
-
* and Learnings blocks as ONE fenced system entry;
|
|
26
|
-
* per-session memoize-on-success; the fence guard
|
|
27
|
-
* prevents doubling.
|
|
28
|
-
* event → session.created / session.compacted POST
|
|
29
|
-
* /recall-index {session_id, reset:true} (the two
|
|
30
|
-
* events carry the id at different paths:
|
|
31
|
-
* properties.info.id vs properties.sessionID) and
|
|
32
|
-
* drop the session's caches.
|
|
33
|
-
* tool × 9 → the hicortex_* tools as direct REST proxies with
|
|
34
|
-
* plain-object args (no zod — verified live).
|
|
9
|
+
* OPENCODE 2.x PLUGIN API (#646): opencode 2.x replaced the V1 plugin API
|
|
10
|
+
* ("V1 plugin implementations do not run in V2", upstream migration docs),
|
|
11
|
+
* so the V1 hooks (experimental.chat.messages.transform /
|
|
12
|
+
* experimental.chat.system.transform / event / tool) are dead there. The V2
|
|
13
|
+
* shape below is BOTH doc-confirmed (opencode.ai/v2/docs/build/plugins/,
|
|
14
|
+
* fetched 2026-11-24) AND probe-confirmed on a live opencode 2.4.0 session
|
|
15
|
+
* (the #646 throwaway probe, probes/opencode-v2/, 2026-11-24):
|
|
35
16
|
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
17
|
+
* Entry → `export default { id, setup(ctx) }` — a PLAIN
|
|
18
|
+
* object with zero imports. PROBE-CONFIRMED: this
|
|
19
|
+
* exact shape loaded and ran on 2.4.0 (all five
|
|
20
|
+
* registrations logged ok; the `@opencode/plugin`
|
|
21
|
+
* wrap was not needed).
|
|
22
|
+
* ctx.session.hook("context") → ONE channel for both injections. It runs
|
|
23
|
+
* for the agent loop including tool-driven
|
|
24
|
+
* continuations, and its edits affect only the
|
|
25
|
+
* OUTGOING model call — never persisted history
|
|
26
|
+
* (docs; probe: the synthetic message appeared in
|
|
27
|
+
* the model's context and produced NO session-store
|
|
28
|
+
* row of its own). The event keys are
|
|
29
|
+
* [sessionID, model, system, messages, options,
|
|
30
|
+
* agent, tools]; message elements carry
|
|
31
|
+
* {id, role, content:[{type:"text",text}]} — NO
|
|
32
|
+
* `info` block (the V1 info.sessionID path is gone;
|
|
33
|
+
* the event's sessionID is the only carrier); system
|
|
34
|
+
* parts are {type:"text", text} (optionally
|
|
35
|
+
* metadata). Recall finds the LAST real user
|
|
36
|
+
* message, POSTs /recall-index (1 s timeout,
|
|
37
|
+
* fail-soft), and appends ONE synthetic user message
|
|
38
|
+
* after it (same channel semantics the V1
|
|
39
|
+
* messages.transform live-verification chose on
|
|
40
|
+
* 1.18.20: synthetic message ephemeral, parts-append
|
|
41
|
+
* refuted). Identity + lessons push ONE fenced
|
|
42
|
+
* system part (`{ type: "text", text }`) memoized
|
|
43
|
+
* per session.
|
|
44
|
+
* ctx.session.hook("prompt") → dedup-reset ONLY, never injection: the
|
|
45
|
+
* prompt hook's edits become the canonical PERSISTED
|
|
46
|
+
* user input (upstream docs), so this plugin makes
|
|
47
|
+
* zero edits in it. Probe-confirmed shape:
|
|
48
|
+
* [sessionID, messageID, prompt, metadata, delivery]
|
|
49
|
+
* — it fires once per admitted prompt and carries
|
|
50
|
+
* the sessionID, which makes it the first-seen-
|
|
51
|
+
* session boundary for the server-side recall dedup
|
|
52
|
+
* reset. Behavior delta vs V1 (which reset on the
|
|
53
|
+
* session.created event): a RESUMED session also
|
|
54
|
+
* resets once at its first admitted prompt —
|
|
55
|
+
* deliberate: the V2 event stream proved parseable
|
|
56
|
+
* (durable envelopes, data.sessionID) but carries NO
|
|
57
|
+
* session-start analog among its 37 event types, so
|
|
58
|
+
* the typed prompt hook is the only faithful
|
|
59
|
+
* session-start channel (#646 AC5).
|
|
60
|
+
* ctx.session.hook("compaction") → dedup reset when a session compacts
|
|
61
|
+
* (probe-confirmed: fired on a manual /compact with
|
|
62
|
+
* [sessionID, model, system, messages, options,
|
|
63
|
+
* agent, tools]; the same-session continuation is
|
|
64
|
+
* the one reset that actually matters — the
|
|
65
|
+
* post-compaction session shares the session id, so
|
|
66
|
+
* the server-side shown-set must be cleared).
|
|
67
|
+
* ctx.tool.transform → the nine hicortex_* tools as editor.add()
|
|
68
|
+
* definitions with a JSON-Schema `input` built from
|
|
69
|
+
* the V1 flat arg maps, registered with
|
|
70
|
+
* `options: { codemode: false }` — PROBE-CONFIRMED
|
|
71
|
+
* on 2.4.0: that flag makes a plugin tool a DIRECT
|
|
72
|
+
* call (it appears in the context event's `tools`
|
|
73
|
+
* record; the definition the model sees is
|
|
74
|
+
* {description, input}), while a no-options
|
|
75
|
+
* registration lands Code-Mode-only (round 1;
|
|
76
|
+
* reachable only as `tools.<name>({...})` inside the
|
|
77
|
+
* `execute` tool, and a namespace would prefix the
|
|
78
|
+
* effective id `<ns>_<name>` — both avoided here).
|
|
79
|
+
* Executors return structured content
|
|
80
|
+
* `{ content: string }` — PROBE-CONFIRMED, and
|
|
81
|
+
* load-bearing: a PLAIN STRING return is REFUTED on
|
|
82
|
+
* 2.4.0 ("a is not an Object ('output' in a)" ×3).
|
|
83
|
+
* Executor context carries [sessionID, agent,
|
|
84
|
+
* messageID, id, progress, signal] on a direct tool
|
|
85
|
+
* (codemode adds its own key); `context.signal` is
|
|
86
|
+
* raced into the 10 s tool timeout.
|
|
87
|
+
*
|
|
88
|
+
* #600: the workspace folder basename IS the agent name. V2 hook events do
|
|
89
|
+
* not carry a per-session directory (ctx.location is the plugin INSTANCE's
|
|
90
|
+
* location, not each session's — upstream docs), so the context hook
|
|
91
|
+
* resolves the workspace via `ctx.session.get({ sessionID })` →
|
|
92
|
+
* `location.directory` (PROBE-CONFIRMED on 2.4.0: session.get returns a bare
|
|
93
|
+
* record — id, projectID, model, cost, tokens, time, title, location — and
|
|
94
|
+
* location.directory is the per-session workspace), memoized per session,
|
|
95
|
+
* and threads agent=<sanitized basename> on the recall body and the
|
|
96
|
+
* read-tool queries; anything unresolved omits the param (fail-closed
|
|
97
|
+
* non-member, same null-sanitizing rule as V1).
|
|
48
98
|
*
|
|
49
99
|
* Capture is NOT the plugin's job — the nightly reader on the server machine
|
|
50
100
|
* distills ~/.local/share/opencode/opencode.db centrally
|
|
51
|
-
* (opencode-transcript-reader)
|
|
101
|
+
* (opencode-transcript-reader); it skips marker-fenced text parts, so the
|
|
102
|
+
* injections here never echo into memory.
|
|
52
103
|
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
104
|
+
* Fail-soft by construction: ANY failure (no config, timeout, non-2xx, parse
|
|
105
|
+
* error, unexpected API shape) injects nothing and never blocks a session —
|
|
106
|
+
* injection-path fetches carry a 1000 ms timeout, tool fetches 10 s, and
|
|
107
|
+
* every hook registration is individually guarded (a V2 API drift degrades
|
|
108
|
+
* to no memory, never a broken agent loop).
|
|
58
109
|
*
|
|
59
|
-
* Loose structural typing throughout (`
|
|
60
|
-
* narrowing): this file must not depend on @opencode
|
|
110
|
+
* Loose structural typing throughout (`ctx: any`, `input: any`, inline
|
|
111
|
+
* narrowing): this file must not depend on @opencode/plugin types — the
|
|
61
112
|
* plugin has ZERO imports beyond Node built-ins so it works on any opencode
|
|
62
113
|
* install straight from the npm tarball.
|
|
63
114
|
*
|
|
64
|
-
* LOADER CONTRACT (
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
* crashed with `blocks.filter is not a function` and the plugin never loaded
|
|
72
|
-
* — live-isolated on opencode 1.18.23). The vitest suite drives this file
|
|
73
|
-
* the way the loader does — through the factory's hooks — never via helper
|
|
74
|
-
* imports, and a structural test pins the export surface.
|
|
115
|
+
* LOADER CONTRACT (V2): the V2 loader reads the default export's `id` and
|
|
116
|
+
* `setup()`; this file exports exactly ONE runtime binding — that default
|
|
117
|
+
* object — and every helper stays module-private. The V1 rule (every named
|
|
118
|
+
* export invoked as a factory, #353) does not carry to V2, but the same
|
|
119
|
+
* discipline holds: one export, one plugin. The vitest suite drives this
|
|
120
|
+
* file the way the loader does — through `setup(ctx)`'s registered hooks —
|
|
121
|
+
* never via helper imports, and a structural test pins the export surface.
|
|
75
122
|
*/
|
|
76
123
|
|
|
77
124
|
import { readFileSync } from "node:fs";
|
|
@@ -87,10 +134,10 @@ const DEFAULT_LESSONS_LIMIT = 10;
|
|
|
87
134
|
|
|
88
135
|
/**
|
|
89
136
|
* HTML-comment fence around every injected block. Doubles as the idempotency
|
|
90
|
-
* guard (
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* (defense in depth —
|
|
137
|
+
* guard (the context hook skips a request whose system already carries the
|
|
138
|
+
* end marker) and as the reader's self-echo skip: any text inside the fence
|
|
139
|
+
* is Hicortex injection, not conversation, and is excluded from capture
|
|
140
|
+
* (defense in depth — the context hook's edits are not persisted anyway).
|
|
94
141
|
* Comments are invisible to the model, so the fence costs nothing on the wire.
|
|
95
142
|
*/
|
|
96
143
|
const CONTEXT_START = "<!-- hicortex-context-start -->";
|
|
@@ -307,11 +354,10 @@ function sanitizeAgentId(raw: string): string | null {
|
|
|
307
354
|
|
|
308
355
|
/**
|
|
309
356
|
* #600: the workspace-scoped agent id sent on every read call — the sanitized
|
|
310
|
-
* basename of the working directory (the
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
314
|
-
* would 400 on and a fail-soft path would silently swallow).
|
|
357
|
+
* basename of the session's working directory (the folder name IS the agent
|
|
358
|
+
* name). null when the basename sanitizes to nothing → the caller omits
|
|
359
|
+
* `agent` entirely (fail-closed: the request reads as a non-member, never an
|
|
360
|
+
* id the server would 400 on and a fail-soft path would silently swallow).
|
|
315
361
|
*/
|
|
316
362
|
function workspaceAgentId(cwd: string): string | null {
|
|
317
363
|
return sanitizeAgentId(basename(cwd ?? ""));
|
|
@@ -323,8 +369,8 @@ function workspaceAgentId(cwd: string): string | null {
|
|
|
323
369
|
* buildHookRequest: project = basename(working directory) so retrieval can
|
|
324
370
|
* apply the soft project-affinity boost (retrieval-scoping: opencode is a
|
|
325
371
|
* cwd-based client and must send `project`), and agent = the sanitized
|
|
326
|
-
* workspace basename threaded by the caller (#600 —
|
|
327
|
-
* directory
|
|
372
|
+
* workspace basename threaded by the caller (#600 — the session's OWN
|
|
373
|
+
* directory, never a process-wide cwd fallback).
|
|
328
374
|
*/
|
|
329
375
|
function buildRecallBody(
|
|
330
376
|
sessionId: string,
|
|
@@ -347,9 +393,10 @@ function fenceBlock(block: string): string {
|
|
|
347
393
|
|
|
348
394
|
/**
|
|
349
395
|
* Build the single fenced system entry from the identity/lessons blocks, or
|
|
350
|
-
* null when there is nothing to inject (no non-empty blocks).
|
|
351
|
-
*
|
|
352
|
-
*
|
|
396
|
+
* null when there is nothing to inject (no non-empty blocks). The entry is
|
|
397
|
+
* pushed as ONE `{ type: "text", text }` system part (the docs' push shape —
|
|
398
|
+
* the V1 system was a plain-string array; V2 parts are typed objects), so
|
|
399
|
+
* the blocks travel together inside one fence.
|
|
353
400
|
*/
|
|
354
401
|
function renderContextEntry(blocks: Array<string | null>): string | null {
|
|
355
402
|
const parts = blocks.filter((b): b is string => typeof b === "string" && b.trim() !== "");
|
|
@@ -357,21 +404,32 @@ function renderContextEntry(blocks: Array<string | null>): string | null {
|
|
|
357
404
|
return `${CONTEXT_START}\n\n${parts.join("\n\n")}\n\n${CONTEXT_END}`;
|
|
358
405
|
}
|
|
359
406
|
|
|
360
|
-
/**
|
|
407
|
+
/**
|
|
408
|
+
* True when a system array already carries our end marker → skip (no
|
|
409
|
+
* doubling). V2 system parts are `{ type: "text", text }` objects (PROBE-
|
|
410
|
+
* PENDING shape; plain strings are still honored defensively) — the guard
|
|
411
|
+
* reads whichever text carrier a part offers.
|
|
412
|
+
*/
|
|
361
413
|
function systemAlreadyFenced(system: unknown): boolean {
|
|
362
|
-
|
|
414
|
+
if (!Array.isArray(system)) return false;
|
|
415
|
+
return system.some((p) => {
|
|
416
|
+
const text = typeof p === "string" ? p : (p as { text?: unknown } | null)?.text;
|
|
417
|
+
return typeof text === "string" && text.includes(CONTEXT_END);
|
|
418
|
+
});
|
|
363
419
|
}
|
|
364
420
|
|
|
365
421
|
// ---------------------------------------------------------------------------
|
|
366
|
-
// Message-shape helpers (the
|
|
422
|
+
// Message-shape helpers (the context event's Message elements are structurally
|
|
423
|
+
// typed; the element shape is probe-confirmed (#646 AC1, probes/opencode-v2 evidence) — every accessor
|
|
424
|
+
// narrows defensively so an unexpected shape degrades to no injection)
|
|
367
425
|
// ---------------------------------------------------------------------------
|
|
368
426
|
|
|
369
427
|
/**
|
|
370
428
|
* The last REAL user message in a model request, with its index, or null.
|
|
371
429
|
* Skips our own synthetic recall message (fresh id on a cloned shape): the
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
430
|
+
* context hook's edits are not persisted, but if one ever loops back into a
|
|
431
|
+
* request it must not be mistaken for the turn's prompt (defense in depth —
|
|
432
|
+
* same reason the reader skips fenced text).
|
|
375
433
|
*/
|
|
376
434
|
function lastUserMessage(
|
|
377
435
|
messages: unknown,
|
|
@@ -414,7 +472,9 @@ function messageSessionId(msg: unknown): string | null {
|
|
|
414
472
|
* Build the synthetic user message that carries the recall block: a clone of
|
|
415
473
|
* the real message's `info` with a FRESH id and exactly one text part. Never
|
|
416
474
|
* mutates the real message; the fresh id keeps the synthetic entry distinct
|
|
417
|
-
* from the real one anywhere downstream.
|
|
475
|
+
* from the real one anywhere downstream. The exact Message element shape is
|
|
476
|
+
* probe-confirmed (#646 AC3, probes/opencode-v2 evidence); the construction mirrors the real message's observed fields so it
|
|
477
|
+
* rides whatever shape the request already carries.
|
|
418
478
|
*/
|
|
419
479
|
function buildRecallMessage(real: unknown, fenced: string): Record<string, unknown> | null {
|
|
420
480
|
if (!real || typeof real !== "object") return null;
|
|
@@ -428,82 +488,6 @@ function buildRecallMessage(real: unknown, fenced: string): Record<string, unkno
|
|
|
428
488
|
return msg;
|
|
429
489
|
}
|
|
430
490
|
|
|
431
|
-
/**
|
|
432
|
-
* The session id of a dedup-reset event, or null when the event is not a
|
|
433
|
-
* reset or carries no id. The two events carry it at DIFFERENT paths:
|
|
434
|
-
* session.created → properties.info.id, session.compacted →
|
|
435
|
-
* properties.sessionID (the @opencode-ai/sdk Event union). `name` is read as
|
|
436
|
-
* a fallback discriminator so a rename upstream degrades to a no-op, not a
|
|
437
|
-
* wrong-shape post.
|
|
438
|
-
*/
|
|
439
|
-
function extractResetSessionId(event: unknown): string | null {
|
|
440
|
-
if (!event || typeof event !== "object") return null;
|
|
441
|
-
const ev = event as { type?: unknown; name?: unknown; properties?: unknown };
|
|
442
|
-
const type = typeof ev.type === "string" ? ev.type : typeof ev.name === "string" ? ev.name : "";
|
|
443
|
-
const props = ev.properties as Record<string, unknown> | null | undefined;
|
|
444
|
-
if (!props || typeof props !== "object") return null;
|
|
445
|
-
if (type === "session.created") {
|
|
446
|
-
const id = (props.info as { id?: unknown } | undefined)?.id;
|
|
447
|
-
return typeof id === "string" && id ? id : null;
|
|
448
|
-
}
|
|
449
|
-
if (type === "session.compacted") {
|
|
450
|
-
const id = props.sessionID;
|
|
451
|
-
return typeof id === "string" && id ? id : null;
|
|
452
|
-
}
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
/** The working directory a hook input carries, falling back to process cwd. */
|
|
457
|
-
function cwdFromInput(input: unknown): string {
|
|
458
|
-
const i = input as { directory?: unknown; cwd?: unknown } | null | undefined;
|
|
459
|
-
if (typeof i?.directory === "string" && i.directory) return i.directory;
|
|
460
|
-
if (typeof i?.cwd === "string" && i.cwd) return i.cwd;
|
|
461
|
-
return process.cwd();
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
/**
|
|
465
|
-
* #600: the working directory a hook input carries — STRICT (no process.cwd()
|
|
466
|
-
* fallback): only a genuine session directory names the workspace agent; the
|
|
467
|
-
* gateway process's cwd is not a workspace. `project` keeps the looser
|
|
468
|
-
* cwdFromInput fallback above (unchanged behavior).
|
|
469
|
-
*/
|
|
470
|
-
function strictCwd(input: unknown): string | null {
|
|
471
|
-
const i = input as { directory?: unknown; cwd?: unknown } | null | undefined;
|
|
472
|
-
if (typeof i?.directory === "string" && i.directory) return i.directory;
|
|
473
|
-
if (typeof i?.cwd === "string" && i.cwd) return i.cwd;
|
|
474
|
-
return null;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
/**
|
|
478
|
-
* #600: the last workspace agent id a per-prompt hook resolved. The tool
|
|
479
|
-
* executes receive no input of their own, so the five read proxies read this
|
|
480
|
-
* directly. Multi-session gateways interleave — a tool read may carry a
|
|
481
|
-
* sibling session's id; bounded by the trust model (the agent param is
|
|
482
|
-
* self-asserted, the bearer token is the boundary) and it fails toward the
|
|
483
|
-
* standard pool in the common case.
|
|
484
|
-
*/
|
|
485
|
-
let LAST_AGENT: string | null = null;
|
|
486
|
-
|
|
487
|
-
/**
|
|
488
|
-
* The workspace agent for a hook input: the sanitized basename of its
|
|
489
|
-
* directory when it carries one (updating LAST_AGENT), else the last-known
|
|
490
|
-
* id — a null-sanitizing basename never overwrites a known id.
|
|
491
|
-
*/
|
|
492
|
-
function currentAgent(input: unknown): string | null {
|
|
493
|
-
const cwd = strictCwd(input);
|
|
494
|
-
const id = cwd ? workspaceAgentId(cwd) : null;
|
|
495
|
-
if (id) LAST_AGENT = id;
|
|
496
|
-
return id ?? LAST_AGENT;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/** Best-effort session id from a hook input (shape not stable upstream). */
|
|
500
|
-
function inputSessionId(input: unknown): string | null {
|
|
501
|
-
const i = input as { info?: { sessionID?: unknown }; sessionID?: unknown; session?: { id?: unknown } } | null | undefined;
|
|
502
|
-
const candidates = [i?.info?.sessionID, i?.sessionID, i?.session?.id];
|
|
503
|
-
for (const c of candidates) if (typeof c === "string" && c) return c;
|
|
504
|
-
return null;
|
|
505
|
-
}
|
|
506
|
-
|
|
507
491
|
// ---------------------------------------------------------------------------
|
|
508
492
|
// Session-scoped state
|
|
509
493
|
// ---------------------------------------------------------------------------
|
|
@@ -518,33 +502,47 @@ function inputSessionId(input: unknown): string | null {
|
|
|
518
502
|
* long-lived opencode process accumulating sessions would otherwise grow the
|
|
519
503
|
* maps forever.
|
|
520
504
|
*
|
|
521
|
-
* #600:
|
|
522
|
-
*
|
|
523
|
-
*
|
|
505
|
+
* #600: LESSONS_BLOCKS stores the agent id the block was fetched UNDER (the
|
|
506
|
+
* lessons pool is member-gated) — see cachedAgentBlock. The identity cache is
|
|
507
|
+
* NOT agent-scoped (identity is global for opencode). DIRECTORIES memoizes
|
|
508
|
+
* the per-session workspace directory resolved via ctx.session.get (one
|
|
509
|
+
* client call per session, never per request).
|
|
524
510
|
*/
|
|
525
511
|
const RECALL_BLOCKS = new Map<string, string | null>();
|
|
526
512
|
const PROMPT_KEYS = new Map<string, string>();
|
|
527
513
|
const IDENTITY_BLOCKS = new Map<string, string | null>();
|
|
528
514
|
const LESSONS_BLOCKS = new Map<string, { block: string | null; agent: string | null }>();
|
|
515
|
+
const DIRECTORIES = new Map<string, string | null>();
|
|
516
|
+
/** Sessions already seen by the prompt hook (first-seen reset gate). */
|
|
517
|
+
const SEEN_SESSIONS = new Set<string>();
|
|
529
518
|
/** In-flight / recently-fired dedup resets, keyed by session id (#316 ordering). */
|
|
530
519
|
const PENDING_RESETS = new Map<string, Promise<void>>();
|
|
531
520
|
const SESSION_STATE_CAP = 32;
|
|
532
|
-
/** Cache key when a hook
|
|
521
|
+
/** Cache key when a hook event carries no session id (fail-soft freshness trade). */
|
|
533
522
|
const FALLBACK_SESSION_KEY = "__opencode__";
|
|
534
523
|
|
|
535
524
|
function pruneSessionState(): void {
|
|
536
525
|
if (
|
|
537
526
|
RECALL_BLOCKS.size > SESSION_STATE_CAP ||
|
|
538
527
|
IDENTITY_BLOCKS.size > SESSION_STATE_CAP ||
|
|
539
|
-
LESSONS_BLOCKS.size > SESSION_STATE_CAP
|
|
528
|
+
LESSONS_BLOCKS.size > SESSION_STATE_CAP ||
|
|
529
|
+
SEEN_SESSIONS.size > SESSION_STATE_CAP ||
|
|
530
|
+
DIRECTORIES.size > SESSION_STATE_CAP
|
|
540
531
|
) {
|
|
541
532
|
RECALL_BLOCKS.clear();
|
|
542
533
|
PROMPT_KEYS.clear();
|
|
543
534
|
IDENTITY_BLOCKS.clear();
|
|
544
535
|
LESSONS_BLOCKS.clear();
|
|
536
|
+
SEEN_SESSIONS.clear();
|
|
537
|
+
DIRECTORIES.clear();
|
|
545
538
|
}
|
|
546
539
|
}
|
|
547
540
|
|
|
541
|
+
/**
|
|
542
|
+
* Drop a session's fetch caches + seen-mark. The workspace directory cache
|
|
543
|
+
* is deliberately NOT dropped: the workspace identity is stable for the
|
|
544
|
+
* session's lifetime (a compaction must not turn into an agent-id amnesia).
|
|
545
|
+
*/
|
|
548
546
|
function dropSessionState(sessionId: string): void {
|
|
549
547
|
RECALL_BLOCKS.delete(sessionId);
|
|
550
548
|
PROMPT_KEYS.delete(sessionId);
|
|
@@ -571,8 +569,8 @@ async function cachedBlock(
|
|
|
571
569
|
/**
|
|
572
570
|
* #600: the lessons-cache identity guard — memoize the settled render UNDER
|
|
573
571
|
* the agent id it was fetched for. A later request that resolves a DIFFERENT
|
|
574
|
-
* (or newly known) workspace id re-fetches; without this, a
|
|
575
|
-
*
|
|
572
|
+
* (or newly known) workspace id re-fetches; without this, a request that
|
|
573
|
+
* fires before any directory is known would pin a standard-pool lessons
|
|
576
574
|
* block for a member's whole session. Same memoize-only-on-success rule as
|
|
577
575
|
* cachedBlock (a throw degrades to null and retries next request).
|
|
578
576
|
*/
|
|
@@ -593,6 +591,17 @@ async function cachedAgentBlock(
|
|
|
593
591
|
}
|
|
594
592
|
}
|
|
595
593
|
|
|
594
|
+
/** Race a promise against the injection timeout (fail-soft null). */
|
|
595
|
+
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T | null> {
|
|
596
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
597
|
+
const deadline = new Promise<null>((resolve) => {
|
|
598
|
+
timer = setTimeout(() => resolve(null), ms);
|
|
599
|
+
});
|
|
600
|
+
return Promise.race([p.catch(() => null), deadline]).finally(() => {
|
|
601
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
|
|
596
605
|
// ---------------------------------------------------------------------------
|
|
597
606
|
// Fetchers — every failure path THROWS to the caller's fail-soft catch
|
|
598
607
|
// ---------------------------------------------------------------------------
|
|
@@ -676,9 +685,84 @@ function resetRecallDedup(cfg: OpencodeConfig, sessionId: string): Promise<void>
|
|
|
676
685
|
}
|
|
677
686
|
|
|
678
687
|
// ---------------------------------------------------------------------------
|
|
679
|
-
//
|
|
680
|
-
//
|
|
681
|
-
|
|
688
|
+
// #600 agent threading — the per-session workspace directory source
|
|
689
|
+
// ---------------------------------------------------------------------------
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* #600 (V2): the session's working directory, or null. Neither the V2
|
|
693
|
+
* context-hook event nor ctx.location (the plugin INSTANCE's location —
|
|
694
|
+
* upstream docs) carries a per-session directory, so the source is
|
|
695
|
+
* `ctx.session.get({ sessionID })` → `location.directory` (PROBE-CONFIRMED
|
|
696
|
+
* on 2.4.0; a top-level `directory` is honored defensively). Memoized per
|
|
697
|
+
* session — one client call per session, never per model request — and
|
|
698
|
+
* raced against the injection timeout so a slow client call cannot stall a
|
|
699
|
+
* turn. The V1 process.cwd() fallback is deliberately GONE: V2 hosts run one
|
|
700
|
+
* shared server process, whose cwd is not any session's workspace — no
|
|
701
|
+
* resolution → no project/agent params (fail-closed).
|
|
702
|
+
*/
|
|
703
|
+
async function sessionDirectory(ctx: any, sessionId: string | null): Promise<string | null> {
|
|
704
|
+
if (!sessionId) return null;
|
|
705
|
+
if (DIRECTORIES.has(sessionId)) return DIRECTORIES.get(sessionId) ?? null;
|
|
706
|
+
let dir: string | null = null;
|
|
707
|
+
try {
|
|
708
|
+
const info = await withTimeout(
|
|
709
|
+
Promise.resolve(ctx?.session?.get?.({ sessionID: sessionId })),
|
|
710
|
+
FETCH_TIMEOUT_MS,
|
|
711
|
+
);
|
|
712
|
+
// Probe-proven (opencode 2.4.0): session.get returns a bare record whose
|
|
713
|
+
// workspace lives at `location.directory`. A top-level `directory` is
|
|
714
|
+
// honored defensively in case a build hoists it.
|
|
715
|
+
const rec = info as { directory?: unknown; location?: { directory?: unknown } } | null;
|
|
716
|
+
const d = typeof rec?.location?.directory === "string" && rec.location.directory
|
|
717
|
+
? rec.location.directory
|
|
718
|
+
: rec?.directory;
|
|
719
|
+
if (typeof d === "string" && d) dir = d;
|
|
720
|
+
} catch {
|
|
721
|
+
dir = null;
|
|
722
|
+
}
|
|
723
|
+
// Only POSITIVE resolutions are memoized: a session.get miss (timeout,
|
|
724
|
+
// API drift, an info shape without the location) retries on the next
|
|
725
|
+
// request — the #600 lessons-cache guard then re-fetches the block under
|
|
726
|
+
// the agent once the directory becomes known, exactly as in V1.
|
|
727
|
+
if (dir !== null) DIRECTORIES.set(sessionId, dir);
|
|
728
|
+
return dir;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* #600: the workspace (cwd + agent id) for a context event — the session's
|
|
733
|
+
* memoized directory resolution sanitized. Publishes to LAST_AGENT for the
|
|
734
|
+
* tool proxies (below); a null-sanitizing resolution never overwrites a
|
|
735
|
+
* known id, and the last-known id covers the no-resolution path (same rule
|
|
736
|
+
* as V1's currentAgent).
|
|
737
|
+
*/
|
|
738
|
+
async function resolveWorkspace(
|
|
739
|
+
ctx: any,
|
|
740
|
+
event: any,
|
|
741
|
+
sessionId: string | null,
|
|
742
|
+
): Promise<{ cwd: string | null; agent: string | null }> {
|
|
743
|
+
const direct = typeof event?.directory === "string" && event.directory ? event.directory : null;
|
|
744
|
+
const cwd = direct ?? (await sessionDirectory(ctx, sessionId));
|
|
745
|
+
const id = cwd ? workspaceAgentId(cwd) : null;
|
|
746
|
+
if (id) LAST_AGENT = id;
|
|
747
|
+
return { cwd, agent: id ?? LAST_AGENT };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* #600: the last workspace agent id a context hook resolved. The tool
|
|
752
|
+
* executes receive no session input of their own, so the five read proxies
|
|
753
|
+
* read this directly. Multi-session gateways interleave — a tool read may
|
|
754
|
+
* carry a sibling session's id; bounded by the trust model (the agent param
|
|
755
|
+
* is self-asserted, the bearer token is the boundary) and it fails toward
|
|
756
|
+
* the standard pool in the common case.
|
|
757
|
+
*/
|
|
758
|
+
let LAST_AGENT: string | null = null;
|
|
759
|
+
|
|
760
|
+
// ---------------------------------------------------------------------------
|
|
761
|
+
// Tool plumbing — REST proxies under ctx.tool.transform (names/descriptions
|
|
762
|
+
// mirror the OC/Pi plugins; `input` is a JSON Schema built from the V1 flat
|
|
763
|
+
// arg maps; `execute` returns structured content `{ content: string }` — the
|
|
764
|
+
// probe-required shape, per #646 AC6 evidence). Config resolves per call (no
|
|
765
|
+
// startup capture).
|
|
682
766
|
// ---------------------------------------------------------------------------
|
|
683
767
|
|
|
684
768
|
/** Canonical memory_type mapping — mirrors normalizeMemoryType (type-labels). */
|
|
@@ -697,19 +781,33 @@ const NOT_CONFIGURED =
|
|
|
697
781
|
"Hicortex is not configured on this machine — run `npx @gamaze/hicortex init` " +
|
|
698
782
|
"(or create ~/.hicortex/config.json).";
|
|
699
783
|
|
|
700
|
-
/** Error results are plain text strings
|
|
784
|
+
/** Error results are plain text strings inside `{ content }`; never throw. */
|
|
701
785
|
function errorResult(message: string): string {
|
|
702
786
|
return `error: ${message}`;
|
|
703
787
|
}
|
|
704
788
|
|
|
789
|
+
/** The executor's abort signal: the 10 s tool timeout raced with the request's. */
|
|
790
|
+
function toolSignal(extra: unknown): AbortSignal {
|
|
791
|
+
const timeout = AbortSignal.timeout(TOOL_TIMEOUT_MS);
|
|
792
|
+
if (extra instanceof AbortSignal) {
|
|
793
|
+
try {
|
|
794
|
+
return AbortSignal.any([timeout, extra]);
|
|
795
|
+
} catch {
|
|
796
|
+
/* pre-20.3 runtime without AbortSignal.any — the timeout alone stands */
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return timeout;
|
|
800
|
+
}
|
|
801
|
+
|
|
705
802
|
async function serverGet(
|
|
706
803
|
cfg: OpencodeConfig,
|
|
707
804
|
path: string,
|
|
805
|
+
extra?: unknown,
|
|
708
806
|
): Promise<{ data: any | null; status: number | null }> {
|
|
709
807
|
try {
|
|
710
808
|
const resp = await fetch(`${cfg.serverUrl}${path}`, {
|
|
711
809
|
headers: authHeaders(cfg),
|
|
712
|
-
signal:
|
|
810
|
+
signal: toolSignal(extra),
|
|
713
811
|
});
|
|
714
812
|
if (!resp.ok) return { data: null, status: resp.status };
|
|
715
813
|
return { data: await resp.json(), status: resp.status };
|
|
@@ -722,13 +820,14 @@ async function serverPost(
|
|
|
722
820
|
cfg: OpencodeConfig,
|
|
723
821
|
path: string,
|
|
724
822
|
body: unknown,
|
|
823
|
+
extra?: unknown,
|
|
725
824
|
): Promise<{ ok: boolean; status: number; data: any | null }> {
|
|
726
825
|
try {
|
|
727
826
|
const resp = await fetch(`${cfg.serverUrl}${path}`, {
|
|
728
827
|
method: "POST",
|
|
729
828
|
headers: { "Content-Type": "application/json", ...authHeaders(cfg) },
|
|
730
829
|
body: JSON.stringify(body),
|
|
731
|
-
signal:
|
|
830
|
+
signal: toolSignal(extra),
|
|
732
831
|
});
|
|
733
832
|
let data: any = null;
|
|
734
833
|
try { data = await resp.json(); } catch { /* non-JSON body */ }
|
|
@@ -767,30 +866,45 @@ function formatSearchResults(results: Array<SearchHit>): string {
|
|
|
767
866
|
.join("\n\n");
|
|
768
867
|
}
|
|
769
868
|
|
|
770
|
-
/**
|
|
771
|
-
|
|
869
|
+
/**
|
|
870
|
+
* The nine tools, keyed by their V1 flat-arg names (the shape the
|
|
871
|
+
* description-drift guard regex-extracts). `input` wraps the flat arg map in
|
|
872
|
+
* the JSON-Schema object form ctx.tool.transform takes (probe-confirmed: the
|
|
873
|
+
* definition the model sees for a direct tool is {description, input});
|
|
874
|
+
* the executor's second argument is the V2 request context carrying
|
|
875
|
+
* `signal`; every definition is registered with {codemode: false} (see the
|
|
876
|
+
* entry below) so it is a DIRECT call.
|
|
877
|
+
*/
|
|
878
|
+
function toolDefinitions(): Record<string, {
|
|
879
|
+
description: string;
|
|
880
|
+
input: Record<string, unknown>;
|
|
881
|
+
execute: (args: any, context: any) => Promise<{ content: string }>;
|
|
882
|
+
}> {
|
|
772
883
|
return {
|
|
773
884
|
hicortex_search: {
|
|
774
885
|
description:
|
|
775
886
|
"Search shared long-term memory (all agents, all sessions). CALL THIS BEFORE assuming, guessing, or asking the user about anything that may have come up before: prior decisions, preferences, project facts, people, hardware, past incidents. If you are about to write 'I don't have information about…', search first.",
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
887
|
+
input: {
|
|
888
|
+
type: "object",
|
|
889
|
+
properties: {
|
|
890
|
+
query: { type: "string", description: "Search query text (required)" },
|
|
891
|
+
limit: { type: "number", description: "Max results (default 5)" },
|
|
892
|
+
project: { type: "string", description: "Filter by project name" },
|
|
893
|
+
},
|
|
780
894
|
},
|
|
781
|
-
async execute(args: any): Promise<string> {
|
|
895
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
782
896
|
try {
|
|
783
897
|
const cfg = resolveOpencodeConfig();
|
|
784
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
898
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
785
899
|
const params = new URLSearchParams({ query: String(args?.query ?? "") });
|
|
786
900
|
if (args?.limit) params.set("limit", String(args.limit));
|
|
787
901
|
if (args?.project) params.set("project", String(args.project));
|
|
788
902
|
if (LAST_AGENT) params.set("agent", LAST_AGENT);
|
|
789
|
-
const { data, status } = await serverGet(cfg, `/search?${params}
|
|
790
|
-
if (!data) return errorResult(`Search failed: ${describeGetFailure(status)}`);
|
|
791
|
-
return formatSearchResults(data.results ?? []);
|
|
903
|
+
const { data, status } = await serverGet(cfg, `/search?${params}`, context?.signal);
|
|
904
|
+
if (!data) return { content: errorResult(`Search failed: ${describeGetFailure(status)}`) };
|
|
905
|
+
return { content: formatSearchResults(data.results ?? []) };
|
|
792
906
|
} catch (err) {
|
|
793
|
-
return errorResult(`Search failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
907
|
+
return { content: errorResult(`Search failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
794
908
|
}
|
|
795
909
|
},
|
|
796
910
|
},
|
|
@@ -798,28 +912,31 @@ function registerTools(): Record<string, unknown> {
|
|
|
798
912
|
hicortex_get: {
|
|
799
913
|
description:
|
|
800
914
|
"Fetch ONE memory's full content by id — use this to lazy-load entries from the '## Memory recall (auto)' index or from search results whose snippet was not enough. Fetching a memory marks it as used (strengthens it), so fetch entries that could change your action — not every shown one. When the memory shapes your answer, cite it to the user (id + date + origin agent) — mark a fetched memory `FETCHED` and a one-line entry cited unread `SNIPPET`; don't pass SNIPPET off as established.",
|
|
801
|
-
|
|
802
|
-
|
|
915
|
+
input: {
|
|
916
|
+
type: "object",
|
|
917
|
+
properties: {
|
|
918
|
+
id: { type: "string", description: "Memory ID (required; as shown in the recall index or search results)" },
|
|
919
|
+
},
|
|
803
920
|
},
|
|
804
|
-
async execute(args: any): Promise<string> {
|
|
921
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
805
922
|
try {
|
|
806
|
-
if (!args?.id) return errorResult("id is required");
|
|
923
|
+
if (!args?.id) return { content: errorResult("id is required") };
|
|
807
924
|
const cfg = resolveOpencodeConfig();
|
|
808
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
925
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
809
926
|
const params = new URLSearchParams({ id: String(args.id) });
|
|
810
927
|
if (LAST_AGENT) params.set("agent", LAST_AGENT);
|
|
811
|
-
const { data, status } = await serverGet(cfg, `/memory?${params}
|
|
928
|
+
const { data, status } = await serverGet(cfg, `/memory?${params}`, context?.signal);
|
|
812
929
|
if (status === 404) {
|
|
813
930
|
// Either no such memory (0.14+) or a pre-0.14 server with no
|
|
814
931
|
// /memory endpoint — the id hint covers the common case.
|
|
815
|
-
return errorResult(`Memory not found: ${args.id} (or the server predates 0.14 — upgrade the server)`);
|
|
932
|
+
return { content: errorResult(`Memory not found: ${args.id} (or the server predates 0.14 — upgrade the server)`) };
|
|
816
933
|
}
|
|
817
|
-
if (!data) return errorResult(`Get failed: ${describeGetFailure(status)}`);
|
|
934
|
+
if (!data) return { content: errorResult(`Get failed: ${describeGetFailure(status)}`) };
|
|
818
935
|
// Render the content BEHIND the server's citation string — the
|
|
819
936
|
// server-side rendering is the single provenance norm (0.14.1).
|
|
820
|
-
return `${data.citation ?? ""}\n\n${data.memory?.content ?? ""}`.trim();
|
|
937
|
+
return { content: `${data.citation ?? ""}\n\n${data.memory?.content ?? ""}`.trim() };
|
|
821
938
|
} catch (err) {
|
|
822
|
-
return errorResult(`Get failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
939
|
+
return { content: errorResult(`Get failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
823
940
|
}
|
|
824
941
|
},
|
|
825
942
|
},
|
|
@@ -827,24 +944,27 @@ function registerTools(): Record<string, unknown> {
|
|
|
827
944
|
hicortex_recent: {
|
|
828
945
|
description:
|
|
829
946
|
"Get recent memories, optionally filtered by project. CALL THIS AT THE START of substantive work on a project to catch up on its latest state — cheaper than asking the user what happened.",
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
947
|
+
input: {
|
|
948
|
+
type: "object",
|
|
949
|
+
properties: {
|
|
950
|
+
project: { type: "string", description: "Filter by project name" },
|
|
951
|
+
limit: { type: "number", description: "Max results (default 10)" },
|
|
952
|
+
},
|
|
833
953
|
},
|
|
834
|
-
async execute(args: any): Promise<string> {
|
|
954
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
835
955
|
try {
|
|
836
956
|
const cfg = resolveOpencodeConfig();
|
|
837
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
957
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
838
958
|
const params = new URLSearchParams();
|
|
839
959
|
if (args?.project) params.set("project", String(args.project));
|
|
840
960
|
if (args?.limit) params.set("limit", String(args.limit));
|
|
841
961
|
if (LAST_AGENT) params.set("agent", LAST_AGENT);
|
|
842
962
|
const qs = params.toString();
|
|
843
|
-
const { data, status } = await serverGet(cfg, `/recent${qs ? `?${qs}` : ""}
|
|
844
|
-
if (!data) return errorResult(`Recent recall failed: ${describeGetFailure(status)}`);
|
|
845
|
-
return formatSearchResults(data.results ?? []);
|
|
963
|
+
const { data, status } = await serverGet(cfg, `/recent${qs ? `?${qs}` : ""}`, context?.signal);
|
|
964
|
+
if (!data) return { content: errorResult(`Recent recall failed: ${describeGetFailure(status)}`) };
|
|
965
|
+
return { content: formatSearchResults(data.results ?? []) };
|
|
846
966
|
} catch (err) {
|
|
847
|
-
return errorResult(`Recent recall failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
967
|
+
return { content: errorResult(`Recent recall failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
848
968
|
}
|
|
849
969
|
},
|
|
850
970
|
},
|
|
@@ -852,33 +972,36 @@ function registerTools(): Record<string, unknown> {
|
|
|
852
972
|
hicortex_ingest: {
|
|
853
973
|
description:
|
|
854
974
|
"Store a new memory in long-term storage. Use for Knowledge, Decisions, or Learnings. Capture is automatic (nightly) — use this ONLY for explicitly requested learnings, never routine content.",
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
type: "string",
|
|
860
|
-
|
|
861
|
-
|
|
975
|
+
input: {
|
|
976
|
+
type: "object",
|
|
977
|
+
properties: {
|
|
978
|
+
content: { type: "string", description: "Memory content to store (required)" },
|
|
979
|
+
project: { type: "string", description: "Project this memory belongs to" },
|
|
980
|
+
memory_type: {
|
|
981
|
+
type: "string",
|
|
982
|
+
description:
|
|
983
|
+
"Type of memory (default: Experience). Accepted: knowledge/experience/decisions/learnings (legacy fact/episode/decision/lesson also accepted, normalized to the canonical term).",
|
|
984
|
+
},
|
|
862
985
|
},
|
|
863
986
|
},
|
|
864
|
-
async execute(args: any): Promise<string> {
|
|
987
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
865
988
|
try {
|
|
866
989
|
const cfg = resolveOpencodeConfig();
|
|
867
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
990
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
868
991
|
const rawType = typeof args?.memory_type === "string" ? args.memory_type : "";
|
|
869
992
|
const result = await serverPost(cfg, "/ingest", {
|
|
870
993
|
content: args?.content,
|
|
871
994
|
source_agent: "opencode/manual",
|
|
872
995
|
project: args?.project,
|
|
873
996
|
memory_type: rawType ? (TO_CANONICAL_TYPE[rawType.toLowerCase()] ?? rawType) : "experience",
|
|
874
|
-
});
|
|
997
|
+
}, context?.signal);
|
|
875
998
|
if (!result.ok) {
|
|
876
|
-
return errorResult(`Ingest failed: ${result.data?.error ?? `HTTP ${result.status}`}`);
|
|
999
|
+
return { content: errorResult(`Ingest failed: ${result.data?.error ?? `HTTP ${result.status}`}`) };
|
|
877
1000
|
}
|
|
878
1001
|
const id = result.data?.id ?? "unknown";
|
|
879
|
-
return `Memory stored (id: ${String(id).slice(0, 8)})
|
|
1002
|
+
return { content: `Memory stored (id: ${String(id).slice(0, 8)})` };
|
|
880
1003
|
} catch (err) {
|
|
881
|
-
return errorResult(`Ingest failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1004
|
+
return { content: errorResult(`Ingest failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
882
1005
|
}
|
|
883
1006
|
},
|
|
884
1007
|
},
|
|
@@ -886,26 +1009,31 @@ function registerTools(): Record<string, unknown> {
|
|
|
886
1009
|
hicortex_lessons: {
|
|
887
1010
|
description:
|
|
888
1011
|
"Get actionable Learnings — auto-generated insights about mistakes to avoid. CALL THIS before retrying an approach that failed before, or when picking up work where past problems may have been recorded.",
|
|
889
|
-
|
|
890
|
-
|
|
1012
|
+
input: {
|
|
1013
|
+
type: "object",
|
|
1014
|
+
properties: {
|
|
1015
|
+
project: { type: "string", description: "Filter by project name (optional)" },
|
|
1016
|
+
},
|
|
891
1017
|
},
|
|
892
|
-
async execute(_args: any): Promise<string> {
|
|
1018
|
+
async execute(_args: any, context: any): Promise<{ content: string }> {
|
|
893
1019
|
try {
|
|
894
1020
|
const cfg = resolveOpencodeConfig();
|
|
895
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
1021
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
896
1022
|
const lessonsUrl = LAST_AGENT
|
|
897
1023
|
? `/learnings?agent=${encodeURIComponent(LAST_AGENT)}`
|
|
898
1024
|
: "/learnings";
|
|
899
|
-
const { data, status } = await serverGet(cfg, lessonsUrl);
|
|
900
|
-
if (!data) return errorResult(`Lessons fetch failed: ${describeGetFailure(status)}`);
|
|
1025
|
+
const { data, status } = await serverGet(cfg, lessonsUrl, context?.signal);
|
|
1026
|
+
if (!data) return { content: errorResult(`Lessons fetch failed: ${describeGetFailure(status)}`) };
|
|
901
1027
|
const lessons = data.lessons ?? [];
|
|
902
1028
|
if (lessons.length === 0) {
|
|
903
|
-
return "No Learnings found.";
|
|
1029
|
+
return { content: "No Learnings found." };
|
|
904
1030
|
}
|
|
905
|
-
return
|
|
906
|
-
|
|
1031
|
+
return {
|
|
1032
|
+
content: lessons.map((l: { content?: unknown }) =>
|
|
1033
|
+
`- ${typeof l.content === "string" ? l.content.slice(0, 500) : ""}`).join("\n"),
|
|
1034
|
+
};
|
|
907
1035
|
} catch (err) {
|
|
908
|
-
return errorResult(`Lessons fetch failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1036
|
+
return { content: errorResult(`Lessons fetch failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
909
1037
|
}
|
|
910
1038
|
},
|
|
911
1039
|
},
|
|
@@ -913,16 +1041,19 @@ function registerTools(): Record<string, unknown> {
|
|
|
913
1041
|
hicortex_index: {
|
|
914
1042
|
description:
|
|
915
1043
|
"Get the knowledge domain index — shows what topics and projects are stored in memory, grouped by domain. Call before a broad search to see which knowledge domains exist, or when unsure what the memory covers.",
|
|
916
|
-
|
|
917
|
-
|
|
1044
|
+
input: {
|
|
1045
|
+
type: "object",
|
|
1046
|
+
properties: {},
|
|
1047
|
+
},
|
|
1048
|
+
async execute(_args: any, context: any): Promise<{ content: string }> {
|
|
918
1049
|
try {
|
|
919
1050
|
const cfg = resolveOpencodeConfig();
|
|
920
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
921
|
-
const { data, status } = await serverGet(cfg, "/index");
|
|
922
|
-
if (!data) return errorResult(`Index fetch failed: ${describeGetFailure(status)}`);
|
|
923
|
-
return JSON.stringify(data);
|
|
1051
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
1052
|
+
const { data, status } = await serverGet(cfg, "/index", context?.signal);
|
|
1053
|
+
if (!data) return { content: errorResult(`Index fetch failed: ${describeGetFailure(status)}`) };
|
|
1054
|
+
return { content: JSON.stringify(data) };
|
|
924
1055
|
} catch (err) {
|
|
925
|
-
return errorResult(`Index fetch failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1056
|
+
return { content: errorResult(`Index fetch failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
926
1057
|
}
|
|
927
1058
|
},
|
|
928
1059
|
},
|
|
@@ -930,18 +1061,21 @@ function registerTools(): Record<string, unknown> {
|
|
|
930
1061
|
hicortex_graph: {
|
|
931
1062
|
description:
|
|
932
1063
|
"Query the memory knowledge graph — find connected memories, hub nodes, or paths between memories. Use it to explore memories connected to one you just fetched, or to find hub memories in a domain.",
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
1064
|
+
input: {
|
|
1065
|
+
type: "object",
|
|
1066
|
+
properties: {
|
|
1067
|
+
operation: { type: "string", description: "Graph operation to perform: neighbors, hubs, or path (required)" },
|
|
1068
|
+
id: { type: "string", description: "Memory ID (required for neighbors and path operations)" },
|
|
1069
|
+
target_id: { type: "string", description: "Target memory ID (required for path operation)" },
|
|
1070
|
+
limit: { type: "number", description: "Max results (default 10)" },
|
|
1071
|
+
domain: { type: "string", description: "Filter hubs by domain" },
|
|
1072
|
+
relationship: { type: "string", description: "Filter neighbors by relationship type (e.g., extends, relates_to; legacy data may also have CONTRADICTS, SUPERSEDES, updates)" },
|
|
1073
|
+
},
|
|
940
1074
|
},
|
|
941
|
-
async execute(args: any): Promise<string> {
|
|
1075
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
942
1076
|
try {
|
|
943
1077
|
const cfg = resolveOpencodeConfig();
|
|
944
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
1078
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
945
1079
|
const params = new URLSearchParams({ op: String(args?.operation ?? "") });
|
|
946
1080
|
if (args?.id) params.set("id", String(args.id));
|
|
947
1081
|
if (args?.target_id) params.set("target_id", String(args.target_id));
|
|
@@ -949,11 +1083,11 @@ function registerTools(): Record<string, unknown> {
|
|
|
949
1083
|
if (args?.domain) params.set("domain", String(args.domain));
|
|
950
1084
|
if (args?.relationship) params.set("relationship", String(args.relationship));
|
|
951
1085
|
if (LAST_AGENT) params.set("agent", LAST_AGENT);
|
|
952
|
-
const { data, status } = await serverGet(cfg, `/graph?${params}
|
|
953
|
-
if (!data) return errorResult(`Graph query failed: ${describeGetFailure(status)}`);
|
|
954
|
-
return JSON.stringify(data);
|
|
1086
|
+
const { data, status } = await serverGet(cfg, `/graph?${params}`, context?.signal);
|
|
1087
|
+
if (!data) return { content: errorResult(`Graph query failed: ${describeGetFailure(status)}`) };
|
|
1088
|
+
return { content: JSON.stringify(data) };
|
|
955
1089
|
} catch (err) {
|
|
956
|
-
return errorResult(`Graph query failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1090
|
+
return { content: errorResult(`Graph query failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
957
1091
|
}
|
|
958
1092
|
},
|
|
959
1093
|
},
|
|
@@ -961,37 +1095,40 @@ function registerTools(): Record<string, unknown> {
|
|
|
961
1095
|
hicortex_update: {
|
|
962
1096
|
description:
|
|
963
1097
|
"Update an existing memory. Use after searching to fix incorrect information. If content changes, the embedding is re-computed.",
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
type: "string",
|
|
970
|
-
|
|
971
|
-
|
|
1098
|
+
input: {
|
|
1099
|
+
type: "object",
|
|
1100
|
+
properties: {
|
|
1101
|
+
id: { type: "string", description: "Memory ID (required; from search results, first 8 chars or full UUID)" },
|
|
1102
|
+
content: { type: "string", description: "New content text" },
|
|
1103
|
+
project: { type: "string", description: "New project name" },
|
|
1104
|
+
memory_type: {
|
|
1105
|
+
type: "string",
|
|
1106
|
+
description:
|
|
1107
|
+
"New memory type. Accepted: knowledge/experience/decisions/learnings (legacy fact/episode/decision/lesson also accepted, normalized to the canonical term).",
|
|
1108
|
+
},
|
|
972
1109
|
},
|
|
973
1110
|
},
|
|
974
|
-
async execute(args: any): Promise<string> {
|
|
1111
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
975
1112
|
try {
|
|
976
1113
|
const cfg = resolveOpencodeConfig();
|
|
977
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
1114
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
978
1115
|
const rawType = typeof args?.memory_type === "string" ? args.memory_type : "";
|
|
979
1116
|
const result = await serverPost(cfg, "/update", {
|
|
980
1117
|
id: args?.id,
|
|
981
1118
|
content: args?.content,
|
|
982
1119
|
project: args?.project,
|
|
983
1120
|
memory_type: rawType ? (TO_CANONICAL_TYPE[rawType.toLowerCase()] ?? rawType) : undefined,
|
|
984
|
-
});
|
|
1121
|
+
}, context?.signal);
|
|
985
1122
|
if (result.status === 404) {
|
|
986
|
-
return errorResult(`Memory not found: ${args?.id}`);
|
|
1123
|
+
return { content: errorResult(`Memory not found: ${args?.id}`) };
|
|
987
1124
|
}
|
|
988
1125
|
if (!result.ok) {
|
|
989
|
-
return errorResult(`Update failed: ${result.data?.error ?? `HTTP ${result.status}`}`);
|
|
1126
|
+
return { content: errorResult(`Update failed: ${result.data?.error ?? `HTTP ${result.status}`}`) };
|
|
990
1127
|
}
|
|
991
1128
|
const id = result.data?.id ?? args?.id;
|
|
992
|
-
return `Memory updated (id: ${String(id).slice(0, 8)})
|
|
1129
|
+
return { content: `Memory updated (id: ${String(id).slice(0, 8)})` };
|
|
993
1130
|
} catch (err) {
|
|
994
|
-
return errorResult(`Update failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1131
|
+
return { content: errorResult(`Update failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
995
1132
|
}
|
|
996
1133
|
},
|
|
997
1134
|
},
|
|
@@ -999,23 +1136,26 @@ function registerTools(): Record<string, unknown> {
|
|
|
999
1136
|
hicortex_delete: {
|
|
1000
1137
|
description:
|
|
1001
1138
|
"Permanently delete a memory and its links. Use when a memory is incorrect and should be removed entirely.",
|
|
1002
|
-
|
|
1003
|
-
|
|
1139
|
+
input: {
|
|
1140
|
+
type: "object",
|
|
1141
|
+
properties: {
|
|
1142
|
+
id: { type: "string", description: "Memory ID (required; from search results, first 8 chars or full UUID)" },
|
|
1143
|
+
},
|
|
1004
1144
|
},
|
|
1005
|
-
async execute(args: any): Promise<string> {
|
|
1145
|
+
async execute(args: any, context: any): Promise<{ content: string }> {
|
|
1006
1146
|
try {
|
|
1007
1147
|
const cfg = resolveOpencodeConfig();
|
|
1008
|
-
if (!cfg) return errorResult(NOT_CONFIGURED);
|
|
1009
|
-
const result = await serverPost(cfg, "/delete", { id: args?.id });
|
|
1148
|
+
if (!cfg) return { content: errorResult(NOT_CONFIGURED) };
|
|
1149
|
+
const result = await serverPost(cfg, "/delete", { id: args?.id }, context?.signal);
|
|
1010
1150
|
if (result.status === 404) {
|
|
1011
|
-
return errorResult(`Memory not found: ${args?.id}`);
|
|
1151
|
+
return { content: errorResult(`Memory not found: ${args?.id}`) };
|
|
1012
1152
|
}
|
|
1013
1153
|
if (!result.ok) {
|
|
1014
|
-
return errorResult(`Delete failed: ${result.data?.error ?? `HTTP ${result.status}`}`);
|
|
1154
|
+
return { content: errorResult(`Delete failed: ${result.data?.error ?? `HTTP ${result.status}`}`) };
|
|
1015
1155
|
}
|
|
1016
|
-
return `Memory deleted (id: ${String(args?.id).slice(0, 8)})
|
|
1156
|
+
return { content: `Memory deleted (id: ${String(args?.id).slice(0, 8)})` };
|
|
1017
1157
|
} catch (err) {
|
|
1018
|
-
return errorResult(`Delete failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1158
|
+
return { content: errorResult(`Delete failed: ${err instanceof Error ? err.message : String(err)}`) };
|
|
1019
1159
|
}
|
|
1020
1160
|
},
|
|
1021
1161
|
},
|
|
@@ -1023,117 +1163,175 @@ function registerTools(): Record<string, unknown> {
|
|
|
1023
1163
|
}
|
|
1024
1164
|
|
|
1025
1165
|
// ---------------------------------------------------------------------------
|
|
1026
|
-
//
|
|
1166
|
+
// Injection — the ONE context hook drives both channels
|
|
1027
1167
|
// ---------------------------------------------------------------------------
|
|
1028
1168
|
|
|
1029
1169
|
/**
|
|
1030
|
-
* The
|
|
1031
|
-
*
|
|
1032
|
-
*
|
|
1033
|
-
* the same factory is a second factory call for the loader, #353). The
|
|
1034
|
-
* single-export shape is live-verified on opencode 1.18.20 and 1.18.23;
|
|
1035
|
-
* the 0.21.0 multi-export shape was live-refuted on 1.18.23 (helper called
|
|
1036
|
-
* with undefined → plugin rejected). An async factory returning the hooks
|
|
1037
|
-
* object; never throws — a broken plugin must not take down the agent loop.
|
|
1170
|
+
* The session id a context/compaction event carries (doc-confirmed readonly
|
|
1171
|
+
* `sessionID` field), falling back to the last user message's
|
|
1172
|
+
* info.sessionID — the V1 path — when the event field is somehow absent.
|
|
1038
1173
|
*/
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1174
|
+
function eventSessionId(event: any, messages: unknown): string | null {
|
|
1175
|
+
if (typeof event?.sessionID === "string" && event.sessionID) return event.sessionID;
|
|
1176
|
+
const last = lastUserMessage(messages);
|
|
1177
|
+
return last ? messageSessionId(last.msg) : null;
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* Pushed recall: find the LAST real user message, fetch (or re-inject from
|
|
1182
|
+
* the stash), append ONE synthetic user message after it. The context hook
|
|
1183
|
+
* rebuilds its event per model request from the STORED messages, so
|
|
1184
|
+
* re-injecting the stashed block on tool-loop requests cannot double, and
|
|
1185
|
+
* the injected message never reaches the store.
|
|
1186
|
+
*/
|
|
1187
|
+
async function injectRecall(ctx: any, event: any): Promise<void> {
|
|
1188
|
+
const messages = Array.isArray(event?.messages) ? event.messages : null;
|
|
1189
|
+
if (!messages) return;
|
|
1190
|
+
const last = lastUserMessage(messages);
|
|
1191
|
+
if (!last) return;
|
|
1192
|
+
const sessionId = eventSessionId(event, messages);
|
|
1193
|
+
if (!sessionId) return;
|
|
1194
|
+
const cfg = resolveOpencodeConfig();
|
|
1195
|
+
if (!cfg) return;
|
|
1196
|
+
pruneSessionState();
|
|
1197
|
+
// #600: resolve the workspace agent from the session's OWN directory
|
|
1198
|
+
// (fail-closed null); publishes to LAST_AGENT for the tool proxies and
|
|
1199
|
+
// rides the recall body.
|
|
1200
|
+
const { cwd, agent } = await resolveWorkspace(ctx, event, sessionId);
|
|
1201
|
+
|
|
1202
|
+
// Ordering (#316): a pending reset for THIS session registered before this
|
|
1203
|
+
// fetch must complete first — bounded by the reset's own 1 s timeout, so a
|
|
1204
|
+
// stalled server cannot stall the turn beyond it.
|
|
1205
|
+
const pending = PENDING_RESETS.get(sessionId);
|
|
1206
|
+
if (pending) await pending;
|
|
1207
|
+
|
|
1208
|
+
const prompt = messageText(last.msg);
|
|
1209
|
+
// A tool-loop request repeats the SAME user message id — only a new id
|
|
1210
|
+
// (falling back to the prompt text when ids are absent) is a new prompt
|
|
1211
|
+
// worth a fetch.
|
|
1212
|
+
const promptKey = typeof last.msg.id === "string" && last.msg.id ? last.msg.id : prompt;
|
|
1213
|
+
if (PROMPT_KEYS.get(sessionId) !== promptKey) {
|
|
1214
|
+
const block = prompt
|
|
1215
|
+
? await fetchRecallBlock(cfg, sessionId, prompt, cwd ?? "", agent).catch(() => null)
|
|
1216
|
+
: null;
|
|
1217
|
+
RECALL_BLOCKS.set(sessionId, block);
|
|
1218
|
+
PROMPT_KEYS.set(sessionId, promptKey);
|
|
1219
|
+
}
|
|
1220
|
+
const block = RECALL_BLOCKS.get(sessionId) ?? null;
|
|
1221
|
+
if (!block) return;
|
|
1222
|
+
const synthetic = buildRecallMessage(last.msg, fenceBlock(block));
|
|
1223
|
+
if (synthetic) messages.splice(last.index + 1, 0, synthetic);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/**
|
|
1227
|
+
* Identity + lessons: ONE fenced system part appended to the event's system
|
|
1228
|
+
* array. Fetched once per session (independent fail-soft); the fence guard
|
|
1229
|
+
* prevents doubling when a part already carries our end marker.
|
|
1230
|
+
*/
|
|
1231
|
+
async function injectIdentityAndLessons(ctx: any, event: any): Promise<void> {
|
|
1232
|
+
const system = Array.isArray(event?.system) ? event.system : null;
|
|
1233
|
+
if (!system || systemAlreadyFenced(system)) return;
|
|
1234
|
+
const cfg = resolveOpencodeConfig();
|
|
1235
|
+
if (!cfg) return;
|
|
1236
|
+
pruneSessionState();
|
|
1237
|
+
const sessionId = eventSessionId(event, event?.messages) ?? FALLBACK_SESSION_KEY;
|
|
1238
|
+
// #600: the workspace agent for the lessons pool (member-gated) — the
|
|
1239
|
+
// session's own directory when it resolves, else the last-known id.
|
|
1240
|
+
const { agent } = await resolveWorkspace(ctx, event, event?.sessionID ?? null);
|
|
1241
|
+
const [identityBlock, lessonsBlock] = await Promise.all([
|
|
1242
|
+
cachedBlock(IDENTITY_BLOCKS, sessionId, () => fetchIdentityBlock(cfg)),
|
|
1243
|
+
cachedAgentBlock(LESSONS_BLOCKS, sessionId, agent, () => fetchLessonsBlock(cfg, agent)),
|
|
1244
|
+
]);
|
|
1245
|
+
const entry = renderContextEntry([identityBlock, lessonsBlock]);
|
|
1246
|
+
if (entry) (system as unknown[]).push({ type: "text", text: entry });
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// ---------------------------------------------------------------------------
|
|
1250
|
+
// Entry — the ONE runtime export (V2 loader contract, see header)
|
|
1251
|
+
// ---------------------------------------------------------------------------
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* The V2 plugin definition. `setup` registers every channel individually
|
|
1255
|
+
* fail-soft: an API drift on one channel (a renamed hook, a moved transform)
|
|
1256
|
+
* degrades to no memory on that channel — never a broken agent loop. No
|
|
1257
|
+
* cleanup is returned: the plugin owns no timers, sockets, or subscriptions
|
|
1258
|
+
* (the event-stream experiment stays out of the shipped wiring — the probe
|
|
1259
|
+
* showed the undocumented V2EventEncoded stream adds nothing the typed
|
|
1260
|
+
* hooks already cover).
|
|
1261
|
+
*/
|
|
1262
|
+
export default {
|
|
1263
|
+
id: "hicortex",
|
|
1264
|
+
async setup(ctx: any): Promise<void> {
|
|
1265
|
+
try {
|
|
1266
|
+
await ctx?.session?.hook?.("context", async (event: any) => {
|
|
1045
1267
|
try {
|
|
1046
|
-
|
|
1047
|
-
|
|
1268
|
+
await injectRecall(ctx, event);
|
|
1269
|
+
} catch {
|
|
1270
|
+
// Fail-soft: inject nothing, never block the request.
|
|
1271
|
+
}
|
|
1272
|
+
try {
|
|
1273
|
+
await injectIdentityAndLessons(ctx, event);
|
|
1274
|
+
} catch {
|
|
1275
|
+
// Fail-soft: inject nothing, never block the request.
|
|
1276
|
+
}
|
|
1277
|
+
});
|
|
1278
|
+
} catch {
|
|
1279
|
+
// Registration failed (unexpected opencode API change) — recall and
|
|
1280
|
+
// identity/lessons are both gone, but the session must proceed.
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
try {
|
|
1284
|
+
// Dedup reset at session start — the prompt hook's edits PERSIST (it
|
|
1285
|
+
// is the admission boundary), so this callback makes ZERO edits; it
|
|
1286
|
+
// only marks the first-seen session and fires the server-side reset.
|
|
1287
|
+
await ctx?.session?.hook?.("prompt", async (event: any) => {
|
|
1288
|
+
try {
|
|
1289
|
+
const sessionId = typeof event?.sessionID === "string" && event.sessionID ? event.sessionID : null;
|
|
1290
|
+
if (!sessionId || SEEN_SESSIONS.has(sessionId)) return;
|
|
1291
|
+
SEEN_SESSIONS.add(sessionId);
|
|
1292
|
+
pruneSessionState();
|
|
1048
1293
|
dropSessionState(sessionId);
|
|
1049
1294
|
const cfg = resolveOpencodeConfig();
|
|
1050
1295
|
if (cfg) void resetRecallDedup(cfg, sessionId);
|
|
1051
1296
|
} catch {
|
|
1052
1297
|
/* fail-soft */
|
|
1053
1298
|
}
|
|
1054
|
-
}
|
|
1299
|
+
});
|
|
1300
|
+
} catch {
|
|
1301
|
+
/* fail-soft — session-start resets are an optimization, not a need */
|
|
1302
|
+
}
|
|
1055
1303
|
|
|
1056
|
-
|
|
1057
|
-
//
|
|
1058
|
-
//
|
|
1059
|
-
//
|
|
1060
|
-
"
|
|
1304
|
+
try {
|
|
1305
|
+
// Dedup reset at compaction: the post-compaction session keeps the
|
|
1306
|
+
// SAME session id, so the server-side shown-set must be cleared or the
|
|
1307
|
+
// rest of the session would stay suppressed.
|
|
1308
|
+
await ctx?.session?.hook?.("compaction", async (event: any) => {
|
|
1061
1309
|
try {
|
|
1062
|
-
const
|
|
1063
|
-
if (!messages) return;
|
|
1064
|
-
const last = lastUserMessage(messages);
|
|
1065
|
-
if (!last) return;
|
|
1066
|
-
const sessionId = messageSessionId(last.msg);
|
|
1310
|
+
const sessionId = typeof event?.sessionID === "string" && event.sessionID ? event.sessionID : null;
|
|
1067
1311
|
if (!sessionId) return;
|
|
1312
|
+
dropSessionState(sessionId);
|
|
1068
1313
|
const cfg = resolveOpencodeConfig();
|
|
1069
|
-
if (
|
|
1070
|
-
pruneSessionState();
|
|
1071
|
-
// #600: resolve the workspace agent from the input's OWN directory
|
|
1072
|
-
// (strict — no process.cwd fallback); publishes to LAST_AGENT for
|
|
1073
|
-
// the tool proxies and rides the recall body.
|
|
1074
|
-
const agent = currentAgent(input);
|
|
1075
|
-
|
|
1076
|
-
// Ordering (#316): a pending reset for THIS session registered
|
|
1077
|
-
// before this fetch must complete first — bounded by the reset's
|
|
1078
|
-
// own 1 s timeout, so a stalled server cannot stall the turn beyond it.
|
|
1079
|
-
const pending = PENDING_RESETS.get(sessionId);
|
|
1080
|
-
if (pending) await pending;
|
|
1081
|
-
|
|
1082
|
-
const prompt = messageText(last.msg);
|
|
1083
|
-
// A tool-loop request repeats the SAME user message id — only a new
|
|
1084
|
-
// id (falling back to the prompt text when ids are absent) is a new
|
|
1085
|
-
// prompt worth a fetch.
|
|
1086
|
-
const promptKey = typeof last.msg.id === "string" && last.msg.id ? last.msg.id : prompt;
|
|
1087
|
-
if (PROMPT_KEYS.get(sessionId) !== promptKey) {
|
|
1088
|
-
const block = prompt
|
|
1089
|
-
? await fetchRecallBlock(cfg, sessionId, prompt, cwdFromInput(input), agent).catch(() => null)
|
|
1090
|
-
: null;
|
|
1091
|
-
RECALL_BLOCKS.set(sessionId, block);
|
|
1092
|
-
PROMPT_KEYS.set(sessionId, promptKey);
|
|
1093
|
-
}
|
|
1094
|
-
const block = RECALL_BLOCKS.get(sessionId) ?? null;
|
|
1095
|
-
if (!block) return;
|
|
1096
|
-
const synthetic = buildRecallMessage(last.msg, fenceBlock(block));
|
|
1097
|
-
if (synthetic) messages.splice(last.index + 1, 0, synthetic);
|
|
1314
|
+
if (cfg) void resetRecallDedup(cfg, sessionId);
|
|
1098
1315
|
} catch {
|
|
1099
|
-
|
|
1316
|
+
/* fail-soft */
|
|
1100
1317
|
}
|
|
1101
|
-
}
|
|
1318
|
+
});
|
|
1319
|
+
} catch {
|
|
1320
|
+
/* fail-soft */
|
|
1321
|
+
}
|
|
1102
1322
|
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
const cfg = resolveOpencodeConfig();
|
|
1111
|
-
if (!cfg) return;
|
|
1112
|
-
pruneSessionState();
|
|
1113
|
-
// The hook input's session shape is not stable across opencode
|
|
1114
|
-
// versions — fall back to one process-wide cache key rather than
|
|
1115
|
-
// skipping injection entirely.
|
|
1116
|
-
const sessionId = inputSessionId(input) ?? FALLBACK_SESSION_KEY;
|
|
1117
|
-
// #600: the workspace agent for the lessons pool (member-gated) —
|
|
1118
|
-
// the input's own directory when it carries one, else the
|
|
1119
|
-
// last-known id a prompt hook resolved.
|
|
1120
|
-
const agent = currentAgent(input);
|
|
1121
|
-
const [identityBlock, lessonsBlock] = await Promise.all([
|
|
1122
|
-
cachedBlock(IDENTITY_BLOCKS, sessionId, () => fetchIdentityBlock(cfg)),
|
|
1123
|
-
cachedAgentBlock(LESSONS_BLOCKS, sessionId, agent, () => fetchLessonsBlock(cfg, agent)),
|
|
1124
|
-
]);
|
|
1125
|
-
const entry = renderContextEntry([identityBlock, lessonsBlock]);
|
|
1126
|
-
if (entry) (system as unknown[]).push(entry);
|
|
1127
|
-
} catch {
|
|
1128
|
-
// Total fail-soft: inject nothing, never block the request.
|
|
1323
|
+
try {
|
|
1324
|
+
await ctx?.tool?.transform?.((editor: any) => {
|
|
1325
|
+
for (const [name, def] of Object.entries(toolDefinitions())) {
|
|
1326
|
+
// {codemode: false} makes the tool a DIRECT call (probe-confirmed
|
|
1327
|
+
// on 2.4.0: a no-options registration lands in the Code Mode
|
|
1328
|
+
// catalog only, reachable solely via the execute tool).
|
|
1329
|
+
editor?.add?.({ name, ...def, options: { codemode: false } });
|
|
1129
1330
|
}
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
// silent; the session must proceed without memory either way.
|
|
1137
|
-
return {};
|
|
1138
|
-
}
|
|
1331
|
+
});
|
|
1332
|
+
} catch {
|
|
1333
|
+
// Registration failed — the tools are gone but the session proceeds
|
|
1334
|
+
// (same contract as the injection channels).
|
|
1335
|
+
}
|
|
1336
|
+
},
|
|
1139
1337
|
};
|