@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/dsh.js
CHANGED
|
@@ -8,7 +8,7 @@ var __export = (target, all) => {
|
|
|
8
8
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
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 (error51) {
|
|
155
156
|
if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
|
|
156
157
|
return null;
|
|
@@ -312,13 +313,13 @@ function isWithin(directory, configured) {
|
|
|
312
313
|
function mapLookup(map2, directory) {
|
|
313
314
|
const cwd = normalize(directory);
|
|
314
315
|
let best;
|
|
315
|
-
for (const [dir,
|
|
316
|
+
for (const [dir, value] of Object.entries(map2)) {
|
|
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(config2, directory, sessionRoot = "") {
|
|
324
325
|
const directories = [normalize(directory)];
|
|
@@ -342,6 +343,10 @@ function isOptedIn(config2, directory) {
|
|
|
342
343
|
const pathMap = config2.mapPathToBank;
|
|
343
344
|
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
344
345
|
}
|
|
346
|
+
function pathSection(config2, paths, directory) {
|
|
347
|
+
if (!directory || !paths) return void 0;
|
|
348
|
+
return lookupDirectories(config2, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
|
|
349
|
+
}
|
|
345
350
|
function mappedBank(config2, directory, sessionRoot) {
|
|
346
351
|
const pathMap = config2.mapPathToBank;
|
|
347
352
|
if (!directory || !pathMap) return void 0;
|
|
@@ -361,6 +366,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
|
|
|
361
366
|
};
|
|
362
367
|
return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
363
368
|
}
|
|
369
|
+
function bankProjectName(config2, directory, sessionRoot) {
|
|
370
|
+
if (mappedBank(config2, directory, sessionRoot)) return void 0;
|
|
371
|
+
const dynamic = config2.dynamicBankId ?? !config2.bankId;
|
|
372
|
+
if (!dynamic) return void 0;
|
|
373
|
+
const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
|
|
374
|
+
if (!template.includes("{gitProject}")) return void 0;
|
|
375
|
+
try {
|
|
376
|
+
return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
|
|
377
|
+
} catch (error51) {
|
|
378
|
+
if (error51 instanceof BankResolutionError) return void 0;
|
|
379
|
+
throw error51;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
364
382
|
function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
|
|
365
383
|
try {
|
|
366
384
|
return deriveBankId(config2, directory, harness, sessionRoot);
|
|
@@ -378,7 +396,7 @@ function deriveBankIdOrSkip(config2, 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(version3, 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 = version3 ? parts(version3) : 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(url2, init) {
|
|
816
|
-
const
|
|
884
|
+
const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
|
|
885
|
+
const send = () => fetch(url2, { ...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, url2, 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(url2, {
|
|
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} ${url2} -> ${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(file2, now) {
|
|
1798
2010
|
try {
|
|
1799
|
-
const state = JSON.parse(
|
|
2011
|
+
const state = JSON.parse(readFileSync4(file2, "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(file2, 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(file2, now) {
|
|
1820
2032
|
try {
|
|
1821
|
-
const held = JSON.parse(
|
|
2033
|
+
const held = JSON.parse(readFileSync4(file2, "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(file2, 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 = (version3) => {
|
|
4000
|
+
if (!version3)
|
|
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}-${version3}[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 version3 = detectVersion(normalized, params?.defaultTarget);
|
|
16624
16879
|
const defs = normalized.$defs || normalized.definitions || {};
|
|
16625
16880
|
const ctx = {
|
|
16626
|
-
version:
|
|
16881
|
+
version: version3,
|
|
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";
|
|
@@ -16819,6 +17085,19 @@ function resolveAgentBin(harness, claudeBin) {
|
|
|
16819
17085
|
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
16820
17086
|
}
|
|
16821
17087
|
}
|
|
17088
|
+
function opencodeCanDefineSurveyAgent(bin) {
|
|
17089
|
+
try {
|
|
17090
|
+
const out = execFileSync3(bin, ["--version"], {
|
|
17091
|
+
encoding: "utf8",
|
|
17092
|
+
timeout: 5e3,
|
|
17093
|
+
windowsHide: true,
|
|
17094
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
17095
|
+
});
|
|
17096
|
+
return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
|
|
17097
|
+
} catch {
|
|
17098
|
+
return false;
|
|
17099
|
+
}
|
|
17100
|
+
}
|
|
16822
17101
|
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.';
|
|
16823
17102
|
var SURVEY_DISALLOWED_TOOLS = [
|
|
16824
17103
|
"Bash",
|
|
@@ -16932,6 +17211,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
16932
17211
|
seen.add(harness);
|
|
16933
17212
|
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
16934
17213
|
if (!exists(bin)) continue;
|
|
17214
|
+
if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
|
|
17215
|
+
continue;
|
|
16935
17216
|
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
16936
17217
|
model: opts.model,
|
|
16937
17218
|
budgetUsd: opts.budgetUsd,
|
|
@@ -16988,7 +17269,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
16988
17269
|
var DEEPEN_DIFF_TARGET = 300;
|
|
16989
17270
|
function commitCount(repoDir) {
|
|
16990
17271
|
try {
|
|
16991
|
-
const out =
|
|
17272
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
16992
17273
|
encoding: "utf8",
|
|
16993
17274
|
windowsHide: true,
|
|
16994
17275
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17059,19 +17340,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
|
17059
17340
|
idempotentHint: false,
|
|
17060
17341
|
openWorldHint: false
|
|
17061
17342
|
};
|
|
17062
|
-
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.';
|
|
17063
|
-
function shapePage(page) {
|
|
17064
|
-
const p = page ?? {};
|
|
17065
|
-
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
17066
|
-
return {
|
|
17067
|
-
id: p.id,
|
|
17068
|
-
name: p.name,
|
|
17069
|
-
...p.description ? { description: p.description } : {},
|
|
17070
|
-
...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
|
|
17071
|
-
...p.timestamp ? { last_updated_at: p.timestamp } : {},
|
|
17072
|
-
body
|
|
17073
|
-
};
|
|
17074
|
-
}
|
|
17343
|
+
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.';
|
|
17075
17344
|
function ok(value) {
|
|
17076
17345
|
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
|
17077
17346
|
}
|
|
@@ -17089,6 +17358,8 @@ function guarded(fn) {
|
|
|
17089
17358
|
};
|
|
17090
17359
|
}
|
|
17091
17360
|
function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
17361
|
+
const extra = opts.toolGuideExtra?.trim();
|
|
17362
|
+
const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
|
|
17092
17363
|
return [
|
|
17093
17364
|
{
|
|
17094
17365
|
name: "hindsight_sync_status",
|
|
@@ -17148,7 +17419,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17148
17419
|
},
|
|
17149
17420
|
{
|
|
17150
17421
|
name: "hindsight_search_knowledge_pages",
|
|
17151
|
-
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. " +
|
|
17422
|
+
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,
|
|
17152
17423
|
inputSchema: { query: external_exports.string().describe("what to look for") },
|
|
17153
17424
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
17154
17425
|
handler: async (args) => {
|
|
@@ -17158,9 +17429,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17158
17429
|
pages: hits.map((h) => ({
|
|
17159
17430
|
page: h.name,
|
|
17160
17431
|
page_id: h.id,
|
|
17432
|
+
// The question the page answers — the same `description` the list and read tools
|
|
17433
|
+
// carry, so a hit says what the page is FOR, not just how it opens.
|
|
17434
|
+
...h.source_query ? { description: h.source_query } : {},
|
|
17161
17435
|
snippet: h.snippet
|
|
17162
17436
|
})),
|
|
17163
|
-
crediting
|
|
17437
|
+
crediting
|
|
17164
17438
|
});
|
|
17165
17439
|
} catch (e) {
|
|
17166
17440
|
return err(e);
|
|
@@ -17179,7 +17453,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17179
17453
|
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.",
|
|
17180
17454
|
inputSchema: { page_id: external_exports.string() },
|
|
17181
17455
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
17182
|
-
handler: guarded(async ({ page_id }) =>
|
|
17456
|
+
handler: guarded(async ({ page_id }) => client.getPage(page_id))
|
|
17183
17457
|
},
|
|
17184
17458
|
{
|
|
17185
17459
|
name: "hindsight_reflect",
|
|
@@ -17249,12 +17523,18 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17249
17523
|
import { createHash as createHash4 } from "crypto";
|
|
17250
17524
|
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
17251
17525
|
var PENDING_MAX_BYTES = 256 * 1024;
|
|
17526
|
+
var MAX_CURSOR_PATHS = 16;
|
|
17527
|
+
function advancePaths(seen, path) {
|
|
17528
|
+
if (!path) return seen;
|
|
17529
|
+
return [...(seen ?? []).filter((p) => p !== path), path].slice(-MAX_CURSOR_PATHS);
|
|
17530
|
+
}
|
|
17252
17531
|
function pendingReplayable(cursor, now) {
|
|
17253
17532
|
const pending = cursor.pending ?? [];
|
|
17254
17533
|
if (!pending.length) return true;
|
|
17255
17534
|
if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
|
|
17256
17535
|
return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
|
|
17257
17536
|
}
|
|
17537
|
+
var MAX_CURSOR_OPS = 8;
|
|
17258
17538
|
function fingerprintTurns(turns, count) {
|
|
17259
17539
|
const h = createHash4("sha1").update(String(count));
|
|
17260
17540
|
for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
|
|
@@ -17265,8 +17545,10 @@ function planRetain(turns, cursor, opts) {
|
|
|
17265
17545
|
if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
|
|
17266
17546
|
if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
|
|
17267
17547
|
if (cursor.bank !== opts.bank) return { mode: "replace" };
|
|
17268
|
-
|
|
17269
|
-
|
|
17548
|
+
const seen = cursor.paths ?? [];
|
|
17549
|
+
const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
|
|
17550
|
+
const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
|
|
17551
|
+
if (!continues) return newFile ? { mode: "append", fromTurn: 0 } : { mode: "replace" };
|
|
17270
17552
|
if (cursor.turns === turns.length) return { mode: "skip" };
|
|
17271
17553
|
return { mode: "append", fromTurn: cursor.turns };
|
|
17272
17554
|
}
|
|
@@ -17308,11 +17590,36 @@ function renderSessionJsonl(refId, turns, baseTs) {
|
|
|
17308
17590
|
}
|
|
17309
17591
|
async function supportsAppend(client) {
|
|
17310
17592
|
try {
|
|
17311
|
-
return await client.
|
|
17593
|
+
return await client.supportsAppendRetain();
|
|
17312
17594
|
} catch {
|
|
17313
17595
|
return false;
|
|
17314
17596
|
}
|
|
17315
17597
|
}
|
|
17598
|
+
var OP_CHECK_TIMEOUT_MS = 5e3;
|
|
17599
|
+
var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
|
|
17600
|
+
async function settleOps(client, cursor) {
|
|
17601
|
+
const ops = cursor.ops ?? [];
|
|
17602
|
+
const statuses = await Promise.all(
|
|
17603
|
+
ops.map(async (id) => {
|
|
17604
|
+
try {
|
|
17605
|
+
const r = await client.req(
|
|
17606
|
+
"GET",
|
|
17607
|
+
client.bankUrl(`/operations/${encodeURIComponent(id)}`),
|
|
17608
|
+
void 0,
|
|
17609
|
+
[],
|
|
17610
|
+
OP_CHECK_TIMEOUT_MS
|
|
17611
|
+
);
|
|
17612
|
+
if (r.status === 404) return "not_found";
|
|
17613
|
+
return String((await r.json()).status ?? "").toLowerCase();
|
|
17614
|
+
} catch {
|
|
17615
|
+
return "";
|
|
17616
|
+
}
|
|
17617
|
+
})
|
|
17618
|
+
);
|
|
17619
|
+
const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
|
|
17620
|
+
const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
|
|
17621
|
+
return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
|
|
17622
|
+
}
|
|
17316
17623
|
var DEFAULT_RETRY_WINDOW_MS = 6e4;
|
|
17317
17624
|
var RETAIN_RETRY_ATTEMPTS = 2;
|
|
17318
17625
|
var REQUEST_BUDGET_MS = 15e3;
|
|
@@ -17342,6 +17649,7 @@ function serialize(cursors, sessionId, write2) {
|
|
|
17342
17649
|
});
|
|
17343
17650
|
return next;
|
|
17344
17651
|
}
|
|
17652
|
+
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.`;
|
|
17345
17653
|
async function retainLiveSession(client, sessionId, turns, startTs, harness, opts = {}) {
|
|
17346
17654
|
const cursors = opts.cursors;
|
|
17347
17655
|
if (!cursors)
|
|
@@ -17353,20 +17661,41 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
|
|
|
17353
17661
|
harness,
|
|
17354
17662
|
opts.stamp,
|
|
17355
17663
|
void 0,
|
|
17356
|
-
opts.retryUntil
|
|
17664
|
+
opts.retryUntil,
|
|
17665
|
+
opts.transcriptPath
|
|
17357
17666
|
);
|
|
17358
17667
|
return serialize(
|
|
17359
17668
|
cursors,
|
|
17360
17669
|
sessionId,
|
|
17361
|
-
() => writeSession(
|
|
17670
|
+
() => writeSession(
|
|
17671
|
+
client,
|
|
17672
|
+
sessionId,
|
|
17673
|
+
turns,
|
|
17674
|
+
startTs,
|
|
17675
|
+
harness,
|
|
17676
|
+
opts.stamp,
|
|
17677
|
+
cursors,
|
|
17678
|
+
opts.retryUntil,
|
|
17679
|
+
opts.transcriptPath
|
|
17680
|
+
)
|
|
17362
17681
|
);
|
|
17363
17682
|
}
|
|
17364
|
-
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
|
|
17683
|
+
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
|
|
17365
17684
|
if (!turns.length) return;
|
|
17366
17685
|
const refId = `conversation:${sessionId}`;
|
|
17367
|
-
|
|
17686
|
+
let cursor = cursors?.read(sessionId);
|
|
17687
|
+
const probed = Boolean(cursors) && cursor?.appendSupported !== true;
|
|
17368
17688
|
const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
|
|
17369
|
-
|
|
17689
|
+
let ops = [];
|
|
17690
|
+
if (appendSupported && cursor?.ops?.length && !cursor.dirty)
|
|
17691
|
+
({ cursor, ops } = await settleOps(client, cursor));
|
|
17692
|
+
const plan = planRetain(turns, cursor, {
|
|
17693
|
+
appendSupported,
|
|
17694
|
+
bank: client.bank,
|
|
17695
|
+
path: transcriptPath
|
|
17696
|
+
});
|
|
17697
|
+
if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
|
|
17698
|
+
const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
|
|
17370
17699
|
const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
|
|
17371
17700
|
if (plan.mode === "skip" && !outbox.length) return;
|
|
17372
17701
|
const opId = (mode, content) => uuidV5(`${client.bank}
|
|
@@ -17375,7 +17704,10 @@ ${mode}
|
|
|
17375
17704
|
${content}`);
|
|
17376
17705
|
const submit = (content, operationId, append) => client.retain(
|
|
17377
17706
|
content,
|
|
17378
|
-
|
|
17707
|
+
// Configured context wins. Extraction reads this to decide whose claim a sentence is, so the
|
|
17708
|
+
// default names both speakers: the previous "coding agent session" said nothing about
|
|
17709
|
+
// authorship and let an assistant's proposal be recorded as the user's decision.
|
|
17710
|
+
stamp?.context ?? DEFAULT_RETAIN_CONTEXT,
|
|
17379
17711
|
refId,
|
|
17380
17712
|
// Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
|
|
17381
17713
|
// the documents list filters and draws its agent logo from, so a template cannot displace them.
|
|
@@ -17405,8 +17737,13 @@ ${content}`);
|
|
|
17405
17737
|
turns: turns.length,
|
|
17406
17738
|
fingerprint: fingerprintTurns(turns, turns.length),
|
|
17407
17739
|
bank: client.bank,
|
|
17740
|
+
...paths ? { paths } : {},
|
|
17408
17741
|
...appendSupported ? { appendSupported: true } : {}
|
|
17409
17742
|
};
|
|
17743
|
+
const accepted = (id) => {
|
|
17744
|
+
if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
|
|
17745
|
+
return ops.length ? { ...next, ops } : next;
|
|
17746
|
+
};
|
|
17410
17747
|
const stillOurs = () => {
|
|
17411
17748
|
if (!cursors) return true;
|
|
17412
17749
|
const now = cursors.read(sessionId);
|
|
@@ -17415,12 +17752,10 @@ ${content}`);
|
|
|
17415
17752
|
if (plan.mode === "replace") {
|
|
17416
17753
|
const content = renderSessionJsonl(refId, turns, startTs);
|
|
17417
17754
|
cursors?.write(sessionId, { ...next, dirty: true });
|
|
17418
|
-
|
|
17419
|
-
|
|
17420
|
-
|
|
17421
|
-
|
|
17422
|
-
);
|
|
17423
|
-
cursors?.write(sessionId, next);
|
|
17755
|
+
const operationId = opId("replace", content);
|
|
17756
|
+
await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
|
|
17757
|
+
ops = [];
|
|
17758
|
+
cursors?.write(sessionId, accepted(operationId));
|
|
17424
17759
|
return;
|
|
17425
17760
|
}
|
|
17426
17761
|
const queue = [...outbox];
|
|
@@ -17428,7 +17763,7 @@ ${content}`);
|
|
|
17428
17763
|
const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
|
|
17429
17764
|
queue.push({ content, operationId: opId("append", content), at: Date.now() });
|
|
17430
17765
|
}
|
|
17431
|
-
cursors?.write(sessionId, { ...
|
|
17766
|
+
cursors?.write(sessionId, { ...accepted(), pending: queue });
|
|
17432
17767
|
for (let i = 0; i < queue.length; i++) {
|
|
17433
17768
|
if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
|
|
17434
17769
|
const entry = queue[i];
|
|
@@ -17438,12 +17773,13 @@ ${content}`);
|
|
|
17438
17773
|
retryUntil
|
|
17439
17774
|
);
|
|
17440
17775
|
const remaining = queue.slice(i + 1);
|
|
17441
|
-
|
|
17776
|
+
const done = accepted(entry.operationId);
|
|
17777
|
+
cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
|
|
17442
17778
|
}
|
|
17443
17779
|
}
|
|
17444
17780
|
|
|
17445
17781
|
// src/core/usage.ts
|
|
17446
|
-
import { readFileSync as
|
|
17782
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
17447
17783
|
import { join as join13 } from "path";
|
|
17448
17784
|
function usageFilePath() {
|
|
17449
17785
|
return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
|
|
@@ -17521,7 +17857,8 @@ function resolversFor(ctx) {
|
|
|
17521
17857
|
function buildRetainStamp(cfg, ctx) {
|
|
17522
17858
|
const hasTags = Boolean(cfg.retainTags?.length);
|
|
17523
17859
|
const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
|
|
17524
|
-
|
|
17860
|
+
const hasContext = Boolean(cfg.retainContext?.trim());
|
|
17861
|
+
if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
|
|
17525
17862
|
const base = resolversFor(ctx);
|
|
17526
17863
|
const cache = /* @__PURE__ */ new Map();
|
|
17527
17864
|
const resolvers = Object.fromEntries(
|
|
@@ -17545,19 +17882,19 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
17545
17882
|
for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
|
|
17546
17883
|
metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
|
|
17547
17884
|
}
|
|
17548
|
-
|
|
17885
|
+
const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
|
|
17886
|
+
return { tags, metadata, context };
|
|
17549
17887
|
}
|
|
17550
17888
|
|
|
17551
|
-
// src/core/session-start.ts
|
|
17552
|
-
import { readFileSync as readFileSync8 } from "fs";
|
|
17553
|
-
|
|
17554
17889
|
// src/core/skill-sync.ts
|
|
17555
|
-
import { cpSync, existsSync as
|
|
17890
|
+
import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
17556
17891
|
import { homedir as homedir7 } from "os";
|
|
17557
|
-
import { dirname as dirname8, join as
|
|
17892
|
+
import { dirname as dirname8, join as join15 } from "path";
|
|
17558
17893
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
17559
17894
|
|
|
17560
17895
|
// src/core/skill-dirs.ts
|
|
17896
|
+
import { existsSync as existsSync5 } from "fs";
|
|
17897
|
+
import { join as join14 } from "path";
|
|
17561
17898
|
var SKILL_DIRS = {
|
|
17562
17899
|
"claude-code": [".claude", "skills"],
|
|
17563
17900
|
// Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
|
|
@@ -17570,6 +17907,8 @@ var SKILL_DIRS = {
|
|
|
17570
17907
|
"cline-cli": [".cline", "data", "settings", "skills"],
|
|
17571
17908
|
"qwen-code": [".qwen", "skills"],
|
|
17572
17909
|
// Qwen's user-level skills root (Storage.getUserSkillsDirs)
|
|
17910
|
+
// Kimi Code's user-level skills root, alongside its config.toml and mcp.json.
|
|
17911
|
+
"kimi-code": [".kimi-code", "skills"],
|
|
17573
17912
|
"factory-droid": [".factory", "skills"],
|
|
17574
17913
|
// Droid's user-level skills root
|
|
17575
17914
|
// ZCode scans TWO user roots by default (its resolveDefaultSkillRoots): `~/.zcode/skills` and the
|
|
@@ -17577,31 +17916,53 @@ var SKILL_DIRS = {
|
|
|
17577
17916
|
// skill removal is by fixed directory name, so installing into the shared root would make
|
|
17578
17917
|
// `uninstall zcode` take Codex's and dsh's copy with it.
|
|
17579
17918
|
zcode: [".zcode", "skills"],
|
|
17919
|
+
// TraeCode's user-level skills root, resolved per edition by traecodeDotDir below — like ZCode's
|
|
17920
|
+
// its own, never the shared agentskills root other hosts install into.
|
|
17921
|
+
traecode: [".trae-cn", "skills"],
|
|
17580
17922
|
// The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
|
|
17581
17923
|
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
17582
17924
|
// and dsh's copy with it.
|
|
17583
17925
|
pi: [".pi", "agent", "skills"],
|
|
17584
|
-
"prime-agent": [".prime", "agent", "skills"]
|
|
17926
|
+
"prime-agent": [".prime", "agent", "skills"],
|
|
17927
|
+
// WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
|
|
17928
|
+
workbuddy: [".workbuddy", "skills"],
|
|
17929
|
+
// CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
|
|
17930
|
+
// its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
|
|
17931
|
+
codebuddy: [".codebuddy", "skills"]
|
|
17932
|
+
};
|
|
17933
|
+
var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
|
|
17934
|
+
var traecodeDotDirName = (home, exists = existsSync5) => {
|
|
17935
|
+
for (const dir of TRAE_DOT_DIRS) {
|
|
17936
|
+
if (exists(join14(home, dir))) return dir;
|
|
17937
|
+
}
|
|
17938
|
+
return ".trae-cn";
|
|
17939
|
+
};
|
|
17940
|
+
var resolveSkillDirs = (harness, home) => {
|
|
17941
|
+
const parts = SKILL_DIRS[harness];
|
|
17942
|
+
if (harness === "traecode" && parts) {
|
|
17943
|
+
return [traecodeDotDirName(home), ...parts.slice(1)];
|
|
17944
|
+
}
|
|
17945
|
+
return parts;
|
|
17585
17946
|
};
|
|
17586
17947
|
|
|
17587
17948
|
// src/core/skill-sync.ts
|
|
17588
17949
|
function packagedSkillDir() {
|
|
17589
17950
|
const here = dirname8(fileURLToPath5(import.meta.url));
|
|
17590
|
-
const dist =
|
|
17591
|
-
return
|
|
17951
|
+
const dist = join15(here, "..", "skill");
|
|
17952
|
+
return existsSync6(join15(dist, "SKILL.md")) ? dist : join15(here, "..", "..", "skill");
|
|
17592
17953
|
}
|
|
17593
17954
|
function syncCompanionSkill(harness, opts = {}) {
|
|
17594
17955
|
try {
|
|
17595
|
-
const parts =
|
|
17956
|
+
const parts = resolveSkillDirs(harness, opts.home ?? homedir7());
|
|
17596
17957
|
if (!parts) return;
|
|
17597
17958
|
const src = opts.srcDir ?? packagedSkillDir();
|
|
17598
|
-
const srcMd =
|
|
17599
|
-
if (!
|
|
17600
|
-
const dst =
|
|
17601
|
-
const dstMd =
|
|
17602
|
-
const installed =
|
|
17959
|
+
const srcMd = join15(src, "SKILL.md");
|
|
17960
|
+
if (!existsSync6(srcMd)) return;
|
|
17961
|
+
const dst = join15(opts.home ?? homedir7(), ...parts, "hindsight-coding-agent");
|
|
17962
|
+
const dstMd = join15(dst, "SKILL.md");
|
|
17963
|
+
const installed = existsSync6(dstMd);
|
|
17603
17964
|
if (!installed && !opts.install) return;
|
|
17604
|
-
if (!installed ||
|
|
17965
|
+
if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
|
|
17605
17966
|
cpSync(src, dst, { recursive: true });
|
|
17606
17967
|
}
|
|
17607
17968
|
} catch {
|
|
@@ -17623,15 +17984,15 @@ function brandWord() {
|
|
|
17623
17984
|
}
|
|
17624
17985
|
|
|
17625
17986
|
// src/core/legacy.ts
|
|
17626
|
-
import { existsSync as
|
|
17987
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
|
|
17627
17988
|
import { homedir as homedir8 } from "os";
|
|
17628
|
-
import { join as
|
|
17989
|
+
import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
|
|
17629
17990
|
var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
|
|
17630
|
-
function detectLegacyClaudePlugin(cwd, claudeDir =
|
|
17631
|
-
const registry2 = readJson(
|
|
17991
|
+
function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
|
|
17992
|
+
const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
|
|
17632
17993
|
const plugins = registry2?.plugins;
|
|
17633
17994
|
if (!plugins || typeof plugins !== "object") return void 0;
|
|
17634
|
-
const enabled = readJson(
|
|
17995
|
+
const enabled = readJson(join16(claudeDir, "settings.json"))?.enabledPlugins;
|
|
17635
17996
|
for (const [key, raw] of Object.entries(plugins)) {
|
|
17636
17997
|
if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
|
|
17637
17998
|
if (enabled && enabled[key] === false) continue;
|
|
@@ -17648,7 +18009,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join15(homedir8(), ".claude")
|
|
|
17648
18009
|
}
|
|
17649
18010
|
function readJson(path) {
|
|
17650
18011
|
try {
|
|
17651
|
-
const parsed = JSON.parse(
|
|
18012
|
+
const parsed = JSON.parse(readFileSync7(path, "utf8"));
|
|
17652
18013
|
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
17653
18014
|
} catch {
|
|
17654
18015
|
return void 0;
|
|
@@ -17660,15 +18021,15 @@ function legacyClaudePluginWarning(key) {
|
|
|
17660
18021
|
}
|
|
17661
18022
|
|
|
17662
18023
|
// src/core/session-cache.ts
|
|
17663
|
-
import { mkdirSync as mkdirSync4, readFileSync as
|
|
18024
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
17664
18025
|
import { tmpdir as tmpdir3 } from "os";
|
|
17665
|
-
import { dirname as dirname9, join as
|
|
18026
|
+
import { dirname as dirname9, join as join17 } from "path";
|
|
17666
18027
|
function sessionCacheFile(harness, sessionId) {
|
|
17667
|
-
return
|
|
18028
|
+
return join17(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
|
|
17668
18029
|
}
|
|
17669
18030
|
function readSessionCache(cacheFile) {
|
|
17670
18031
|
try {
|
|
17671
|
-
return JSON.parse(
|
|
18032
|
+
return JSON.parse(readFileSync8(cacheFile, "utf8"));
|
|
17672
18033
|
} catch {
|
|
17673
18034
|
return {};
|
|
17674
18035
|
}
|
|
@@ -17706,15 +18067,15 @@ async function gitSyncNote(args) {
|
|
|
17706
18067
|
if (mode === "none" || cold) return void 0;
|
|
17707
18068
|
const head = gitHeadSha(cwd);
|
|
17708
18069
|
if (!head) return void 0;
|
|
17709
|
-
const gitlogCurrent = await client
|
|
18070
|
+
const gitlogCurrent = await gitLogIsCurrent(client, cwd, head).catch(() => void 0);
|
|
17710
18071
|
if (gitlogCurrent === void 0) return void 0;
|
|
17711
18072
|
if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
|
|
17712
18073
|
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
17713
18074
|
let target = DEEPEN_DIFF_TARGET;
|
|
17714
18075
|
try {
|
|
17715
|
-
const { execFileSync:
|
|
18076
|
+
const { execFileSync: execFileSync5 } = await import("child_process");
|
|
17716
18077
|
const n = Number(
|
|
17717
|
-
|
|
18078
|
+
execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
17718
18079
|
encoding: "utf8",
|
|
17719
18080
|
windowsHide: true,
|
|
17720
18081
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17731,6 +18092,7 @@ async function buildSessionStartContext(args) {
|
|
|
17731
18092
|
const t0 = Date.now();
|
|
17732
18093
|
let cold;
|
|
17733
18094
|
let gitDocIds;
|
|
18095
|
+
let bankEmpty = false;
|
|
17734
18096
|
const harness = args.harness ?? "claude-code";
|
|
17735
18097
|
const hasGit = args.hasGit ?? hasGitHistory;
|
|
17736
18098
|
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
@@ -17770,11 +18132,21 @@ async function buildSessionStartContext(args) {
|
|
|
17770
18132
|
} catch {
|
|
17771
18133
|
docIds = void 0;
|
|
17772
18134
|
}
|
|
17773
|
-
|
|
18135
|
+
let baselines;
|
|
18136
|
+
if (docIds?.size === 0) {
|
|
18137
|
+
baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
|
|
18138
|
+
}
|
|
18139
|
+
cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
|
|
17774
18140
|
gitDocIds = docIds;
|
|
18141
|
+
if (cold === true && client.hasDocuments) {
|
|
18142
|
+
bankEmpty = await client.hasDocuments().then(
|
|
18143
|
+
(has) => !has,
|
|
18144
|
+
() => false
|
|
18145
|
+
);
|
|
18146
|
+
}
|
|
17775
18147
|
if (docIds !== void 0) {
|
|
17776
18148
|
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
17777
|
-
if (
|
|
18149
|
+
if (cold) {
|
|
17778
18150
|
if (cfg.codebaseSurvey !== false) {
|
|
17779
18151
|
const started = await startSurvey(cwd, {
|
|
17780
18152
|
harness,
|
|
@@ -17788,7 +18160,7 @@ async function buildSessionStartContext(args) {
|
|
|
17788
18160
|
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
17789
18161
|
const sha = resolveHeadSha(cwd);
|
|
17790
18162
|
if (sha) {
|
|
17791
|
-
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18163
|
+
const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
17792
18164
|
const counts = [];
|
|
17793
18165
|
for (const id of markers) {
|
|
17794
18166
|
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
@@ -17822,19 +18194,18 @@ async function buildSessionStartContext(args) {
|
|
|
17822
18194
|
}
|
|
17823
18195
|
}
|
|
17824
18196
|
let pages = [];
|
|
17825
|
-
let pageListKnown = false;
|
|
17826
18197
|
try {
|
|
17827
18198
|
pages = parsePageList(await client.listPages());
|
|
17828
|
-
pageListKnown = true;
|
|
17829
18199
|
} catch {
|
|
17830
18200
|
if (client.knowledgePagesSupported === false) {
|
|
17831
18201
|
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
17832
18202
|
}
|
|
17833
18203
|
}
|
|
17834
18204
|
const additionalContext = buildKnowledgePreamble(pages, {
|
|
17835
|
-
reflectOnNewGoals: cfg.autoInject !== "reflect"
|
|
18205
|
+
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18206
|
+
extra: cfg.toolGuideExtra
|
|
17836
18207
|
});
|
|
17837
|
-
const deferInitialReflect =
|
|
18208
|
+
const deferInitialReflect = bankEmpty;
|
|
17838
18209
|
let gitNote;
|
|
17839
18210
|
if (gitDocIds) {
|
|
17840
18211
|
gitNote = await gitSyncNote({
|
|
@@ -17858,7 +18229,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
|
|
|
17858
18229
|
}
|
|
17859
18230
|
|
|
17860
18231
|
// src/core/hook.ts
|
|
17861
|
-
import { existsSync as
|
|
18232
|
+
import { existsSync as existsSync8 } from "fs";
|
|
17862
18233
|
|
|
17863
18234
|
// src/core/inject.ts
|
|
17864
18235
|
function buildReflectQuery(prompt) {
|
|
@@ -17907,7 +18278,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
|
|
|
17907
18278
|
// src/core/turn-journal.ts
|
|
17908
18279
|
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
|
|
17909
18280
|
import { tmpdir as tmpdir4 } from "os";
|
|
17910
|
-
import { dirname as dirname10, join as
|
|
18281
|
+
import { dirname as dirname10, join as join18 } from "path";
|
|
17911
18282
|
|
|
17912
18283
|
// src/core/transcript-util.ts
|
|
17913
18284
|
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;
|
|
@@ -17948,11 +18319,24 @@ function actionLine(tool, input) {
|
|
|
17948
18319
|
var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
17949
18320
|
|
|
17950
18321
|
// src/core/hook.ts
|
|
17951
|
-
var HOOK_FALLBACK_BUDGET_MS = 7e3;
|
|
17952
18322
|
var HOOK_INJECT_ATTEMPTS = 2;
|
|
18323
|
+
var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
|
|
17953
18324
|
function resolveInjection(got, attempts) {
|
|
17954
18325
|
if (got != null) return got;
|
|
17955
|
-
|
|
18326
|
+
const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
|
|
18327
|
+
return attempts >= budget ? "" : void 0;
|
|
18328
|
+
}
|
|
18329
|
+
var RECALL_QUERY_MAX_TOKENS = 500;
|
|
18330
|
+
function boundRecallQuery(prompt) {
|
|
18331
|
+
let cost = 0;
|
|
18332
|
+
let end = 0;
|
|
18333
|
+
for (const ch of prompt) {
|
|
18334
|
+
const cp = ch.codePointAt(0);
|
|
18335
|
+
cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
|
|
18336
|
+
if (cost > RECALL_QUERY_MAX_TOKENS) break;
|
|
18337
|
+
end += ch.length;
|
|
18338
|
+
}
|
|
18339
|
+
return prompt.slice(0, end);
|
|
17956
18340
|
}
|
|
17957
18341
|
async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
17958
18342
|
const t0 = Date.now();
|
|
@@ -17968,7 +18352,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
17968
18352
|
async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
17969
18353
|
const t0 = Date.now();
|
|
17970
18354
|
try {
|
|
17971
|
-
const observations = await client.recallObservations(prompt
|
|
18355
|
+
const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
|
|
17972
18356
|
diag(harness, event, { ms: Date.now() - t0, count: observations.length });
|
|
17973
18357
|
return observations.length ? formatRecallFallback(observations, lead) : null;
|
|
17974
18358
|
} catch (e) {
|
|
@@ -17976,8 +18360,8 @@ async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
17976
18360
|
return void 0;
|
|
17977
18361
|
}
|
|
17978
18362
|
}
|
|
17979
|
-
async function reflectFallback(harness, prompt, client) {
|
|
17980
|
-
const deadline = Date.now() +
|
|
18363
|
+
async function reflectFallback(harness, prompt, client, timeoutMs) {
|
|
18364
|
+
const deadline = Date.now() + timeoutMs;
|
|
17981
18365
|
const remaining = () => Math.max(deadline - Date.now(), 1);
|
|
17982
18366
|
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
|
|
17983
18367
|
// other tools read, so renaming it would silently break them.
|
|
@@ -18002,7 +18386,7 @@ async function buildHookOutput(args) {
|
|
|
18002
18386
|
harness,
|
|
18003
18387
|
prompt,
|
|
18004
18388
|
client,
|
|
18005
|
-
|
|
18389
|
+
cfg.injectTimeoutMs,
|
|
18006
18390
|
"inject_pages",
|
|
18007
18391
|
PAGE_INJECT_LEAD
|
|
18008
18392
|
);
|
|
@@ -18015,7 +18399,7 @@ async function buildHookOutput(args) {
|
|
|
18015
18399
|
harness,
|
|
18016
18400
|
prompt,
|
|
18017
18401
|
client,
|
|
18018
|
-
|
|
18402
|
+
cfg.injectTimeoutMs,
|
|
18019
18403
|
"inject_recall",
|
|
18020
18404
|
RECALL_INJECT_LEAD
|
|
18021
18405
|
);
|
|
@@ -18043,7 +18427,7 @@ async function buildHookOutput(args) {
|
|
|
18043
18427
|
answer: reflectAnswer.slice(0, 8e3)
|
|
18044
18428
|
});
|
|
18045
18429
|
} catch (e) {
|
|
18046
|
-
reflectAnswer = resolveInjection(void 0, reflectAttempts);
|
|
18430
|
+
reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
|
|
18047
18431
|
reflectFailed = true;
|
|
18048
18432
|
log.warn(harness, "reflect failed \u2014 session runs without memory", {
|
|
18049
18433
|
error: describeError(e)
|
|
@@ -18057,7 +18441,7 @@ async function buildHookOutput(args) {
|
|
|
18057
18441
|
query: prompt.slice(0, 80)
|
|
18058
18442
|
});
|
|
18059
18443
|
if (e instanceof ReflectError && e.fallbackEligible) {
|
|
18060
|
-
fallback = await reflectFallback(harness, prompt, client);
|
|
18444
|
+
fallback = await reflectFallback(harness, prompt, client, cfg.injectTimeoutMs);
|
|
18061
18445
|
if (fallback) reflectAnswer = fallback;
|
|
18062
18446
|
}
|
|
18063
18447
|
}
|
|
@@ -18090,7 +18474,12 @@ async function buildHookOutput(args) {
|
|
|
18090
18474
|
const blocks = [];
|
|
18091
18475
|
if (reflectAnswer && reflectRanThisTurn) blocks.push(buildSystemInjection(reflectAnswer));
|
|
18092
18476
|
if (cadence > 0 && turns % cadence === 0) {
|
|
18093
|
-
blocks.push(
|
|
18477
|
+
blocks.push(
|
|
18478
|
+
buildRosterRefresh(pages, {
|
|
18479
|
+
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18480
|
+
extra: cfg.toolGuideExtra
|
|
18481
|
+
})
|
|
18482
|
+
);
|
|
18094
18483
|
}
|
|
18095
18484
|
const kept = blocks.filter(Boolean);
|
|
18096
18485
|
let notice;
|
|
@@ -18110,6 +18499,7 @@ async function buildHookOutput(args) {
|
|
|
18110
18499
|
|
|
18111
18500
|
// src/core/runtime.ts
|
|
18112
18501
|
var HARNESS = "opencode";
|
|
18502
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
18113
18503
|
var RuntimeCore = class {
|
|
18114
18504
|
constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
|
|
18115
18505
|
this.client = client;
|
|
@@ -18135,6 +18525,8 @@ var RuntimeCore = class {
|
|
|
18135
18525
|
usageCursors = memoryUsageCursorStore();
|
|
18136
18526
|
/** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
|
|
18137
18527
|
fetchTranscript;
|
|
18528
|
+
/** Write-backs started and not yet settled — what `flush` waits for. */
|
|
18529
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
18138
18530
|
lastInjection = "";
|
|
18139
18531
|
// most recent turn's injection block, keyed by nothing (see getInjection)
|
|
18140
18532
|
deferInitialReflect = false;
|
|
@@ -18159,6 +18551,7 @@ var RuntimeCore = class {
|
|
|
18159
18551
|
pageTrigger: buildPageTrigger(this.cfg),
|
|
18160
18552
|
reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
|
|
18161
18553
|
reflectBudget: this.cfg.reflectBudget,
|
|
18554
|
+
toolGuideExtra: this.cfg.toolGuideExtra,
|
|
18162
18555
|
stampFor: () => buildRetainStamp(this.cfg, {
|
|
18163
18556
|
directory: this.projectDir,
|
|
18164
18557
|
harness: this.harness,
|
|
@@ -18226,7 +18619,8 @@ var RuntimeCore = class {
|
|
|
18226
18619
|
if (turns === 1) {
|
|
18227
18620
|
blocks.push(
|
|
18228
18621
|
buildKnowledgePreamble(output.pages, {
|
|
18229
|
-
reflectOnNewGoals: this.cfg.autoInject !== "reflect"
|
|
18622
|
+
reflectOnNewGoals: this.cfg.autoInject !== "reflect",
|
|
18623
|
+
extra: this.cfg.toolGuideExtra
|
|
18230
18624
|
})
|
|
18231
18625
|
);
|
|
18232
18626
|
}
|
|
@@ -18265,8 +18659,9 @@ var RuntimeCore = class {
|
|
|
18265
18659
|
*/
|
|
18266
18660
|
async onTranscript(sessionId, turns, lastTurnComplete) {
|
|
18267
18661
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18268
|
-
if (!
|
|
18662
|
+
if (!sessionId || !turns.length) return;
|
|
18269
18663
|
this.recordUsage(sessionId, turns, lastTurnComplete);
|
|
18664
|
+
if (!this.writeBackEnabled) return;
|
|
18270
18665
|
const st = this.stateFor(sessionId);
|
|
18271
18666
|
this.retain(sessionId, turns, st.startTs);
|
|
18272
18667
|
}
|
|
@@ -18284,7 +18679,7 @@ var RuntimeCore = class {
|
|
|
18284
18679
|
*/
|
|
18285
18680
|
async onSessionIdle(sessionId) {
|
|
18286
18681
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18287
|
-
if (!
|
|
18682
|
+
if (!sessionId || !this.fetchTranscript) return;
|
|
18288
18683
|
let turns;
|
|
18289
18684
|
try {
|
|
18290
18685
|
turns = await this.fetchTranscript(sessionId);
|
|
@@ -18297,6 +18692,7 @@ var RuntimeCore = class {
|
|
|
18297
18692
|
}
|
|
18298
18693
|
if (!turns.length) return;
|
|
18299
18694
|
this.recordUsage(sessionId, turns, true);
|
|
18695
|
+
if (!this.writeBackEnabled) return;
|
|
18300
18696
|
const st = this.stateFor(sessionId);
|
|
18301
18697
|
if (turns.length <= st.retainedTurns) return;
|
|
18302
18698
|
st.retainedTurns = turns.length;
|
|
@@ -18324,10 +18720,27 @@ var RuntimeCore = class {
|
|
|
18324
18720
|
}
|
|
18325
18721
|
return st;
|
|
18326
18722
|
}
|
|
18723
|
+
/**
|
|
18724
|
+
* Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
|
|
18725
|
+
* so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
|
|
18726
|
+
* calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
|
|
18727
|
+
* stalled server cannot hold the host's exit open. Never throws.
|
|
18728
|
+
*/
|
|
18729
|
+
async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
18730
|
+
if (!this.inFlight.size) return;
|
|
18731
|
+
let timer;
|
|
18732
|
+
await Promise.race([
|
|
18733
|
+
Promise.all(this.inFlight),
|
|
18734
|
+
new Promise((r) => {
|
|
18735
|
+
timer = setTimeout(r, timeoutMs);
|
|
18736
|
+
})
|
|
18737
|
+
]);
|
|
18738
|
+
clearTimeout(timer);
|
|
18739
|
+
}
|
|
18327
18740
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
18328
18741
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
18329
18742
|
const t0 = Date.now();
|
|
18330
|
-
|
|
18743
|
+
const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
18331
18744
|
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
18332
18745
|
cursors: this.cursors,
|
|
18333
18746
|
stamp: buildRetainStamp(this.cfg, {
|
|
@@ -18352,6 +18765,8 @@ var RuntimeCore = class {
|
|
|
18352
18765
|
trigger
|
|
18353
18766
|
})
|
|
18354
18767
|
);
|
|
18768
|
+
this.inFlight.add(write2);
|
|
18769
|
+
void write2.finally(() => this.inFlight.delete(write2));
|
|
18355
18770
|
}
|
|
18356
18771
|
};
|
|
18357
18772
|
|
|
@@ -18443,10 +18858,11 @@ function injectionMessage(text) {
|
|
|
18443
18858
|
id: randomUUID2(),
|
|
18444
18859
|
role: "user",
|
|
18445
18860
|
content: [{ type: "text", text }],
|
|
18446
|
-
source: { kind:
|
|
18861
|
+
source: { kind: `plugin:${HINDSIGHT_PLUGIN}`, form: "recall" }
|
|
18447
18862
|
};
|
|
18448
18863
|
}
|
|
18449
18864
|
function createDshHooks(resolve3) {
|
|
18865
|
+
const lastInjected = /* @__PURE__ */ new Map();
|
|
18450
18866
|
return {
|
|
18451
18867
|
sessionStart({ agent }) {
|
|
18452
18868
|
const workspace = resolve3(agent);
|
|
@@ -18470,6 +18886,11 @@ function createDshHooks(resolve3) {
|
|
|
18470
18886
|
diag(HARNESS2, "inject_empty", { session: sessionId });
|
|
18471
18887
|
return decision;
|
|
18472
18888
|
}
|
|
18889
|
+
if (injection === lastInjected.get(sessionId)) {
|
|
18890
|
+
diag(HARNESS2, "inject_unchanged", { session: sessionId });
|
|
18891
|
+
return decision;
|
|
18892
|
+
}
|
|
18893
|
+
lastInjected.set(sessionId, injection);
|
|
18473
18894
|
diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
|
|
18474
18895
|
return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
|
|
18475
18896
|
},
|
|
@@ -18482,6 +18903,7 @@ function createDshHooks(resolve3) {
|
|
|
18482
18903
|
},
|
|
18483
18904
|
disposed({ agent }) {
|
|
18484
18905
|
liveAgents.delete(agent.session.header.id);
|
|
18906
|
+
lastInjected.delete(agent.session.header.id);
|
|
18485
18907
|
}
|
|
18486
18908
|
};
|
|
18487
18909
|
}
|