@vectorize-io/hindsight-coding-agents 0.7.0 → 0.8.1
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 +201 -16
- package/dist/antigravity-hook.js +1132 -115
- package/dist/antigravity-statusline.js +77 -11
- package/dist/antigravity-stop-hook.js +1193 -133
- package/dist/claude-hook.js +1132 -115
- package/dist/claude-sessionstart-hook.js +1241 -140
- package/dist/claude-stop-hook.js +1193 -133
- package/dist/cline.js +578 -163
- package/dist/codebuddy-hook.js +4270 -0
- package/dist/codebuddy-sessionstart-hook.js +5030 -0
- package/dist/codebuddy-stop-hook.js +4564 -0
- package/dist/codex-hook.js +1132 -115
- package/dist/codex-sessionstart-hook.js +1241 -140
- package/dist/codex-stop-hook.js +1193 -133
- package/dist/copilot-hook.js +1132 -115
- package/dist/copilot-sessionstart-hook.js +1241 -140
- package/dist/copilot-stop-hook.js +1193 -133
- package/dist/cursor-hook.js +1132 -115
- package/dist/cursor-sessionstart-hook.js +1241 -140
- package/dist/cursor-stop-hook.js +1193 -133
- package/dist/daemon-start.js +54 -9
- package/dist/dcode-hook.js +1132 -115
- package/dist/dcode-sessionstart-hook.js +1241 -140
- package/dist/dcode-stop-hook.js +1193 -133
- package/dist/deepen.js +370 -104
- package/dist/devin-hook.js +1132 -115
- package/dist/devin-sessionstart-hook.js +1241 -140
- package/dist/devin-stop-hook.js +1193 -133
- package/dist/droid-hook.js +1132 -115
- package/dist/droid-sessionstart-hook.js +1241 -140
- package/dist/droid-stop-hook.js +1193 -133
- package/dist/dsh.js +586 -164
- package/dist/grok-hook.js +1132 -115
- package/dist/grok-sessionstart-hook.js +1241 -140
- package/dist/grok-stop-hook.js +1193 -133
- package/dist/hindsight-seed.js +50 -8
- package/dist/index.js +587 -172
- package/dist/installer.js +2010 -769
- package/dist/kilo.js +587 -172
- package/dist/kimi-hook.js +4270 -0
- package/dist/kimi-sessionstart-hook.js +5030 -0
- package/dist/kimi-stop-hook.js +4564 -0
- package/dist/mcp-server.js +419 -115
- package/dist/opencode2.js +586 -169
- package/dist/pi.js +644 -175
- package/dist/prime-agent.js +644 -175
- package/dist/qwen-hook.js +1132 -115
- package/dist/qwen-sessionstart-hook.js +1241 -140
- package/dist/qwen-stop-hook.js +1193 -133
- package/dist/status.js +243 -52
- package/dist/traecode-hook.js +4270 -0
- package/dist/traecode-sessionstart-hook.js +5030 -0
- package/dist/traecode-stop-hook.js +4564 -0
- package/dist/workbuddy-hook.js +4270 -0
- package/dist/workbuddy-sessionstart-hook.js +5030 -0
- package/dist/workbuddy-stop-hook.js +4564 -0
- package/dist/zcode-hook.js +1132 -115
- package/dist/zcode-sessionstart-hook.js +1241 -140
- package/dist/zcode-stop-hook.js +1193 -133
- package/package.json +22 -12
- package/plugin.json +1 -1
- package/skill/SKILL.md +73 -14
package/dist/kilo.js
CHANGED
|
@@ -8,7 +8,7 @@ var __export = (target, all) => {
|
|
|
8
8
|
import { posix, win32 } from "path";
|
|
9
9
|
|
|
10
10
|
// src/core/config.ts
|
|
11
|
-
import { readFileSync as
|
|
11
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
12
12
|
import { homedir as homedir3 } from "os";
|
|
13
13
|
import { join as join7 } from "path";
|
|
14
14
|
|
|
@@ -51,6 +51,7 @@ import { homedir as homedir2 } from "os";
|
|
|
51
51
|
import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
|
|
52
52
|
|
|
53
53
|
// src/core/diag.ts
|
|
54
|
+
import { readFileSync } from "fs";
|
|
54
55
|
import { join as join3 } from "path";
|
|
55
56
|
|
|
56
57
|
// src/core/log.ts
|
|
@@ -126,7 +127,7 @@ function diag(harness, event, extra = {}) {
|
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
// src/core/git-layout.ts
|
|
129
|
-
import { lstatSync, readFileSync, realpathSync } from "fs";
|
|
130
|
+
import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
|
|
130
131
|
import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
|
|
131
132
|
var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
|
|
132
133
|
var ATTEMPTS = 3;
|
|
@@ -150,7 +151,7 @@ function entryKind(path) {
|
|
|
150
151
|
}
|
|
151
152
|
function readTextOrNull(path) {
|
|
152
153
|
try {
|
|
153
|
-
return
|
|
154
|
+
return readFileSync2(path, "utf8");
|
|
154
155
|
} catch (error95) {
|
|
155
156
|
if (TRANSIENT.has(errorCode(error95))) throw new TransientProbeError(errorCode(error95));
|
|
156
157
|
return null;
|
|
@@ -312,13 +313,13 @@ function isWithin(directory, configured) {
|
|
|
312
313
|
function mapLookup(map3, directory) {
|
|
313
314
|
const cwd = normalize(directory);
|
|
314
315
|
let best;
|
|
315
|
-
for (const [dir,
|
|
316
|
+
for (const [dir, value] of Object.entries(map3)) {
|
|
316
317
|
const p = configuredDir(dir);
|
|
317
318
|
if (isWithin(cwd, p)) {
|
|
318
|
-
if (!best || p.length > best.len) best = { len: p.length,
|
|
319
|
+
if (!best || p.length > best.len) best = { len: p.length, value };
|
|
319
320
|
}
|
|
320
321
|
}
|
|
321
|
-
return best?.
|
|
322
|
+
return best?.value;
|
|
322
323
|
}
|
|
323
324
|
function lookupDirectories(config3, directory, sessionRoot = "") {
|
|
324
325
|
const directories = [normalize(directory)];
|
|
@@ -342,6 +343,10 @@ function isOptedIn(config3, directory) {
|
|
|
342
343
|
const pathMap = config3.mapPathToBank;
|
|
343
344
|
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
344
345
|
}
|
|
346
|
+
function pathSection(config3, paths, directory) {
|
|
347
|
+
if (!directory || !paths) return void 0;
|
|
348
|
+
return lookupDirectories(config3, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
|
|
349
|
+
}
|
|
345
350
|
function mappedBank(config3, directory, sessionRoot) {
|
|
346
351
|
const pathMap = config3.mapPathToBank;
|
|
347
352
|
if (!directory || !pathMap) return void 0;
|
|
@@ -361,6 +366,19 @@ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
|
|
|
361
366
|
};
|
|
362
367
|
return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
363
368
|
}
|
|
369
|
+
function bankProjectName(config3, directory, sessionRoot) {
|
|
370
|
+
if (mappedBank(config3, directory, sessionRoot)) return void 0;
|
|
371
|
+
const dynamic = config3.dynamicBankId ?? !config3.bankId;
|
|
372
|
+
if (!dynamic) return void 0;
|
|
373
|
+
const template = config3.bankIdTemplate || DEFAULT_TEMPLATE;
|
|
374
|
+
if (!template.includes("{gitProject}")) return void 0;
|
|
375
|
+
try {
|
|
376
|
+
return gitProjectName(directory, config3.resolveWorktrees ?? true, sessionRoot);
|
|
377
|
+
} catch (error95) {
|
|
378
|
+
if (error95 instanceof BankResolutionError) return void 0;
|
|
379
|
+
throw error95;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
364
382
|
function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot) {
|
|
365
383
|
try {
|
|
366
384
|
return deriveBankId(config3, directory, harness, sessionRoot);
|
|
@@ -378,7 +396,7 @@ function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot)
|
|
|
378
396
|
// src/core/missions.ts
|
|
379
397
|
import { createHash } from "crypto";
|
|
380
398
|
var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
|
|
381
|
-
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history,
|
|
399
|
+
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
|
|
382
400
|
var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
|
|
383
401
|
var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
|
|
384
402
|
var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
|
|
@@ -454,6 +472,8 @@ var KNOWLEDGE_LABELS = {
|
|
|
454
472
|
]
|
|
455
473
|
};
|
|
456
474
|
function pageScopeRule(project) {
|
|
475
|
+
if (project === void 0)
|
|
476
|
+
return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
|
|
457
477
|
return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
|
|
458
478
|
}
|
|
459
479
|
var PAGE_TAXONOMY = [
|
|
@@ -589,12 +609,17 @@ var CODING_BANK_TEMPLATE = {
|
|
|
589
609
|
}
|
|
590
610
|
};
|
|
591
611
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
612
|
+
var PLUGIN_GOVERNED_BANK_FIELDS = [
|
|
613
|
+
"retain_strategies",
|
|
614
|
+
"entity_labels",
|
|
615
|
+
"retain_extraction_mode"
|
|
616
|
+
];
|
|
592
617
|
function isSet(v) {
|
|
593
618
|
if (v === null || v === void 0) return false;
|
|
594
619
|
if (typeof v === "string") return v.trim() !== "";
|
|
595
620
|
return true;
|
|
596
621
|
}
|
|
597
|
-
function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
|
|
622
|
+
function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
|
|
598
623
|
const current2 = overrides ?? {};
|
|
599
624
|
const template = CODING_BANK_TEMPLATE.bank;
|
|
600
625
|
const bank = {};
|
|
@@ -623,9 +648,16 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
|
|
|
623
648
|
const [knowledgeGroup] = template.entity_labels;
|
|
624
649
|
if (!labels.some((g) => g?.key === knowledgeGroup.key))
|
|
625
650
|
bank.entity_labels = [...labels, knowledgeGroup];
|
|
651
|
+
for (const [key, value] of Object.entries(defaults)) {
|
|
652
|
+
if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
|
|
653
|
+
bank[key] = value;
|
|
654
|
+
}
|
|
626
655
|
return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
|
|
627
656
|
}
|
|
628
657
|
|
|
658
|
+
// package.json
|
|
659
|
+
var version = "0.8.1";
|
|
660
|
+
|
|
629
661
|
// src/core/util.ts
|
|
630
662
|
import { accessSync, constants } from "fs";
|
|
631
663
|
import { delimiter, join as join6 } from "path";
|
|
@@ -649,12 +681,12 @@ function binOnPath(bin) {
|
|
|
649
681
|
}
|
|
650
682
|
}
|
|
651
683
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
652
|
-
function semverGte(
|
|
684
|
+
function semverGte(version4, min) {
|
|
653
685
|
const parts = (v) => {
|
|
654
686
|
const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
655
687
|
return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
|
|
656
688
|
};
|
|
657
|
-
const a =
|
|
689
|
+
const a = version4 ? parts(version4) : void 0;
|
|
658
690
|
const b = parts(min);
|
|
659
691
|
if (!a || !b) return false;
|
|
660
692
|
for (let i = 0; i < 3; i++) {
|
|
@@ -679,6 +711,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
679
711
|
}
|
|
680
712
|
|
|
681
713
|
// src/core/hindsight.ts
|
|
714
|
+
var USER_AGENT = `hindsight-coding-agents/${version}`;
|
|
682
715
|
function resolveRetainScopes(tags, configured) {
|
|
683
716
|
if (configured !== "per_source") return configured;
|
|
684
717
|
const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
|
|
@@ -714,7 +747,7 @@ async function isEndpointMissing(r) {
|
|
|
714
747
|
const j = await r.json();
|
|
715
748
|
return String(j?.detail ?? "").trim().toLowerCase() === "not found";
|
|
716
749
|
} catch {
|
|
717
|
-
return
|
|
750
|
+
return false;
|
|
718
751
|
}
|
|
719
752
|
}
|
|
720
753
|
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
@@ -733,6 +766,12 @@ var ReflectError = class extends Error {
|
|
|
733
766
|
get fallbackEligible() {
|
|
734
767
|
return this.timedOut || this.status !== void 0 && this.status >= 500;
|
|
735
768
|
}
|
|
769
|
+
/** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
|
|
770
|
+
* only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
|
|
771
|
+
get permanent() {
|
|
772
|
+
const s = this.status;
|
|
773
|
+
return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
|
|
774
|
+
}
|
|
736
775
|
};
|
|
737
776
|
var DEFAULT_MAX_PARALLEL_RETAINS = 10;
|
|
738
777
|
var DEFAULT_PAGE_SEARCH_LIMIT = 10;
|
|
@@ -743,8 +782,31 @@ var DEFAULT_RECALL_OPTIONS = {
|
|
|
743
782
|
include: { entities: null }
|
|
744
783
|
};
|
|
745
784
|
var POLL_CYCLE_MS = 5e3;
|
|
785
|
+
var POLL_MAX_SERVER_ERRORS = 12;
|
|
746
786
|
var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
|
|
747
787
|
var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
788
|
+
var RATE_LIMIT_BACKOFF_MS = 1e3;
|
|
789
|
+
function shapePage(page) {
|
|
790
|
+
const p = page ?? {};
|
|
791
|
+
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
792
|
+
return {
|
|
793
|
+
id: p.id,
|
|
794
|
+
name: p.name,
|
|
795
|
+
...p.description ? { description: p.description } : {},
|
|
796
|
+
...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
|
|
797
|
+
...p.timestamp ? { last_updated_at: p.timestamp } : {},
|
|
798
|
+
body
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
|
|
802
|
+
function signalOnlyDispatcher() {
|
|
803
|
+
void globalThis.Headers;
|
|
804
|
+
const d = globalThis[GLOBAL_DISPATCHER];
|
|
805
|
+
if (typeof d?.compose !== "function") return void 0;
|
|
806
|
+
return d.compose(
|
|
807
|
+
(dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
|
|
808
|
+
);
|
|
809
|
+
}
|
|
748
810
|
var HindsightClient = class {
|
|
749
811
|
apiUrl;
|
|
750
812
|
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
@@ -764,6 +826,7 @@ var HindsightClient = class {
|
|
|
764
826
|
observationScopes;
|
|
765
827
|
pageSearchLimit;
|
|
766
828
|
recallOptions;
|
|
829
|
+
rateLimitPatienceMs;
|
|
767
830
|
constructor(o) {
|
|
768
831
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
769
832
|
this.token = o.apiToken;
|
|
@@ -776,13 +839,18 @@ var HindsightClient = class {
|
|
|
776
839
|
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
777
840
|
this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
|
|
778
841
|
this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
|
|
842
|
+
this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
|
|
779
843
|
}
|
|
780
844
|
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
781
845
|
get apiToken() {
|
|
782
846
|
return this.token;
|
|
783
847
|
}
|
|
784
848
|
headers() {
|
|
785
|
-
const h = {
|
|
849
|
+
const h = {
|
|
850
|
+
"Content-Type": "application/json",
|
|
851
|
+
"Accept-Encoding": "identity",
|
|
852
|
+
"User-Agent": USER_AGENT
|
|
853
|
+
};
|
|
786
854
|
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
787
855
|
return h;
|
|
788
856
|
}
|
|
@@ -813,7 +881,8 @@ var HindsightClient = class {
|
|
|
813
881
|
* bounds the whole call.
|
|
814
882
|
*/
|
|
815
883
|
async fetchWithAuth(url3, init) {
|
|
816
|
-
const
|
|
884
|
+
const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
|
|
885
|
+
const send = () => fetch(url3, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
|
|
817
886
|
const r = await send();
|
|
818
887
|
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
819
888
|
return send();
|
|
@@ -829,13 +898,22 @@ var HindsightClient = class {
|
|
|
829
898
|
}
|
|
830
899
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
831
900
|
async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
901
|
+
const payload = body ? JSON.stringify(body) : void 0;
|
|
902
|
+
let r;
|
|
903
|
+
for (let attempt = 0, waited = 0; ; attempt++) {
|
|
904
|
+
r = await this.fetchWithAuth(url3, {
|
|
905
|
+
method,
|
|
906
|
+
body: payload,
|
|
907
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
908
|
+
});
|
|
909
|
+
if (r.status !== 429 || tolerate.includes(429)) break;
|
|
910
|
+
const asked = retryAfterMs(r.headers.get("retry-after"));
|
|
911
|
+
const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
|
|
912
|
+
const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
|
|
913
|
+
if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
|
|
914
|
+
await sleep(wait);
|
|
915
|
+
waited += wait;
|
|
916
|
+
}
|
|
839
917
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
840
918
|
throw new Error(
|
|
841
919
|
`${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
@@ -870,7 +948,7 @@ var HindsightClient = class {
|
|
|
870
948
|
}
|
|
871
949
|
/**
|
|
872
950
|
* Whether this server honours `operation_id` on an async retain, and can therefore be appended to
|
|
873
|
-
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via
|
|
951
|
+
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
|
|
874
952
|
* unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
|
|
875
953
|
*/
|
|
876
954
|
async supportsIdempotentRetain() {
|
|
@@ -880,14 +958,37 @@ var HindsightClient = class {
|
|
|
880
958
|
}
|
|
881
959
|
return this.idempotentRetain;
|
|
882
960
|
}
|
|
961
|
+
/** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
|
|
962
|
+
* hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
|
|
963
|
+
* so append silently never turned on (#5286). Servers that predate the alias still answer
|
|
964
|
+
* `/version`, so that stays as the fallback. */
|
|
883
965
|
async probeIdempotentRetain() {
|
|
966
|
+
for (const path of ["/v1/version", "/version"]) {
|
|
967
|
+
try {
|
|
968
|
+
const r = await this.req("GET", `${this.apiUrl}${path}`);
|
|
969
|
+
if (!r.ok) continue;
|
|
970
|
+
const j = await r.json();
|
|
971
|
+
return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
|
|
972
|
+
} catch {
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
return false;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Whether a session write-back may use `update_mode="append"`: the server must dedupe by
|
|
979
|
+
* `operation_id` AND the bank must keep document text, or the server rejects the append in the
|
|
980
|
+
* background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
|
|
981
|
+
* or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
|
|
982
|
+
*/
|
|
983
|
+
async supportsAppendRetain() {
|
|
984
|
+
if (!await this.supportsIdempotentRetain()) return false;
|
|
884
985
|
try {
|
|
885
|
-
const r = await this.req("GET",
|
|
886
|
-
if (!r.ok) return
|
|
986
|
+
const r = await this.req("GET", this.bankUrl("/config"));
|
|
987
|
+
if (!r.ok) return true;
|
|
887
988
|
const j = await r.json();
|
|
888
|
-
return
|
|
989
|
+
return j.config?.store_document_text !== false;
|
|
889
990
|
} catch {
|
|
890
|
-
return
|
|
991
|
+
return true;
|
|
891
992
|
}
|
|
892
993
|
}
|
|
893
994
|
/**
|
|
@@ -915,6 +1016,32 @@ var HindsightClient = class {
|
|
|
915
1016
|
}
|
|
916
1017
|
return ids;
|
|
917
1018
|
}
|
|
1019
|
+
/**
|
|
1020
|
+
* The tags on one document, or undefined when the bank holds none with that id. Read from the
|
|
1021
|
+
* document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
|
|
1022
|
+
* the page) rather than GET /documents/{id}, which also sends the document's full text: the
|
|
1023
|
+
* caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
|
|
1024
|
+
*/
|
|
1025
|
+
async documentTags(documentId) {
|
|
1026
|
+
const limit = 100;
|
|
1027
|
+
for (let offset = 0; ; offset += limit) {
|
|
1028
|
+
const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
|
|
1029
|
+
const r = await this.req("GET", this.bankUrl(`/documents${q}`));
|
|
1030
|
+
const j = await r.json();
|
|
1031
|
+
const items = j.items ?? [];
|
|
1032
|
+
const hit = items.find((it) => it.id === documentId);
|
|
1033
|
+
if (hit) return hit.tags ?? [];
|
|
1034
|
+
if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
/** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
|
|
1038
|
+
* yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
|
|
1039
|
+
async hasDocuments() {
|
|
1040
|
+
const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
|
|
1041
|
+
if (r.status === 404) return false;
|
|
1042
|
+
const j = await r.json();
|
|
1043
|
+
return (j.total ?? j.items?.length ?? 0) > 0;
|
|
1044
|
+
}
|
|
918
1045
|
/** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
|
|
919
1046
|
* entity labels), then seed knowledge pages when the server supports them. Both halves are
|
|
920
1047
|
* idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
|
|
@@ -936,7 +1063,8 @@ var HindsightClient = class {
|
|
|
936
1063
|
} else {
|
|
937
1064
|
const manifest = codingBankManifest(
|
|
938
1065
|
opts.reset ? void 0 : await this.readBankOverrides(),
|
|
939
|
-
opts.extractionMode
|
|
1066
|
+
opts.extractionMode,
|
|
1067
|
+
opts.defaults
|
|
940
1068
|
);
|
|
941
1069
|
if (!manifest) {
|
|
942
1070
|
this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
|
|
@@ -995,7 +1123,13 @@ var HindsightClient = class {
|
|
|
995
1123
|
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
996
1124
|
const start = Date.now();
|
|
997
1125
|
const pending = new Set(ids);
|
|
1126
|
+
const serverErrors = /* @__PURE__ */ new Map();
|
|
998
1127
|
let failed = 0;
|
|
1128
|
+
const giveUp = (id, status) => {
|
|
1129
|
+
pending.delete(id);
|
|
1130
|
+
failed++;
|
|
1131
|
+
this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
|
|
1132
|
+
};
|
|
999
1133
|
while (pending.size && Date.now() - start < maxMs) {
|
|
1000
1134
|
let backoffMs = POLL_CYCLE_MS;
|
|
1001
1135
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
@@ -1008,7 +1142,14 @@ var HindsightClient = class {
|
|
|
1008
1142
|
);
|
|
1009
1143
|
return;
|
|
1010
1144
|
}
|
|
1011
|
-
if (
|
|
1145
|
+
if (r.status >= 500) {
|
|
1146
|
+
const n = (serverErrors.get(id) ?? 0) + 1;
|
|
1147
|
+
serverErrors.set(id, n);
|
|
1148
|
+
if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
if (!r.ok) return giveUp(id, r.status);
|
|
1152
|
+
serverErrors.delete(id);
|
|
1012
1153
|
const st = ((await r.json()).status || "").toLowerCase();
|
|
1013
1154
|
if (TERMINAL.has(st)) {
|
|
1014
1155
|
pending.delete(id);
|
|
@@ -1142,8 +1283,8 @@ var HindsightClient = class {
|
|
|
1142
1283
|
return { items };
|
|
1143
1284
|
}
|
|
1144
1285
|
/**
|
|
1145
|
-
* Read one knowledge page's synthesized content by knowledge-base id,
|
|
1146
|
-
*
|
|
1286
|
+
* Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
|
|
1287
|
+
* the body arrives once. The endpoint omits the internal reflect trace that built
|
|
1147
1288
|
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
1148
1289
|
* token cap.
|
|
1149
1290
|
*/
|
|
@@ -1154,7 +1295,7 @@ var HindsightClient = class {
|
|
|
1154
1295
|
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
1155
1296
|
);
|
|
1156
1297
|
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
1157
|
-
return await r.json();
|
|
1298
|
+
return shapePage(await r.json());
|
|
1158
1299
|
}
|
|
1159
1300
|
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
1160
1301
|
* Returns page-level hits with a relevance snippet — the real search behind
|
|
@@ -1175,6 +1316,7 @@ var HindsightClient = class {
|
|
|
1175
1316
|
return (j.results ?? []).map((x) => ({
|
|
1176
1317
|
id: x.id,
|
|
1177
1318
|
name: x.name,
|
|
1319
|
+
...x.source_query ? { source_query: x.source_query } : {},
|
|
1178
1320
|
snippet: x.snippet ?? "",
|
|
1179
1321
|
score: x.score ?? 0
|
|
1180
1322
|
}));
|
|
@@ -1191,7 +1333,7 @@ var HindsightClient = class {
|
|
|
1191
1333
|
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
1192
1334
|
*/
|
|
1193
1335
|
async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
|
|
1194
|
-
const pages = pagesFor(this.project
|
|
1336
|
+
const pages = pagesFor(this.project, pagesConfig, customPages);
|
|
1195
1337
|
const existing = /* @__PURE__ */ new Map();
|
|
1196
1338
|
let roots;
|
|
1197
1339
|
try {
|
|
@@ -1266,7 +1408,7 @@ var HindsightClient = class {
|
|
|
1266
1408
|
}
|
|
1267
1409
|
const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
|
|
1268
1410
|
this.log(
|
|
1269
|
-
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ??
|
|
1411
|
+
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
|
|
1270
1412
|
);
|
|
1271
1413
|
}
|
|
1272
1414
|
/**
|
|
@@ -1277,23 +1419,33 @@ var HindsightClient = class {
|
|
|
1277
1419
|
* it: five taxonomy pages against one page per initiative, each an LLM synthesis per
|
|
1278
1420
|
* consolidation under the auto-refresh that used to be the default (#3506).
|
|
1279
1421
|
*
|
|
1280
|
-
*
|
|
1281
|
-
*
|
|
1282
|
-
*
|
|
1422
|
+
* Their `name` and `source_query` are written once, from the initiative's own title, and
|
|
1423
|
+
* re-stating either would rebuild a page whose question never changed. The one exception is
|
|
1424
|
+
* the scope clause: a page captured while the clause named the BANK is scoped to a project no
|
|
1425
|
+
* memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
|
|
1426
|
+
* one — the rest of the query, the user's wording included, is kept. The tree read above is
|
|
1427
|
+
* reused rather than re-fetched.
|
|
1283
1428
|
*/
|
|
1284
1429
|
async resyncInitiativeTriggers(roots, pageTrigger) {
|
|
1285
1430
|
const folder = roots.find(
|
|
1286
1431
|
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
|
|
1287
1432
|
);
|
|
1433
|
+
const bankScope = pageScopeRule(this.bank);
|
|
1288
1434
|
let updated = 0;
|
|
1289
1435
|
for (const page of folder?.children ?? []) {
|
|
1290
|
-
if (page.kind !== "page"
|
|
1291
|
-
const
|
|
1292
|
-
|
|
1436
|
+
if (page.kind !== "page") continue;
|
|
1437
|
+
const patch = {};
|
|
1438
|
+
const query = page.description?.replace(bankScope, pageScopeRule(this.project));
|
|
1439
|
+
if (query !== page.description) patch.source_query = query;
|
|
1440
|
+
if (page.trigger != null) {
|
|
1441
|
+
const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
|
|
1442
|
+
if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
|
|
1443
|
+
}
|
|
1444
|
+
if (!patch.trigger && !patch.source_query) continue;
|
|
1293
1445
|
const r = await this.req(
|
|
1294
1446
|
"PATCH",
|
|
1295
1447
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
|
|
1296
|
-
|
|
1448
|
+
patch
|
|
1297
1449
|
);
|
|
1298
1450
|
if (r.status === 404) continue;
|
|
1299
1451
|
updated++;
|
|
@@ -1321,10 +1473,9 @@ var HindsightClient = class {
|
|
|
1321
1473
|
let pageId = args.relatesToPageId;
|
|
1322
1474
|
if (!pageId) {
|
|
1323
1475
|
const folderId = await this.ensureFolder("Initiatives");
|
|
1324
|
-
const subject = this.project ?? this.bank;
|
|
1325
1476
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
1326
1477
|
name: args.title,
|
|
1327
|
-
source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(
|
|
1478
|
+
source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
|
|
1328
1479
|
parent_id: folderId,
|
|
1329
1480
|
tags: ["knowledge:feature-work"],
|
|
1330
1481
|
max_tokens: PAGE_MAX_TOKENS,
|
|
@@ -1339,7 +1490,7 @@ var HindsightClient = class {
|
|
|
1339
1490
|
}
|
|
1340
1491
|
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
1341
1492
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
1342
|
-
const markerId = `initiative-marker-${this.slugify(
|
|
1493
|
+
const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
|
|
1343
1494
|
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
1344
1495
|
const context = `initiative marker for [[page:${pageId}]]`;
|
|
1345
1496
|
await this.retain(content, context, markerId, tags, "document", {
|
|
@@ -1445,6 +1596,7 @@ function resolveCustomPages(raw) {
|
|
|
1445
1596
|
}
|
|
1446
1597
|
var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
|
|
1447
1598
|
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
1599
|
+
var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
|
|
1448
1600
|
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
1449
1601
|
function resolveReflectBudget(raw) {
|
|
1450
1602
|
const value = raw.reflectBudget;
|
|
@@ -1471,6 +1623,22 @@ function resolveObservationScopes(raw) {
|
|
|
1471
1623
|
}
|
|
1472
1624
|
return DEFAULT_OBSERVATION_SCOPES;
|
|
1473
1625
|
}
|
|
1626
|
+
function resolveDefaultBankConfig(raw) {
|
|
1627
|
+
const value = raw;
|
|
1628
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
1629
|
+
const out = {};
|
|
1630
|
+
for (const [key, v] of Object.entries(value)) {
|
|
1631
|
+
if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
|
|
1632
|
+
log.warn(
|
|
1633
|
+
"config",
|
|
1634
|
+
`ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
|
|
1635
|
+
);
|
|
1636
|
+
continue;
|
|
1637
|
+
}
|
|
1638
|
+
out[key] = v;
|
|
1639
|
+
}
|
|
1640
|
+
return out;
|
|
1641
|
+
}
|
|
1474
1642
|
var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
|
|
1475
1643
|
function resolveAutoInject(raw) {
|
|
1476
1644
|
if (raw.autoReflect !== void 0) {
|
|
@@ -1510,18 +1678,21 @@ function resolveConfig(raw = {}) {
|
|
|
1510
1678
|
// write sessions back by default, every harness
|
|
1511
1679
|
manageBankConfig: raw.manageBankConfig ?? true,
|
|
1512
1680
|
retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
|
|
1681
|
+
defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
|
|
1513
1682
|
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
1514
1683
|
reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
|
|
1515
1684
|
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
1516
1685
|
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
1517
1686
|
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
1518
1687
|
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
1688
|
+
injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
|
|
1519
1689
|
reflectBudget: resolveReflectBudget(raw),
|
|
1520
1690
|
autoInject: resolveAutoInject(raw),
|
|
1521
1691
|
pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
|
|
1522
1692
|
// Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
|
|
1523
1693
|
// keys and reach the API as garbage, so it is rejected like any other non-object.
|
|
1524
1694
|
recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
|
|
1695
|
+
toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
|
|
1525
1696
|
// Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
|
|
1526
1697
|
// at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
|
|
1527
1698
|
// 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
|
|
@@ -1541,18 +1712,22 @@ function resolveConfig(raw = {}) {
|
|
|
1541
1712
|
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
1542
1713
|
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
1543
1714
|
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
1715
|
+
// Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
|
|
1716
|
+
// the built-in default) from a configured value, and an empty context would strip the default.
|
|
1717
|
+
retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
|
|
1544
1718
|
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
1545
1719
|
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
1546
1720
|
) : {},
|
|
1547
1721
|
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
1548
1722
|
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
1723
|
+
paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
|
|
1549
1724
|
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
|
|
1550
1725
|
autoUpdate: raw.autoUpdate ?? true
|
|
1551
1726
|
};
|
|
1552
1727
|
}
|
|
1553
1728
|
function readRaw(path) {
|
|
1554
1729
|
try {
|
|
1555
|
-
return JSON.parse(
|
|
1730
|
+
return JSON.parse(readFileSync3(path, "utf8"));
|
|
1556
1731
|
} catch (e) {
|
|
1557
1732
|
if (e?.code !== "ENOENT") {
|
|
1558
1733
|
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
@@ -1562,7 +1737,12 @@ function readRaw(path) {
|
|
|
1562
1737
|
}
|
|
1563
1738
|
function mergeRaw(a, b) {
|
|
1564
1739
|
const { harnesses: _drop, ...flat } = b;
|
|
1565
|
-
return {
|
|
1740
|
+
return {
|
|
1741
|
+
...a,
|
|
1742
|
+
...flat,
|
|
1743
|
+
banks: { ...a.banks ?? {}, ...b.banks ?? {} },
|
|
1744
|
+
paths: { ...a.paths ?? {}, ...b.paths ?? {} }
|
|
1745
|
+
};
|
|
1566
1746
|
}
|
|
1567
1747
|
function applyLayer(raw, layer, harness) {
|
|
1568
1748
|
let out = mergeRaw(raw, layer);
|
|
@@ -1593,9 +1773,11 @@ var ENV_KEYS = {
|
|
|
1593
1773
|
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1594
1774
|
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1595
1775
|
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1776
|
+
injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
|
|
1596
1777
|
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1597
1778
|
autoInject: "HINDSIGHT_AUTO_INJECT",
|
|
1598
1779
|
pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
|
|
1780
|
+
toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
|
|
1599
1781
|
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1600
1782
|
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1601
1783
|
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
@@ -1637,6 +1819,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
|
1637
1819
|
"maxParallelRetains",
|
|
1638
1820
|
"reflectTimeoutMs",
|
|
1639
1821
|
"reflectToolTimeoutMs",
|
|
1822
|
+
"injectTimeoutMs",
|
|
1640
1823
|
"pageSearchLimit",
|
|
1641
1824
|
"pageRefreshEveryTurns",
|
|
1642
1825
|
"seedLimit",
|
|
@@ -1685,15 +1868,25 @@ var BANK_OVERRIDE_EXCLUDED = [
|
|
|
1685
1868
|
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1686
1869
|
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1687
1870
|
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1871
|
+
const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
|
|
1872
|
+
if (byPath) {
|
|
1873
|
+
const { bank: _rename, ...rest } = overrideFields(byPath);
|
|
1874
|
+
cfg = { ...cfg, ...resolvePartial(cfg, rest) };
|
|
1875
|
+
}
|
|
1688
1876
|
const section = cfg.banks[resolvedId];
|
|
1689
1877
|
if (!section) return { cfg, bankId: resolvedId };
|
|
1690
|
-
const safe =
|
|
1691
|
-
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1692
|
-
delete safe.banks;
|
|
1878
|
+
const safe = overrideFields(section);
|
|
1693
1879
|
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1694
1880
|
delete safe.bank;
|
|
1695
1881
|
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1696
1882
|
}
|
|
1883
|
+
function overrideFields(section) {
|
|
1884
|
+
const safe = { ...section };
|
|
1885
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1886
|
+
delete safe.banks;
|
|
1887
|
+
delete safe.paths;
|
|
1888
|
+
return safe;
|
|
1889
|
+
}
|
|
1697
1890
|
function resolvePartial(cfg, patch) {
|
|
1698
1891
|
const full = resolveConfig(patch);
|
|
1699
1892
|
const out = {};
|
|
@@ -1702,6 +1895,16 @@ function resolvePartial(cfg, patch) {
|
|
|
1702
1895
|
out[key] = full[key];
|
|
1703
1896
|
}
|
|
1704
1897
|
if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
|
|
1898
|
+
if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
|
|
1899
|
+
const conn = resolveConfig({
|
|
1900
|
+
serverMode: patch.serverMode ?? cfg.serverMode,
|
|
1901
|
+
apiPort: patch.apiPort ?? cfg.apiPort,
|
|
1902
|
+
apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
|
|
1903
|
+
});
|
|
1904
|
+
out.serverMode = conn.serverMode;
|
|
1905
|
+
out.apiUrl = conn.apiUrl;
|
|
1906
|
+
out.apiPort = conn.apiPort;
|
|
1907
|
+
}
|
|
1705
1908
|
return out;
|
|
1706
1909
|
}
|
|
1707
1910
|
|
|
@@ -1711,10 +1914,12 @@ function resolveHostConfig(harness, directory) {
|
|
|
1711
1914
|
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
1712
1915
|
const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
|
|
1713
1916
|
if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
|
|
1714
|
-
|
|
1917
|
+
const resolved2 = applyBankConfig(cfg0, bankId, directory);
|
|
1918
|
+
const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
|
|
1919
|
+
return { ...resolved2, project };
|
|
1715
1920
|
}
|
|
1716
1921
|
function resolveHostMemory(harness, directory) {
|
|
1717
|
-
const { cfg, bankId } = resolveHostConfig(harness, directory);
|
|
1922
|
+
const { cfg, bankId, project } = resolveHostConfig(harness, directory);
|
|
1718
1923
|
return {
|
|
1719
1924
|
cfg,
|
|
1720
1925
|
bankId,
|
|
@@ -1722,6 +1927,8 @@ function resolveHostMemory(harness, directory) {
|
|
|
1722
1927
|
apiUrl: cfg.apiUrl,
|
|
1723
1928
|
apiToken: cfg.apiToken,
|
|
1724
1929
|
bank: bankId,
|
|
1930
|
+
// Names the repo in the initiative pages this host captures, as the seeded pages do.
|
|
1931
|
+
project,
|
|
1725
1932
|
maxParallelRetains: cfg.maxParallelRetains,
|
|
1726
1933
|
observationScopes: cfg.observationScopes,
|
|
1727
1934
|
pageSearchLimit: cfg.pageSearchLimit,
|
|
@@ -1730,7 +1937,12 @@ function resolveHostMemory(harness, directory) {
|
|
|
1730
1937
|
// rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
|
|
1731
1938
|
// through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
|
|
1732
1939
|
// honoured on re-resolution exactly as it was on the first one.
|
|
1733
|
-
|
|
1940
|
+
// The URL stays the one this client was built with, so a token re-read after the config
|
|
1941
|
+
// moved this directory to ANOTHER server is that server's credential: never send it here.
|
|
1942
|
+
tokenProvider: () => {
|
|
1943
|
+
const live = resolveHostConfig(harness, directory).cfg;
|
|
1944
|
+
return live.apiUrl === cfg.apiUrl ? live.apiToken : cfg.apiToken;
|
|
1945
|
+
}
|
|
1734
1946
|
})
|
|
1735
1947
|
};
|
|
1736
1948
|
}
|
|
@@ -1740,7 +1952,7 @@ import { spawn as realSpawn2 } from "child_process";
|
|
|
1740
1952
|
import {
|
|
1741
1953
|
existsSync as existsSync2,
|
|
1742
1954
|
mkdirSync as mkdirSync2,
|
|
1743
|
-
readFileSync as
|
|
1955
|
+
readFileSync as readFileSync4,
|
|
1744
1956
|
realpathSync as realpathSync2,
|
|
1745
1957
|
unlinkSync,
|
|
1746
1958
|
writeFileSync
|
|
@@ -1771,7 +1983,7 @@ function sameDir(a, b) {
|
|
|
1771
1983
|
}
|
|
1772
1984
|
function stagedVersion(pkgRoot) {
|
|
1773
1985
|
try {
|
|
1774
|
-
const pkg = JSON.parse(
|
|
1986
|
+
const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
|
|
1775
1987
|
return typeof pkg.version === "string" ? pkg.version : "";
|
|
1776
1988
|
} catch {
|
|
1777
1989
|
return "";
|
|
@@ -1796,7 +2008,7 @@ function isNewer(candidate, current2) {
|
|
|
1796
2008
|
}
|
|
1797
2009
|
function dueForCheck(file3, now) {
|
|
1798
2010
|
try {
|
|
1799
|
-
const state = JSON.parse(
|
|
2011
|
+
const state = JSON.parse(readFileSync4(file3, "utf8"));
|
|
1800
2012
|
return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
|
|
1801
2013
|
} catch {
|
|
1802
2014
|
return true;
|
|
@@ -1805,7 +2017,7 @@ function dueForCheck(file3, now) {
|
|
|
1805
2017
|
var ORIGIN_FILE = ".install-origin.json";
|
|
1806
2018
|
function selfUpdatable(runtimeDir) {
|
|
1807
2019
|
try {
|
|
1808
|
-
const origin = JSON.parse(
|
|
2020
|
+
const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
|
|
1809
2021
|
if (typeof origin.source !== "string" || !origin.source) return false;
|
|
1810
2022
|
return origin.source.split(/[\\/]/).includes("_npx");
|
|
1811
2023
|
} catch {
|
|
@@ -1818,7 +2030,7 @@ function lockFile() {
|
|
|
1818
2030
|
}
|
|
1819
2031
|
function acquireUpdateLock(file3, now) {
|
|
1820
2032
|
try {
|
|
1821
|
-
const held = JSON.parse(
|
|
2033
|
+
const held = JSON.parse(readFileSync4(file3, "utf8"));
|
|
1822
2034
|
if (held.ts && now - held.ts < LOCK_STALE_MS) {
|
|
1823
2035
|
let holderAlive = false;
|
|
1824
2036
|
if (held.pid) {
|
|
@@ -1859,6 +2071,9 @@ function stampCheck(file3, now, latest) {
|
|
|
1859
2071
|
} catch {
|
|
1860
2072
|
}
|
|
1861
2073
|
}
|
|
2074
|
+
function spawnNpm(spawnImpl, bin, args, opts) {
|
|
2075
|
+
return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
|
|
2076
|
+
}
|
|
1862
2077
|
async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
|
|
1863
2078
|
return new Promise((resolve3) => {
|
|
1864
2079
|
let out = "";
|
|
@@ -1872,7 +2087,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
|
|
|
1872
2087
|
resolve3(v);
|
|
1873
2088
|
};
|
|
1874
2089
|
try {
|
|
1875
|
-
const child = spawnImpl
|
|
2090
|
+
const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
|
|
1876
2091
|
timeout: NPM_VIEW_TIMEOUT_MS,
|
|
1877
2092
|
stdio: ["ignore", "pipe", "ignore"],
|
|
1878
2093
|
windowsHide: true
|
|
@@ -1941,7 +2156,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
|
|
|
1941
2156
|
return "";
|
|
1942
2157
|
}
|
|
1943
2158
|
log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
|
|
1944
|
-
const child = (
|
|
2159
|
+
const child = spawnNpm(
|
|
2160
|
+
opts.spawn ?? realSpawn2,
|
|
1945
2161
|
"npx",
|
|
1946
2162
|
["-y", `${PACKAGE_NAME}@${latest}`, "update"],
|
|
1947
2163
|
{
|
|
@@ -1974,7 +2190,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
|
1974
2190
|
var DAEMON_WAIT_RETAIN_MS = 4e4;
|
|
1975
2191
|
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
1976
2192
|
try {
|
|
1977
|
-
const res = await fetch(`${baseUrl}/health`, {
|
|
2193
|
+
const res = await fetch(`${baseUrl}/health`, {
|
|
2194
|
+
headers: { "User-Agent": USER_AGENT },
|
|
2195
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
2196
|
+
});
|
|
1978
2197
|
return res.ok;
|
|
1979
2198
|
} catch {
|
|
1980
2199
|
return false;
|
|
@@ -2056,12 +2275,46 @@ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
|
|
|
2056
2275
|
} catch {
|
|
2057
2276
|
}
|
|
2058
2277
|
}
|
|
2278
|
+
var coldStarts = /* @__PURE__ */ new Map();
|
|
2279
|
+
async function waitBounded(p, ms) {
|
|
2280
|
+
let timer;
|
|
2281
|
+
try {
|
|
2282
|
+
await Promise.race([
|
|
2283
|
+
p,
|
|
2284
|
+
new Promise((resolve3) => {
|
|
2285
|
+
timer = setTimeout(resolve3, Math.max(ms, 0));
|
|
2286
|
+
})
|
|
2287
|
+
]);
|
|
2288
|
+
} finally {
|
|
2289
|
+
clearTimeout(timer);
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2059
2292
|
async function ensureDaemon(cfg, harness, opts = {}) {
|
|
2060
2293
|
if (cfg.serverMode !== "daemon") return;
|
|
2061
2294
|
if (await isServerHealthy(cfg.apiUrl)) return;
|
|
2062
2295
|
if (!preflightDaemon(cfg, harness)) return;
|
|
2063
|
-
|
|
2064
|
-
|
|
2296
|
+
const waitMs = opts.waitMs ?? 0;
|
|
2297
|
+
const running = coldStarts.get(cfg.apiUrl);
|
|
2298
|
+
if (running) {
|
|
2299
|
+
const startedAt = Date.now();
|
|
2300
|
+
await waitBounded(
|
|
2301
|
+
running.catch(() => void 0),
|
|
2302
|
+
waitMs
|
|
2303
|
+
);
|
|
2304
|
+
const remaining = waitMs - (Date.now() - startedAt);
|
|
2305
|
+
if (remaining > 0) await waitForHealth(cfg.apiUrl, remaining);
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
const attempt = (async () => {
|
|
2309
|
+
startDaemonDetached(cfg, harness, opts.spawnFn);
|
|
2310
|
+
await waitForHealth(cfg.apiUrl, waitMs);
|
|
2311
|
+
})();
|
|
2312
|
+
coldStarts.set(cfg.apiUrl, attempt);
|
|
2313
|
+
try {
|
|
2314
|
+
await attempt;
|
|
2315
|
+
} finally {
|
|
2316
|
+
if (coldStarts.get(cfg.apiUrl) === attempt) coldStarts.delete(cfg.apiUrl);
|
|
2317
|
+
}
|
|
2065
2318
|
}
|
|
2066
2319
|
async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
|
|
2067
2320
|
const deadline = Date.now() + budgetMs;
|
|
@@ -2113,13 +2366,13 @@ function indexLine(pages) {
|
|
|
2113
2366
|
const count = pages.length === 1 ? "1 knowledge page covers" : `${pages.length} knowledge pages cover`;
|
|
2114
2367
|
return `${count} this repository \u2014 architecture, conventions, past decisions and in-flight initiatives. They are deliberately NOT listed here: call hindsight_search_knowledge_pages(query) to find the ones that bear on the current turn, then hindsight_read_knowledge_page(<id>) on anything the results show is worth reading in full.`;
|
|
2115
2368
|
}
|
|
2116
|
-
var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today
|
|
2117
|
-
\u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return,
|
|
2369
|
+
var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, and the way IN to everything below. The code shows what is true today but not what was decided or why; memory shows what was decided or said back then but not whether it still holds. Work built from either alone goes wrong: from code alone it quietly re-litigates settled questions, from memory alone it acts on stale claims. Search BEFORE you act whenever the turn is one of these \u2014 they are the ones that go wrong silently:
|
|
2370
|
+
\u2022 the user reports a bug or a wrong response (the intended behaviour, and the status code or value it should return, may already have been decided);
|
|
2118
2371
|
\u2022 you are about to write or change a test (what this project expects a change to ship with, and how it asserts, is a convention, not a preference);
|
|
2119
2372
|
\u2022 you are implementing something new, or two parts have to fit together;
|
|
2120
2373
|
\u2022 the user asks why something is the way it is, or what is left to do;
|
|
2121
2374
|
\u2022 you are about to commit, and need to know what the change was supposed to honour.
|
|
2122
|
-
It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you.
|
|
2375
|
+
It ranks the pages by relevance and returns the matching passage, which a page title cannot tell you. What it returns is a past record, not a live reading: a claim that something was fixed, passes, or works is what someone said then \u2014 check it against the code before you rely on it, and say so when the two disagree.
|
|
2123
2376
|
CREDITING IS NOT OPTIONAL AND NOT A JUDGEMENT CALL. If you called this tool and anything it returned reached your reply \u2014 quoted, paraphrased, or merely confirming what you were about to say \u2014 open that part with a markdown blockquote, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. A search that turned up nothing useful needs no mention at all \u2014 just carry on.
|
|
2124
2377
|
- hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
|
|
2125
2378
|
- hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
|
|
@@ -2127,7 +2380,9 @@ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP, a
|
|
|
2127
2380
|
- hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
|
|
2128
2381
|
var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
|
|
2129
2382
|
function toolGuide(opts) {
|
|
2130
|
-
|
|
2383
|
+
const extra = opts?.extra?.trim();
|
|
2384
|
+
return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE + (extra ? `
|
|
2385
|
+
${extra}` : "");
|
|
2131
2386
|
}
|
|
2132
2387
|
function buildKnowledgePreamble(pages, opts) {
|
|
2133
2388
|
const body = pages.length ? indexLine(pages) : EMPTY_STATE;
|
|
@@ -2666,7 +2921,7 @@ __export(core_exports2, {
|
|
|
2666
2921
|
toJSONSchema: () => toJSONSchema,
|
|
2667
2922
|
treeifyError: () => treeifyError,
|
|
2668
2923
|
util: () => util_exports,
|
|
2669
|
-
version: () =>
|
|
2924
|
+
version: () => version2
|
|
2670
2925
|
});
|
|
2671
2926
|
|
|
2672
2927
|
// node_modules/zod/v4/core/core.js
|
|
@@ -3741,10 +3996,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
3741
3996
|
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
3742
3997
|
var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
|
3743
3998
|
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
3744
|
-
var uuid = (
|
|
3745
|
-
if (!
|
|
3999
|
+
var uuid = (version4) => {
|
|
4000
|
+
if (!version4)
|
|
3746
4001
|
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
|
|
3747
|
-
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${
|
|
4002
|
+
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
3748
4003
|
};
|
|
3749
4004
|
var uuid4 = /* @__PURE__ */ uuid(4);
|
|
3750
4005
|
var uuid6 = /* @__PURE__ */ uuid(6);
|
|
@@ -4413,7 +4668,7 @@ var Doc = class {
|
|
|
4413
4668
|
};
|
|
4414
4669
|
|
|
4415
4670
|
// node_modules/zod/v4/core/versions.js
|
|
4416
|
-
var
|
|
4671
|
+
var version2 = {
|
|
4417
4672
|
major: 4,
|
|
4418
4673
|
minor: 4,
|
|
4419
4674
|
patch: 3
|
|
@@ -4425,7 +4680,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
|
|
|
4425
4680
|
inst ?? (inst = {});
|
|
4426
4681
|
inst._zod.def = def;
|
|
4427
4682
|
inst._zod.bag = inst._zod.bag || {};
|
|
4428
|
-
inst._zod.version =
|
|
4683
|
+
inst._zod.version = version2;
|
|
4429
4684
|
const checks = [...inst._zod.def.checks ?? []];
|
|
4430
4685
|
if (inst._zod.traits.has("$ZodCheck")) {
|
|
4431
4686
|
checks.unshift(inst);
|
|
@@ -16620,10 +16875,10 @@ function fromJSONSchema(schema, params) {
|
|
|
16620
16875
|
} catch {
|
|
16621
16876
|
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
|
|
16622
16877
|
}
|
|
16623
|
-
const
|
|
16878
|
+
const version4 = detectVersion(normalized, params?.defaultTarget);
|
|
16624
16879
|
const defs = normalized.$defs || normalized.definitions || {};
|
|
16625
16880
|
const ctx = {
|
|
16626
|
-
version:
|
|
16881
|
+
version: version4,
|
|
16627
16882
|
defs,
|
|
16628
16883
|
refs: /* @__PURE__ */ new Map(),
|
|
16629
16884
|
processing: /* @__PURE__ */ new Set(),
|
|
@@ -16668,13 +16923,14 @@ import { homedir as homedir6 } from "os";
|
|
|
16668
16923
|
import { join as join12 } from "path";
|
|
16669
16924
|
|
|
16670
16925
|
// src/core/status.ts
|
|
16671
|
-
import { execFileSync as
|
|
16926
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
16672
16927
|
|
|
16673
16928
|
// src/core/git.ts
|
|
16674
16929
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
16675
16930
|
import { resolve as resolve2 } from "path";
|
|
16931
|
+
var GITLOG_HEAD = "gitlog-head:";
|
|
16676
16932
|
function git(repo, ...args) {
|
|
16677
|
-
return execFileSync2("git", ["-C", repo, ...args], {
|
|
16933
|
+
return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
|
|
16678
16934
|
encoding: "utf8",
|
|
16679
16935
|
maxBuffer: 1 << 28,
|
|
16680
16936
|
windowsHide: true,
|
|
@@ -16694,6 +16950,7 @@ function gitHeadSha(dir) {
|
|
|
16694
16950
|
}
|
|
16695
16951
|
}
|
|
16696
16952
|
function commitsSince(dir, sinceSha) {
|
|
16953
|
+
if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
|
|
16697
16954
|
try {
|
|
16698
16955
|
const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
|
|
16699
16956
|
return Number.isFinite(n) ? n : null;
|
|
@@ -16708,9 +16965,18 @@ function hasGitHistory(dir) {
|
|
|
16708
16965
|
return false;
|
|
16709
16966
|
}
|
|
16710
16967
|
}
|
|
16968
|
+
async function gitLogIsCurrent(client, repo, head) {
|
|
16969
|
+
const canonical2 = `gitlog:${repoNameOf(repo)}`;
|
|
16970
|
+
if ((await client.listDocumentIds(`${GITLOG_HEAD}${head}`, "all_strict")).has(canonical2))
|
|
16971
|
+
return true;
|
|
16972
|
+
const tags = await client.documentTags?.(canonical2) ?? [];
|
|
16973
|
+
return tags.some(
|
|
16974
|
+
(tag) => tag.startsWith(GITLOG_HEAD) && commitsSince(repo, tag.slice(GITLOG_HEAD.length)) === 0
|
|
16975
|
+
);
|
|
16976
|
+
}
|
|
16711
16977
|
|
|
16712
16978
|
// src/core/survey.ts
|
|
16713
|
-
import { spawn as realSpawn5 } from "child_process";
|
|
16979
|
+
import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
|
|
16714
16980
|
import { createHash as createHash2 } from "crypto";
|
|
16715
16981
|
import { existsSync as existsSync3 } from "fs";
|
|
16716
16982
|
import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
|
|
@@ -16830,6 +17096,19 @@ function resolveAgentBin(harness, claudeBin) {
|
|
|
16830
17096
|
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
16831
17097
|
}
|
|
16832
17098
|
}
|
|
17099
|
+
function opencodeCanDefineSurveyAgent(bin) {
|
|
17100
|
+
try {
|
|
17101
|
+
const out = execFileSync3(bin, ["--version"], {
|
|
17102
|
+
encoding: "utf8",
|
|
17103
|
+
timeout: 5e3,
|
|
17104
|
+
windowsHide: true,
|
|
17105
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
17106
|
+
});
|
|
17107
|
+
return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
|
|
17108
|
+
} catch {
|
|
17109
|
+
return false;
|
|
17110
|
+
}
|
|
17111
|
+
}
|
|
16833
17112
|
var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
|
|
16834
17113
|
var SURVEY_DISALLOWED_TOOLS = [
|
|
16835
17114
|
"Bash",
|
|
@@ -16943,6 +17222,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
16943
17222
|
seen.add(harness);
|
|
16944
17223
|
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
16945
17224
|
if (!exists(bin)) continue;
|
|
17225
|
+
if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
|
|
17226
|
+
continue;
|
|
16946
17227
|
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
16947
17228
|
model: opts.model,
|
|
16948
17229
|
budgetUsd: opts.budgetUsd,
|
|
@@ -16999,7 +17280,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
16999
17280
|
var DEEPEN_DIFF_TARGET = 300;
|
|
17000
17281
|
function commitCount(repoDir) {
|
|
17001
17282
|
try {
|
|
17002
|
-
const out =
|
|
17283
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
17003
17284
|
encoding: "utf8",
|
|
17004
17285
|
windowsHide: true,
|
|
17005
17286
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17070,19 +17351,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
|
17070
17351
|
idempotentHint: false,
|
|
17071
17352
|
openWorldHint: false
|
|
17072
17353
|
};
|
|
17073
|
-
var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention.';
|
|
17074
|
-
function shapePage(page) {
|
|
17075
|
-
const p = page ?? {};
|
|
17076
|
-
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
17077
|
-
return {
|
|
17078
|
-
id: p.id,
|
|
17079
|
-
name: p.name,
|
|
17080
|
-
...p.description ? { description: p.description } : {},
|
|
17081
|
-
...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
|
|
17082
|
-
...p.timestamp ? { last_updated_at: p.timestamp } : {},
|
|
17083
|
-
body
|
|
17084
|
-
};
|
|
17085
|
-
}
|
|
17354
|
+
var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention. These are past records: check a claim that something was fixed or works against the code before relying on it.';
|
|
17086
17355
|
function ok(value) {
|
|
17087
17356
|
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
|
17088
17357
|
}
|
|
@@ -17100,6 +17369,8 @@ function guarded(fn) {
|
|
|
17100
17369
|
};
|
|
17101
17370
|
}
|
|
17102
17371
|
function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
17372
|
+
const extra = opts.toolGuideExtra?.trim();
|
|
17373
|
+
const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
|
|
17103
17374
|
return [
|
|
17104
17375
|
{
|
|
17105
17376
|
name: "hindsight_sync_status",
|
|
@@ -17159,7 +17430,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17159
17430
|
},
|
|
17160
17431
|
{
|
|
17161
17432
|
name: "hindsight_search_knowledge_pages",
|
|
17162
|
-
description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " +
|
|
17433
|
+
description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + crediting,
|
|
17163
17434
|
inputSchema: { query: external_exports.string().describe("what to look for") },
|
|
17164
17435
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
17165
17436
|
handler: async (args) => {
|
|
@@ -17169,9 +17440,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17169
17440
|
pages: hits.map((h) => ({
|
|
17170
17441
|
page: h.name,
|
|
17171
17442
|
page_id: h.id,
|
|
17443
|
+
// The question the page answers — the same `description` the list and read tools
|
|
17444
|
+
// carry, so a hit says what the page is FOR, not just how it opens.
|
|
17445
|
+
...h.source_query ? { description: h.source_query } : {},
|
|
17172
17446
|
snippet: h.snippet
|
|
17173
17447
|
})),
|
|
17174
|
-
crediting
|
|
17448
|
+
crediting
|
|
17175
17449
|
});
|
|
17176
17450
|
} catch (e) {
|
|
17177
17451
|
return err(e);
|
|
@@ -17190,7 +17464,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17190
17464
|
description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
|
|
17191
17465
|
inputSchema: { page_id: external_exports.string() },
|
|
17192
17466
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
17193
|
-
handler: guarded(async ({ page_id }) =>
|
|
17467
|
+
handler: guarded(async ({ page_id }) => client.getPage(page_id))
|
|
17194
17468
|
},
|
|
17195
17469
|
{
|
|
17196
17470
|
name: "hindsight_reflect",
|
|
@@ -17260,12 +17534,18 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17260
17534
|
import { createHash as createHash4 } from "crypto";
|
|
17261
17535
|
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
17262
17536
|
var PENDING_MAX_BYTES = 256 * 1024;
|
|
17537
|
+
var MAX_CURSOR_PATHS = 16;
|
|
17538
|
+
function advancePaths(seen, path) {
|
|
17539
|
+
if (!path) return seen;
|
|
17540
|
+
return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
|
|
17541
|
+
}
|
|
17263
17542
|
function pendingReplayable(cursor, now) {
|
|
17264
17543
|
const pending = cursor.pending ?? [];
|
|
17265
17544
|
if (!pending.length) return true;
|
|
17266
17545
|
if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
|
|
17267
17546
|
return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
|
|
17268
17547
|
}
|
|
17548
|
+
var MAX_CURSOR_OPS = 8;
|
|
17269
17549
|
function fingerprintTurns(turns, count) {
|
|
17270
17550
|
const h = createHash4("sha1").update(String(count));
|
|
17271
17551
|
for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
|
|
@@ -17276,8 +17556,10 @@ function planRetain(turns, cursor, opts) {
|
|
|
17276
17556
|
if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
|
|
17277
17557
|
if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
|
|
17278
17558
|
if (cursor.bank !== opts.bank) return { mode: "replace" };
|
|
17279
|
-
|
|
17280
|
-
|
|
17559
|
+
const seen = cursor.paths ?? [];
|
|
17560
|
+
const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
|
|
17561
|
+
const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
|
|
17562
|
+
if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
|
|
17281
17563
|
if (cursor.turns === turns.length) return { mode: "skip" };
|
|
17282
17564
|
return { mode: "append", fromTurn: cursor.turns };
|
|
17283
17565
|
}
|
|
@@ -17319,11 +17601,36 @@ function renderSessionJsonl(refId, turns, baseTs) {
|
|
|
17319
17601
|
}
|
|
17320
17602
|
async function supportsAppend(client) {
|
|
17321
17603
|
try {
|
|
17322
|
-
return await client.
|
|
17604
|
+
return await client.supportsAppendRetain();
|
|
17323
17605
|
} catch {
|
|
17324
17606
|
return false;
|
|
17325
17607
|
}
|
|
17326
17608
|
}
|
|
17609
|
+
var OP_CHECK_TIMEOUT_MS = 5e3;
|
|
17610
|
+
var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
|
|
17611
|
+
async function settleOps(client, cursor) {
|
|
17612
|
+
const ops = cursor.ops ?? [];
|
|
17613
|
+
const statuses = await Promise.all(
|
|
17614
|
+
ops.map(async (id) => {
|
|
17615
|
+
try {
|
|
17616
|
+
const r = await client.req(
|
|
17617
|
+
"GET",
|
|
17618
|
+
client.bankUrl(`/operations/${encodeURIComponent(id)}`),
|
|
17619
|
+
void 0,
|
|
17620
|
+
[],
|
|
17621
|
+
OP_CHECK_TIMEOUT_MS
|
|
17622
|
+
);
|
|
17623
|
+
if (r.status === 404) return "not_found";
|
|
17624
|
+
return String((await r.json()).status ?? "").toLowerCase();
|
|
17625
|
+
} catch {
|
|
17626
|
+
return "";
|
|
17627
|
+
}
|
|
17628
|
+
})
|
|
17629
|
+
);
|
|
17630
|
+
const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
|
|
17631
|
+
const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
|
|
17632
|
+
return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
|
|
17633
|
+
}
|
|
17327
17634
|
var DEFAULT_RETRY_WINDOW_MS = 6e4;
|
|
17328
17635
|
var RETAIN_RETRY_ATTEMPTS = 2;
|
|
17329
17636
|
var REQUEST_BUDGET_MS = 15e3;
|
|
@@ -17353,6 +17660,7 @@ function serialize(cursors, sessionId, write2) {
|
|
|
17353
17660
|
});
|
|
17354
17661
|
return next;
|
|
17355
17662
|
}
|
|
17663
|
+
var DEFAULT_RETAIN_CONTEXT = `conversation between the user and you (the coding agent): user turns are the user's words and decisions, assistant turns are yours. When an assistant turn says something is fixed, passes or works, record it as the agent's claim ("the agent reported X fixed"), not as an established fact.`;
|
|
17356
17664
|
async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
|
|
17357
17665
|
const cursors = opts.cursors;
|
|
17358
17666
|
if (!cursors)
|
|
@@ -17364,20 +17672,41 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
|
|
|
17364
17672
|
harness,
|
|
17365
17673
|
opts.stamp,
|
|
17366
17674
|
void 0,
|
|
17367
|
-
opts.retryUntil
|
|
17675
|
+
opts.retryUntil,
|
|
17676
|
+
opts.transcriptPath
|
|
17368
17677
|
);
|
|
17369
17678
|
return serialize(
|
|
17370
17679
|
cursors,
|
|
17371
17680
|
sessionId,
|
|
17372
|
-
() => writeSession(
|
|
17681
|
+
() => writeSession(
|
|
17682
|
+
client,
|
|
17683
|
+
sessionId,
|
|
17684
|
+
turns,
|
|
17685
|
+
startTs,
|
|
17686
|
+
harness,
|
|
17687
|
+
opts.stamp,
|
|
17688
|
+
cursors,
|
|
17689
|
+
opts.retryUntil,
|
|
17690
|
+
opts.transcriptPath
|
|
17691
|
+
)
|
|
17373
17692
|
);
|
|
17374
17693
|
}
|
|
17375
|
-
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
|
|
17694
|
+
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
|
|
17376
17695
|
if (!turns.length) return;
|
|
17377
17696
|
const refId = `conversation:${sessionId}`;
|
|
17378
|
-
|
|
17697
|
+
let cursor = cursors?.read(sessionId);
|
|
17698
|
+
const probed = Boolean(cursors) && cursor?.appendSupported !== true;
|
|
17379
17699
|
const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
|
|
17380
|
-
|
|
17700
|
+
let ops = [];
|
|
17701
|
+
if (appendSupported && cursor?.ops?.length && !cursor.dirty)
|
|
17702
|
+
({ cursor, ops } = await settleOps(client, cursor));
|
|
17703
|
+
const plan = planRetain(turns, cursor, {
|
|
17704
|
+
appendSupported,
|
|
17705
|
+
bank: client.bank,
|
|
17706
|
+
path: transcriptPath
|
|
17707
|
+
});
|
|
17708
|
+
if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
|
|
17709
|
+
const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
|
|
17381
17710
|
const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
|
|
17382
17711
|
if (plan.mode === "skip" && !outbox.length) return;
|
|
17383
17712
|
const opId = (mode, content) => uuidV5(`${client.bank}
|
|
@@ -17386,7 +17715,10 @@ ${mode}
|
|
|
17386
17715
|
${content}`);
|
|
17387
17716
|
const submit = (content, operationId, append) => client.retain(
|
|
17388
17717
|
content,
|
|
17389
|
-
|
|
17718
|
+
// Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
|
|
17719
|
+
// default names both speakers: the previous "coding agent session" said nothing about
|
|
17720
|
+
// authorship and let an assistant's proposal be recorded as the user's decision.
|
|
17721
|
+
stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
|
|
17390
17722
|
refId,
|
|
17391
17723
|
// Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
|
|
17392
17724
|
// the documents list filters and draws its agent logo from, so a template cannot displace them.
|
|
@@ -17416,8 +17748,13 @@ ${content}`);
|
|
|
17416
17748
|
turns: turns.length,
|
|
17417
17749
|
fingerprint: fingerprintTurns(turns, turns.length),
|
|
17418
17750
|
bank: client.bank,
|
|
17751
|
+
...paths ? { paths } : {},
|
|
17419
17752
|
...appendSupported ? { appendSupported: true } : {}
|
|
17420
17753
|
};
|
|
17754
|
+
const accepted = (id) => {
|
|
17755
|
+
if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
|
|
17756
|
+
return ops.length ? { ...next, ops } : next;
|
|
17757
|
+
};
|
|
17421
17758
|
const stillOurs = () => {
|
|
17422
17759
|
if (!cursors) return true;
|
|
17423
17760
|
const now = cursors.read(sessionId);
|
|
@@ -17426,12 +17763,10 @@ ${content}`);
|
|
|
17426
17763
|
if (plan.mode === "replace") {
|
|
17427
17764
|
const content = renderSessionJsonl(refId, turns, startTs);
|
|
17428
17765
|
cursors?.write(sessionId, { ...next, dirty: true });
|
|
17429
|
-
|
|
17430
|
-
|
|
17431
|
-
|
|
17432
|
-
|
|
17433
|
-
);
|
|
17434
|
-
cursors?.write(sessionId, next);
|
|
17766
|
+
const operationId = opId("replace", content);
|
|
17767
|
+
await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
|
|
17768
|
+
ops = [];
|
|
17769
|
+
cursors?.write(sessionId, accepted(operationId));
|
|
17435
17770
|
return;
|
|
17436
17771
|
}
|
|
17437
17772
|
const queue = [...outbox];
|
|
@@ -17439,7 +17774,7 @@ ${content}`);
|
|
|
17439
17774
|
const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
|
|
17440
17775
|
queue.push({ content, operationId: opId("append", content), at: Date.now() });
|
|
17441
17776
|
}
|
|
17442
|
-
cursors?.write(sessionId, { ...
|
|
17777
|
+
cursors?.write(sessionId, { ...accepted(), pending: queue });
|
|
17443
17778
|
for (let i = 0; i < queue.length; i++) {
|
|
17444
17779
|
if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
|
|
17445
17780
|
const entry = queue[i];
|
|
@@ -17449,12 +17784,13 @@ ${content}`);
|
|
|
17449
17784
|
retryUntil
|
|
17450
17785
|
);
|
|
17451
17786
|
const remaining = queue.slice(i + 1);
|
|
17452
|
-
|
|
17787
|
+
const done = accepted(entry.operationId);
|
|
17788
|
+
cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
|
|
17453
17789
|
}
|
|
17454
17790
|
}
|
|
17455
17791
|
|
|
17456
17792
|
// src/core/usage.ts
|
|
17457
|
-
import { readFileSync as
|
|
17793
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
17458
17794
|
import { join as join13 } from "path";
|
|
17459
17795
|
function usageFilePath() {
|
|
17460
17796
|
return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
|
|
@@ -17532,7 +17868,8 @@ function resolversFor(ctx) {
|
|
|
17532
17868
|
function buildRetainStamp(cfg, ctx) {
|
|
17533
17869
|
const hasTags = Boolean(cfg.retainTags?.length);
|
|
17534
17870
|
const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
|
|
17535
|
-
|
|
17871
|
+
const hasContext = Boolean(cfg.retainContext?.trim());
|
|
17872
|
+
if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
|
|
17536
17873
|
const base = resolversFor(ctx);
|
|
17537
17874
|
const cache = /* @__PURE__ */ new Map();
|
|
17538
17875
|
const resolvers = Object.fromEntries(
|
|
@@ -17556,19 +17893,19 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
17556
17893
|
for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
|
|
17557
17894
|
metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
|
|
17558
17895
|
}
|
|
17559
|
-
|
|
17896
|
+
const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
|
|
17897
|
+
return { tags, metadata, context };
|
|
17560
17898
|
}
|
|
17561
17899
|
|
|
17562
|
-
// src/core/session-start.ts
|
|
17563
|
-
import { readFileSync as readFileSync8 } from "fs";
|
|
17564
|
-
|
|
17565
17900
|
// src/core/skill-sync.ts
|
|
17566
|
-
import { cpSync, existsSync as
|
|
17901
|
+
import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
17567
17902
|
import { homedir as homedir7 } from "os";
|
|
17568
|
-
import { dirname as dirname8, join as
|
|
17903
|
+
import { dirname as dirname8, join as join15 } from "path";
|
|
17569
17904
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
17570
17905
|
|
|
17571
17906
|
// src/core/skill-dirs.ts
|
|
17907
|
+
import { existsSync as existsSync5 } from "fs";
|
|
17908
|
+
import { join as join14 } from "path";
|
|
17572
17909
|
var SKILL_DIRS = {
|
|
17573
17910
|
"claude-code": [".claude", "skills"],
|
|
17574
17911
|
// Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
|
|
@@ -17581,6 +17918,8 @@ var SKILL_DIRS = {
|
|
|
17581
17918
|
"cline-cli": [".cline", "data", "settings", "skills"],
|
|
17582
17919
|
"qwen-code": [".qwen", "skills"],
|
|
17583
17920
|
// Qwen's user-level skills root (Storage.getUserSkillsDirs)
|
|
17921
|
+
// Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
|
|
17922
|
+
"kimi-code": [".kimi-code", "skills"],
|
|
17584
17923
|
"factory-droid": [".factory", "skills"],
|
|
17585
17924
|
// Droid's user-level skills root
|
|
17586
17925
|
// ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
|
|
@@ -17588,31 +17927,53 @@ var SKILL_DIRS = {
|
|
|
17588
17927
|
// skill removal is by fixed directory name, so installing into the shared root would make
|
|
17589
17928
|
// `uninstall zcode` take Codex's and dsh's copy with it.
|
|
17590
17929
|
zcode: [".zcode", "skills"],
|
|
17930
|
+
// TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
|
|
17931
|
+
// its own, never the shared agentskills root other hosts install into.
|
|
17932
|
+
traecode: [".trae-cn", "skills"],
|
|
17591
17933
|
// The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
|
|
17592
17934
|
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
17593
17935
|
// and dsh's copy with it.
|
|
17594
17936
|
pi: [".pi", "agent", "skills"],
|
|
17595
|
-
"prime-agent": [".prime", "agent", "skills"]
|
|
17937
|
+
"prime-agent": [".prime", "agent", "skills"],
|
|
17938
|
+
// WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
|
|
17939
|
+
workbuddy: [".workbuddy", "skills"],
|
|
17940
|
+
// CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
|
|
17941
|
+
// its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
|
|
17942
|
+
codebuddy: [".codebuddy", "skills"]
|
|
17943
|
+
};
|
|
17944
|
+
var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
|
|
17945
|
+
var traecodeDotDirName = (home, exists = existsSync5) => {
|
|
17946
|
+
for (const dir of TRAE_DOT_DIRS) {
|
|
17947
|
+
if (exists(join14(home, dir))) return dir;
|
|
17948
|
+
}
|
|
17949
|
+
return ".trae-cn";
|
|
17950
|
+
};
|
|
17951
|
+
var resolveSkillDirs = (harness, home) => {
|
|
17952
|
+
const parts = SKILL_DIRS[harness];
|
|
17953
|
+
if (harness === "traecode" && parts) {
|
|
17954
|
+
return [traecodeDotDirName(home), ...parts.slice(1)];
|
|
17955
|
+
}
|
|
17956
|
+
return parts;
|
|
17596
17957
|
};
|
|
17597
17958
|
|
|
17598
17959
|
// src/core/skill-sync.ts
|
|
17599
17960
|
function packagedSkillDir() {
|
|
17600
17961
|
const here = dirname8(fileURLToPath5(import.meta.url));
|
|
17601
|
-
const dist =
|
|
17602
|
-
return
|
|
17962
|
+
const dist = join15(here, "..", "skill");
|
|
17963
|
+
return existsSync6(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
|
|
17603
17964
|
}
|
|
17604
17965
|
function syncCompanionSkill(harness, opts = {}) {
|
|
17605
17966
|
try {
|
|
17606
|
-
const parts =
|
|
17967
|
+
const parts = resolveSkillDirs(harness, opts.home ?? homedir7());
|
|
17607
17968
|
if (!parts) return;
|
|
17608
17969
|
const src = opts.srcDir ?? packagedSkillDir();
|
|
17609
|
-
const srcMd =
|
|
17610
|
-
if (!
|
|
17611
|
-
const dst =
|
|
17612
|
-
const dstMd =
|
|
17613
|
-
const installed =
|
|
17970
|
+
const srcMd = join15(src, "SKILL.md");
|
|
17971
|
+
if (!existsSync6(srcMd)) return;
|
|
17972
|
+
const dst = join15(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
|
|
17973
|
+
const dstMd = join15(dst, "SKILL.md");
|
|
17974
|
+
const installed = existsSync6(dstMd);
|
|
17614
17975
|
if (!installed && !opts.install) return;
|
|
17615
|
-
if (!installed ||
|
|
17976
|
+
if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
|
|
17616
17977
|
cpSync(src, dst, { recursive: true });
|
|
17617
17978
|
}
|
|
17618
17979
|
} catch {
|
|
@@ -17634,15 +17995,15 @@ function brandWord() {
|
|
|
17634
17995
|
}
|
|
17635
17996
|
|
|
17636
17997
|
// src/core/legacy.ts
|
|
17637
|
-
import { existsSync as
|
|
17998
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
|
|
17638
17999
|
import { homedir as homedir8 } from "os";
|
|
17639
|
-
import { join as
|
|
18000
|
+
import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
|
|
17640
18001
|
var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
|
|
17641
|
-
function detectLegacyClaudePlugin(cwd, claudeDir =
|
|
17642
|
-
const registry3 = readJson(
|
|
18002
|
+
function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
|
|
18003
|
+
const registry3 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
|
|
17643
18004
|
const plugins = registry3?.plugins;
|
|
17644
18005
|
if (!plugins || typeof plugins !== "object") return void 0;
|
|
17645
|
-
const enabled = readJson(
|
|
18006
|
+
const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
|
|
17646
18007
|
for (const [key, raw] of Object.entries(plugins)) {
|
|
17647
18008
|
if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
|
|
17648
18009
|
if (enabled && enabled[key] === false) continue;
|
|
@@ -17659,7 +18020,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")
|
|
|
17659
18020
|
}
|
|
17660
18021
|
function readJson(path) {
|
|
17661
18022
|
try {
|
|
17662
|
-
const parsed = JSON.parse(
|
|
18023
|
+
const parsed = JSON.parse(readFileSync7(path, "utf8"));
|
|
17663
18024
|
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
17664
18025
|
} catch {
|
|
17665
18026
|
return void 0;
|
|
@@ -17671,15 +18032,15 @@ function legacyClaudePluginWarning(key) {
|
|
|
17671
18032
|
}
|
|
17672
18033
|
|
|
17673
18034
|
// src/core/session-cache.ts
|
|
17674
|
-
import { mkdirSync as mkdirSync4, readFileSync as
|
|
18035
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
17675
18036
|
import { tmpdir as tmpdir3 } from "os";
|
|
17676
|
-
import { dirname as dirname9, join as
|
|
18037
|
+
import { dirname as dirname9, join as join17 } from "path";
|
|
17677
18038
|
function sessionCacheFile(harness, sessionId) {
|
|
17678
|
-
return
|
|
18039
|
+
return join17(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
|
|
17679
18040
|
}
|
|
17680
18041
|
function readSessionCache(cacheFile) {
|
|
17681
18042
|
try {
|
|
17682
|
-
return JSON.parse(
|
|
18043
|
+
return JSON.parse(readFileSync8(cacheFile, "utf8"));
|
|
17683
18044
|
} catch {
|
|
17684
18045
|
return {};
|
|
17685
18046
|
}
|
|
@@ -17717,15 +18078,15 @@ async function gitSyncNote(args) {
|
|
|
17717
18078
|
if (mode === "none" || cold) return void 0;
|
|
17718
18079
|
const head = gitHeadSha(cwd);
|
|
17719
18080
|
if (!head) return void 0;
|
|
17720
|
-
const gitlogCurrent = await client
|
|
18081
|
+
const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
|
|
17721
18082
|
if (gitlogCurrent === void 0) return void 0;
|
|
17722
18083
|
if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
|
|
17723
18084
|
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
17724
18085
|
let target = DEEPEN_DIFF_TARGET;
|
|
17725
18086
|
try {
|
|
17726
|
-
const { execFileSync:
|
|
18087
|
+
const { execFileSync: execFileSync5 } = await import("child_process");
|
|
17727
18088
|
const n = Number(
|
|
17728
|
-
|
|
18089
|
+
execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
17729
18090
|
encoding: "utf8",
|
|
17730
18091
|
windowsHide: true,
|
|
17731
18092
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17742,6 +18103,7 @@ async function buildSessionStartContext(args) {
|
|
|
17742
18103
|
const t0 = Date.now();
|
|
17743
18104
|
let cold;
|
|
17744
18105
|
let gitDocIds;
|
|
18106
|
+
let bankEmpty = false;
|
|
17745
18107
|
const harness = args.harness ?? "claude-code";
|
|
17746
18108
|
const hasGit = args.hasGit ?? hasGitHistory;
|
|
17747
18109
|
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
@@ -17781,11 +18143,21 @@ async function buildSessionStartContext(args) {
|
|
|
17781
18143
|
} catch {
|
|
17782
18144
|
docIds = void 0;
|
|
17783
18145
|
}
|
|
17784
|
-
|
|
18146
|
+
let baselines;
|
|
18147
|
+
if (docIds?.size === 0) {
|
|
18148
|
+
baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
|
|
18149
|
+
}
|
|
18150
|
+
cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
|
|
17785
18151
|
gitDocIds = docIds;
|
|
18152
|
+
if (cold === true && client.hasDocuments) {
|
|
18153
|
+
bankEmpty = await client.hasDocuments().then(
|
|
18154
|
+
(has) => !has,
|
|
18155
|
+
() => false
|
|
18156
|
+
);
|
|
18157
|
+
}
|
|
17786
18158
|
if (docIds !== void 0) {
|
|
17787
18159
|
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
17788
|
-
if (
|
|
18160
|
+
if (cold) {
|
|
17789
18161
|
if (cfg.codebaseSurvey !== false) {
|
|
17790
18162
|
const started = await startSurvey(cwd, {
|
|
17791
18163
|
harness,
|
|
@@ -17799,7 +18171,7 @@ async function buildSessionStartContext(args) {
|
|
|
17799
18171
|
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
17800
18172
|
const sha = resolveHeadSha(cwd);
|
|
17801
18173
|
if (sha) {
|
|
17802
|
-
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18174
|
+
const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
17803
18175
|
const counts = [];
|
|
17804
18176
|
for (const id of markers) {
|
|
17805
18177
|
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
@@ -17833,19 +18205,18 @@ async function buildSessionStartContext(args) {
|
|
|
17833
18205
|
}
|
|
17834
18206
|
}
|
|
17835
18207
|
let pages = [];
|
|
17836
|
-
let pageListKnown = false;
|
|
17837
18208
|
try {
|
|
17838
18209
|
pages = parsePageList(await client.listPages());
|
|
17839
|
-
pageListKnown = true;
|
|
17840
18210
|
} catch {
|
|
17841
18211
|
if (client.knowledgePagesSupported === false) {
|
|
17842
18212
|
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
17843
18213
|
}
|
|
17844
18214
|
}
|
|
17845
18215
|
const additionalContext = buildKnowledgePreamble(pages, {
|
|
17846
|
-
reflectOnNewGoals: cfg.autoInject !== "reflect"
|
|
18216
|
+
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18217
|
+
extra: cfg.toolGuideExtra
|
|
17847
18218
|
});
|
|
17848
|
-
const deferInitialReflect =
|
|
18219
|
+
const deferInitialReflect = bankEmpty;
|
|
17849
18220
|
let gitNote;
|
|
17850
18221
|
if (gitDocIds) {
|
|
17851
18222
|
gitNote = await gitSyncNote({
|
|
@@ -17869,7 +18240,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
|
|
|
17869
18240
|
}
|
|
17870
18241
|
|
|
17871
18242
|
// src/core/hook.ts
|
|
17872
|
-
import { existsSync as
|
|
18243
|
+
import { existsSync as existsSync8 } from "fs";
|
|
17873
18244
|
|
|
17874
18245
|
// src/core/inject.ts
|
|
17875
18246
|
function buildReflectQuery(prompt) {
|
|
@@ -17918,7 +18289,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
|
|
|
17918
18289
|
// src/core/turn-journal.ts
|
|
17919
18290
|
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
|
|
17920
18291
|
import { tmpdir as tmpdir4 } from "os";
|
|
17921
|
-
import { dirname as dirname10, join as
|
|
18292
|
+
import { dirname as dirname10, join as join18 } from "path";
|
|
17922
18293
|
|
|
17923
18294
|
// src/core/transcript-util.ts
|
|
17924
18295
|
var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
|
|
@@ -17959,11 +18330,24 @@ function actionLine(tool2, input) {
|
|
|
17959
18330
|
var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
17960
18331
|
|
|
17961
18332
|
// src/core/hook.ts
|
|
17962
|
-
var HOOK_FALLBACK_BUDGET_MS = 7e3;
|
|
17963
18333
|
var HOOK_INJECT_ATTEMPTS = 2;
|
|
18334
|
+
var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
|
|
17964
18335
|
function resolveInjection(got, attempts) {
|
|
17965
18336
|
if (got != null) return got;
|
|
17966
|
-
|
|
18337
|
+
const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
|
|
18338
|
+
return attempts >= budget ? "" : void 0;
|
|
18339
|
+
}
|
|
18340
|
+
var RECALL_QUERY_MAX_TOKENS = 500;
|
|
18341
|
+
function boundRecallQuery(prompt) {
|
|
18342
|
+
let cost = 0;
|
|
18343
|
+
let end = 0;
|
|
18344
|
+
for (const ch of prompt) {
|
|
18345
|
+
const cp = ch.codePointAt(0);
|
|
18346
|
+
cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
|
|
18347
|
+
if (cost > RECALL_QUERY_MAX_TOKENS) break;
|
|
18348
|
+
end += ch.length;
|
|
18349
|
+
}
|
|
18350
|
+
return prompt.slice(0, end);
|
|
17967
18351
|
}
|
|
17968
18352
|
async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
17969
18353
|
const t0 = Date.now();
|
|
@@ -17979,7 +18363,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
17979
18363
|
async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
17980
18364
|
const t0 = Date.now();
|
|
17981
18365
|
try {
|
|
17982
|
-
const observations = await client.recallObservations(prompt
|
|
18366
|
+
const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
|
|
17983
18367
|
diag(harness, event, { ms: Date.now() - t0, count: observations.length });
|
|
17984
18368
|
return observations.length ? formatRecallFallback(observations, lead) : null;
|
|
17985
18369
|
} catch (e) {
|
|
@@ -17987,8 +18371,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
17987
18371
|
return void 0;
|
|
17988
18372
|
}
|
|
17989
18373
|
}
|
|
17990
|
-
async function reflectFallback(harness, prompt, client) {
|
|
17991
|
-
const deadline = Date.now() +
|
|
18374
|
+
async function reflectFallback(harness, prompt, client, timeoutMs) {
|
|
18375
|
+
const deadline = Date.now() + timeoutMs;
|
|
17992
18376
|
const remaining = () => Math.max(deadline - Date.now(), 1);
|
|
17993
18377
|
return await injectPages(harness, prompt, client, remaining(), "reflect_fallback_pages") ?? // Event name predates the `injectRecall` rename and is kept: it is a logged contract that
|
|
17994
18378
|
// other tools read, so renaming it would silently break them.
|
|
@@ -18013,7 +18397,7 @@ async function buildHookOutput(args) {
|
|
|
18013
18397
|
harness,
|
|
18014
18398
|
prompt,
|
|
18015
18399
|
client,
|
|
18016
|
-
|
|
18400
|
+
cfg.injectTimeoutMs,
|
|
18017
18401
|
"inject_pages",
|
|
18018
18402
|
PAGE_INJECT_LEAD
|
|
18019
18403
|
);
|
|
@@ -18026,7 +18410,7 @@ async function buildHookOutput(args) {
|
|
|
18026
18410
|
harness,
|
|
18027
18411
|
prompt,
|
|
18028
18412
|
client,
|
|
18029
|
-
|
|
18413
|
+
cfg.injectTimeoutMs,
|
|
18030
18414
|
"inject_recall",
|
|
18031
18415
|
RECALL_INJECT_LEAD
|
|
18032
18416
|
);
|
|
@@ -18054,7 +18438,7 @@ async function buildHookOutput(args) {
|
|
|
18054
18438
|
answer: reflectAnswer.slice(0, 8e3)
|
|
18055
18439
|
});
|
|
18056
18440
|
} catch (e) {
|
|
18057
|
-
reflectAnswer = resolveInjection(void 0, reflectAttempts);
|
|
18441
|
+
reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
|
|
18058
18442
|
reflectFailed = true;
|
|
18059
18443
|
log.warn(harness, "reflect failed \u2014 session runs without memory", {
|
|
18060
18444
|
error: describeError(e)
|
|
@@ -18068,7 +18452,7 @@ async function buildHookOutput(args) {
|
|
|
18068
18452
|
query: prompt.slice(0, 80)
|
|
18069
18453
|
});
|
|
18070
18454
|
if (e instanceof ReflectError && e.fallbackEligible) {
|
|
18071
|
-
fallback = await reflectFallback(harness, prompt, client);
|
|
18455
|
+
fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
|
|
18072
18456
|
if (fallback) reflectAnswer = fallback;
|
|
18073
18457
|
}
|
|
18074
18458
|
}
|
|
@@ -18101,7 +18485,12 @@ async function buildHookOutput(args) {
|
|
|
18101
18485
|
const blocks = [];
|
|
18102
18486
|
if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
|
|
18103
18487
|
if (cadence > 0 && turns % cadence === 0) {
|
|
18104
|
-
blocks.push(
|
|
18488
|
+
blocks.push(
|
|
18489
|
+
buildRosterRefresh(pages, {
|
|
18490
|
+
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18491
|
+
extra: cfg.toolGuideExtra
|
|
18492
|
+
})
|
|
18493
|
+
);
|
|
18105
18494
|
}
|
|
18106
18495
|
const kept = blocks.filter(Boolean);
|
|
18107
18496
|
let notice;
|
|
@@ -18121,6 +18510,7 @@ async function buildHookOutput(args) {
|
|
|
18121
18510
|
|
|
18122
18511
|
// src/core/runtime.ts
|
|
18123
18512
|
var HARNESS = "opencode";
|
|
18513
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
18124
18514
|
var RuntimeCore = class {
|
|
18125
18515
|
constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
|
|
18126
18516
|
this.client = client;
|
|
@@ -18146,6 +18536,8 @@ var RuntimeCore = class {
|
|
|
18146
18536
|
usageCursors = memoryUsageCursorStore();
|
|
18147
18537
|
/** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
|
|
18148
18538
|
fetchTranscript;
|
|
18539
|
+
/** Write-backs started and not yet settled — what `flush` waits for. */
|
|
18540
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
18149
18541
|
lastInjection = "";
|
|
18150
18542
|
// most recent turn's injection block, keyed by nothing (see getInjection)
|
|
18151
18543
|
deferInitialReflect = false;
|
|
@@ -18170,6 +18562,7 @@ var RuntimeCore = class {
|
|
|
18170
18562
|
pageTrigger: buildPageTrigger(this.cfg),
|
|
18171
18563
|
reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
|
|
18172
18564
|
reflectBudget: this.cfg.reflectBudget,
|
|
18565
|
+
toolGuideExtra: this.cfg.toolGuideExtra,
|
|
18173
18566
|
stampFor: () => buildRetainStamp(this.cfg, {
|
|
18174
18567
|
directory: this.projectDir,
|
|
18175
18568
|
harness: this.harness,
|
|
@@ -18237,7 +18630,8 @@ var RuntimeCore = class {
|
|
|
18237
18630
|
if (turns === 1) {
|
|
18238
18631
|
blocks.push(
|
|
18239
18632
|
buildKnowledgePreamble(output.pages, {
|
|
18240
|
-
reflectOnNewGoals: this.cfg.autoInject !== "reflect"
|
|
18633
|
+
reflectOnNewGoals: this.cfg.autoInject !== "reflect",
|
|
18634
|
+
extra: this.cfg.toolGuideExtra
|
|
18241
18635
|
})
|
|
18242
18636
|
);
|
|
18243
18637
|
}
|
|
@@ -18276,8 +18670,9 @@ var RuntimeCore = class {
|
|
|
18276
18670
|
*/
|
|
18277
18671
|
async onTranscript(sessionId, turns, lastTurnComplete) {
|
|
18278
18672
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18279
|
-
if (!
|
|
18673
|
+
if (!sessionId || !turns.length) return;
|
|
18280
18674
|
this.recordUsage(sessionId, turns, lastTurnComplete);
|
|
18675
|
+
if (!this.writeBackEnabled) return;
|
|
18281
18676
|
const st = this.stateFor(sessionId);
|
|
18282
18677
|
this.retain(sessionId, turns, st.startTs);
|
|
18283
18678
|
}
|
|
@@ -18295,7 +18690,7 @@ var RuntimeCore = class {
|
|
|
18295
18690
|
*/
|
|
18296
18691
|
async onSessionIdle(sessionId) {
|
|
18297
18692
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18298
|
-
if (!
|
|
18693
|
+
if (!sessionId || !this.fetchTranscript) return;
|
|
18299
18694
|
let turns;
|
|
18300
18695
|
try {
|
|
18301
18696
|
turns = await this.fetchTranscript(sessionId);
|
|
@@ -18308,6 +18703,7 @@ var RuntimeCore = class {
|
|
|
18308
18703
|
}
|
|
18309
18704
|
if (!turns.length) return;
|
|
18310
18705
|
this.recordUsage(sessionId, turns, true);
|
|
18706
|
+
if (!this.writeBackEnabled) return;
|
|
18311
18707
|
const st = this.stateFor(sessionId);
|
|
18312
18708
|
if (turns.length <= st.retainedTurns) return;
|
|
18313
18709
|
st.retainedTurns = turns.length;
|
|
@@ -18335,10 +18731,27 @@ var RuntimeCore = class {
|
|
|
18335
18731
|
}
|
|
18336
18732
|
return st;
|
|
18337
18733
|
}
|
|
18734
|
+
/**
|
|
18735
|
+
* Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
|
|
18736
|
+
* so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
|
|
18737
|
+
* calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
|
|
18738
|
+
* stalled server cannot hold the host's exit open. Never throws.
|
|
18739
|
+
*/
|
|
18740
|
+
async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
18741
|
+
if (!this.inFlight.size) return;
|
|
18742
|
+
let timer;
|
|
18743
|
+
await Promise.race([
|
|
18744
|
+
Promise.all(this.inFlight),
|
|
18745
|
+
new Promise((r) => {
|
|
18746
|
+
timer = setTimeout(r, timeoutMs);
|
|
18747
|
+
})
|
|
18748
|
+
]);
|
|
18749
|
+
clearTimeout(timer);
|
|
18750
|
+
}
|
|
18338
18751
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
18339
18752
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
18340
18753
|
const t0 = Date.now();
|
|
18341
|
-
|
|
18754
|
+
const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
18342
18755
|
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
18343
18756
|
cursors: this.cursors,
|
|
18344
18757
|
stamp: buildRetainStamp(this.cfg, {
|
|
@@ -18363,6 +18776,8 @@ var RuntimeCore = class {
|
|
|
18363
18776
|
trigger
|
|
18364
18777
|
})
|
|
18365
18778
|
);
|
|
18779
|
+
this.inFlight.add(write2);
|
|
18780
|
+
void write2.finally(() => this.inFlight.delete(write2));
|
|
18366
18781
|
}
|
|
18367
18782
|
};
|
|
18368
18783
|
|
|
@@ -18393,7 +18808,7 @@ function readOpencodeMessages(messages) {
|
|
|
18393
18808
|
return (messages || []).flatMap((m) => renderMessage(m));
|
|
18394
18809
|
}
|
|
18395
18810
|
function opencodeSessionId(messages) {
|
|
18396
|
-
return
|
|
18811
|
+
return [...messages || []].reverse().find((m) => m.info?.sessionID)?.info?.sessionID;
|
|
18397
18812
|
}
|
|
18398
18813
|
|
|
18399
18814
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/classic/external.js
|
|
@@ -18887,7 +19302,7 @@ __export(core_exports4, {
|
|
|
18887
19302
|
toJSONSchema: () => toJSONSchema2,
|
|
18888
19303
|
treeifyError: () => treeifyError2,
|
|
18889
19304
|
util: () => util_exports2,
|
|
18890
|
-
version: () =>
|
|
19305
|
+
version: () => version3
|
|
18891
19306
|
});
|
|
18892
19307
|
|
|
18893
19308
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
|
|
@@ -19890,10 +20305,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
19890
20305
|
var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
19891
20306
|
var extendedDuration2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
|
19892
20307
|
var guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
19893
|
-
var uuid3 = (
|
|
19894
|
-
if (!
|
|
20308
|
+
var uuid3 = (version4) => {
|
|
20309
|
+
if (!version4)
|
|
19895
20310
|
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
|
|
19896
|
-
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${
|
|
20311
|
+
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
19897
20312
|
};
|
|
19898
20313
|
var uuid42 = /* @__PURE__ */ uuid3(4);
|
|
19899
20314
|
var uuid62 = /* @__PURE__ */ uuid3(6);
|
|
@@ -20551,7 +20966,7 @@ var Doc2 = class {
|
|
|
20551
20966
|
};
|
|
20552
20967
|
|
|
20553
20968
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
|
|
20554
|
-
var
|
|
20969
|
+
var version3 = {
|
|
20555
20970
|
major: 4,
|
|
20556
20971
|
minor: 1,
|
|
20557
20972
|
patch: 8
|
|
@@ -20563,7 +20978,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
|
|
|
20563
20978
|
inst ?? (inst = {});
|
|
20564
20979
|
inst._zod.def = def;
|
|
20565
20980
|
inst._zod.bag = inst._zod.bag || {};
|
|
20566
|
-
inst._zod.version =
|
|
20981
|
+
inst._zod.version = version3;
|
|
20567
20982
|
const checks = [...inst._zod.def.checks ?? []];
|
|
20568
20983
|
if (inst._zod.traits.has("$ZodCheck")) {
|
|
20569
20984
|
checks.unshift(inst);
|
|
@@ -30819,12 +31234,12 @@ function tool(input) {
|
|
|
30819
31234
|
tool.schema = external_exports2;
|
|
30820
31235
|
|
|
30821
31236
|
// src/harness/registry.ts
|
|
30822
|
-
import { readFileSync as
|
|
31237
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
30823
31238
|
var jsonChatReader = (harness) => ({
|
|
30824
31239
|
describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
|
|
30825
31240
|
async read(opts) {
|
|
30826
31241
|
if (!opts.conversations) return [];
|
|
30827
|
-
return JSON.parse(
|
|
31242
|
+
return JSON.parse(readFileSync10(opts.conversations, "utf8"));
|
|
30828
31243
|
}
|
|
30829
31244
|
});
|
|
30830
31245
|
|