@vectorize-io/hindsight-coding-agents 0.8.0 → 0.8.2
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 +73 -8
- package/dist/antigravity-hook.js +444 -80
- package/dist/antigravity-statusline.js +9 -4
- package/dist/antigravity-stop-hook.js +444 -95
- package/dist/claude-hook.js +444 -80
- package/dist/claude-sessionstart-hook.js +476 -93
- package/dist/claude-stop-hook.js +444 -95
- package/dist/cline.js +322 -122
- package/dist/codebuddy-hook.js +4273 -0
- package/dist/codebuddy-sessionstart-hook.js +5033 -0
- package/dist/codebuddy-stop-hook.js +4567 -0
- package/dist/codex-hook.js +444 -80
- package/dist/codex-sessionstart-hook.js +476 -93
- package/dist/codex-stop-hook.js +444 -95
- package/dist/copilot-hook.js +444 -80
- package/dist/copilot-sessionstart-hook.js +476 -93
- package/dist/copilot-stop-hook.js +444 -95
- package/dist/cursor-hook.js +444 -80
- package/dist/cursor-sessionstart-hook.js +476 -93
- package/dist/cursor-stop-hook.js +444 -95
- package/dist/daemon-start.js +16 -8
- package/dist/dcode-hook.js +444 -80
- package/dist/dcode-sessionstart-hook.js +476 -93
- package/dist/dcode-stop-hook.js +444 -95
- package/dist/deepen.js +252 -79
- package/dist/devin-hook.js +444 -80
- package/dist/devin-sessionstart-hook.js +476 -93
- package/dist/devin-stop-hook.js +444 -95
- package/dist/droid-hook.js +444 -80
- package/dist/droid-sessionstart-hook.js +476 -93
- package/dist/droid-stop-hook.js +444 -95
- package/dist/dsh.js +329 -122
- package/dist/grok-hook.js +444 -80
- package/dist/grok-sessionstart-hook.js +476 -93
- package/dist/grok-stop-hook.js +444 -95
- package/dist/hindsight-seed.js +9 -4
- package/dist/index.js +331 -131
- package/dist/installer.js +1046 -647
- package/dist/kilo.js +331 -131
- package/dist/kimi-hook.js +444 -80
- package/dist/kimi-sessionstart-hook.js +476 -93
- package/dist/kimi-stop-hook.js +444 -95
- package/dist/mcp-server.js +272 -89
- package/dist/opencode2.js +328 -128
- package/dist/pi.js +384 -134
- package/dist/prime-agent.js +384 -134
- package/dist/qwen-hook.js +444 -80
- package/dist/qwen-sessionstart-hook.js +476 -93
- package/dist/qwen-stop-hook.js +444 -95
- package/dist/status.js +124 -43
- package/dist/traecode-hook.js +444 -80
- package/dist/traecode-sessionstart-hook.js +476 -93
- package/dist/traecode-stop-hook.js +444 -95
- package/dist/workbuddy-hook.js +4273 -0
- package/dist/workbuddy-sessionstart-hook.js +5033 -0
- package/dist/workbuddy-stop-hook.js +4567 -0
- package/dist/zcode-hook.js +444 -80
- package/dist/zcode-sessionstart-hook.js +476 -93
- package/dist/zcode-stop-hook.js +444 -95
- package/package.json +9 -3
- package/plugin.json +1 -1
- package/skill/SKILL.md +10 -6
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/core/hook.ts
|
|
4
|
-
import { existsSync as existsSync2
|
|
4
|
+
import { existsSync as existsSync2 } from "fs";
|
|
5
5
|
|
|
6
6
|
// src/core/bank.ts
|
|
7
7
|
import { existsSync } from "fs";
|
|
@@ -9,6 +9,7 @@ import { homedir as homedir2 } from "os";
|
|
|
9
9
|
import { basename, dirname as dirname3, join as join4, normalize, sep } from "path";
|
|
10
10
|
|
|
11
11
|
// src/core/diag.ts
|
|
12
|
+
import { readFileSync } from "fs";
|
|
12
13
|
import { join as join2 } from "path";
|
|
13
14
|
|
|
14
15
|
// src/core/log.ts
|
|
@@ -82,9 +83,30 @@ function diag(harness, event, extra = {}) {
|
|
|
82
83
|
} catch {
|
|
83
84
|
}
|
|
84
85
|
}
|
|
86
|
+
function parseHookEvent(harness, raw) {
|
|
87
|
+
const text = raw.replace(/^(?:|)+/, "");
|
|
88
|
+
if (!text.trim()) return null;
|
|
89
|
+
try {
|
|
90
|
+
const ev = JSON.parse(text);
|
|
91
|
+
if (ev && typeof ev === "object" && !Array.isArray(ev)) return ev;
|
|
92
|
+
diag(harness, "hook_input_invalid", { error: "not a JSON object" });
|
|
93
|
+
} catch (e) {
|
|
94
|
+
diag(harness, "hook_input_invalid", { error: e.message });
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
function readHookEvent(harness) {
|
|
99
|
+
let raw;
|
|
100
|
+
try {
|
|
101
|
+
raw = readFileSync(0, "utf8");
|
|
102
|
+
} catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
return parseHookEvent(harness, raw);
|
|
106
|
+
}
|
|
85
107
|
|
|
86
108
|
// src/core/git-layout.ts
|
|
87
|
-
import { lstatSync, readFileSync, realpathSync } from "fs";
|
|
109
|
+
import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
|
|
88
110
|
import { dirname as dirname2, isAbsolute, join as join3, resolve } from "path";
|
|
89
111
|
var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
|
|
90
112
|
var ATTEMPTS = 3;
|
|
@@ -108,7 +130,7 @@ function entryKind(path) {
|
|
|
108
130
|
}
|
|
109
131
|
function readTextOrNull(path) {
|
|
110
132
|
try {
|
|
111
|
-
return
|
|
133
|
+
return readFileSync2(path, "utf8");
|
|
112
134
|
} catch (error) {
|
|
113
135
|
if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
|
|
114
136
|
return null;
|
|
@@ -323,6 +345,19 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
|
|
|
323
345
|
};
|
|
324
346
|
return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
325
347
|
}
|
|
348
|
+
function bankProjectName(config, directory, sessionRoot) {
|
|
349
|
+
if (mappedBank(config, directory, sessionRoot)) return void 0;
|
|
350
|
+
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
351
|
+
if (!dynamic) return void 0;
|
|
352
|
+
const template = config.bankIdTemplate || DEFAULT_TEMPLATE;
|
|
353
|
+
if (!template.includes("{gitProject}")) return void 0;
|
|
354
|
+
try {
|
|
355
|
+
return gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (error instanceof BankResolutionError) return void 0;
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
326
361
|
function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
|
|
327
362
|
try {
|
|
328
363
|
return deriveBankId(config, directory, harness, sessionRoot);
|
|
@@ -338,7 +373,7 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
|
|
|
338
373
|
}
|
|
339
374
|
|
|
340
375
|
// src/core/config.ts
|
|
341
|
-
import { readFileSync as
|
|
376
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
342
377
|
import { homedir as homedir3 } from "os";
|
|
343
378
|
import { join as join7 } from "path";
|
|
344
379
|
|
|
@@ -378,7 +413,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
|
|
|
378
413
|
// src/core/missions.ts
|
|
379
414
|
import { createHash } from "crypto";
|
|
380
415
|
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,
|
|
416
|
+
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
417
|
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
418
|
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
419
|
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 +489,8 @@ var KNOWLEDGE_LABELS = {
|
|
|
454
489
|
]
|
|
455
490
|
};
|
|
456
491
|
function pageScopeRule(project) {
|
|
492
|
+
if (project === void 0)
|
|
493
|
+
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
494
|
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
495
|
}
|
|
459
496
|
var PAGE_TAXONOMY = [
|
|
@@ -635,6 +672,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
|
|
|
635
672
|
return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
|
|
636
673
|
}
|
|
637
674
|
|
|
675
|
+
// package.json
|
|
676
|
+
var version = "0.8.2";
|
|
677
|
+
|
|
638
678
|
// src/core/util.ts
|
|
639
679
|
import { accessSync, constants } from "fs";
|
|
640
680
|
import { delimiter, join as join6 } from "path";
|
|
@@ -658,12 +698,12 @@ function binOnPath(bin) {
|
|
|
658
698
|
}
|
|
659
699
|
}
|
|
660
700
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
661
|
-
function semverGte(
|
|
701
|
+
function semverGte(version2, min) {
|
|
662
702
|
const parts = (v) => {
|
|
663
703
|
const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
664
704
|
return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
|
|
665
705
|
};
|
|
666
|
-
const a =
|
|
706
|
+
const a = version2 ? parts(version2) : void 0;
|
|
667
707
|
const b = parts(min);
|
|
668
708
|
if (!a || !b) return false;
|
|
669
709
|
for (let i = 0; i < 3; i++) {
|
|
@@ -697,6 +737,7 @@ function isOurMcpEntry(entry) {
|
|
|
697
737
|
}
|
|
698
738
|
|
|
699
739
|
// src/core/hindsight.ts
|
|
740
|
+
var USER_AGENT = `hindsight-coding-agents/${version}`;
|
|
700
741
|
function resolveRetainScopes(tags, configured) {
|
|
701
742
|
if (configured !== "per_source") return configured;
|
|
702
743
|
const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
|
|
@@ -732,7 +773,7 @@ async function isEndpointMissing(r) {
|
|
|
732
773
|
const j = await r.json();
|
|
733
774
|
return String(j?.detail ?? "").trim().toLowerCase() === "not found";
|
|
734
775
|
} catch {
|
|
735
|
-
return
|
|
776
|
+
return false;
|
|
736
777
|
}
|
|
737
778
|
}
|
|
738
779
|
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
@@ -751,6 +792,12 @@ var ReflectError = class extends Error {
|
|
|
751
792
|
get fallbackEligible() {
|
|
752
793
|
return this.timedOut || this.status !== void 0 && this.status >= 500;
|
|
753
794
|
}
|
|
795
|
+
/** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
|
|
796
|
+
* only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
|
|
797
|
+
get permanent() {
|
|
798
|
+
const s = this.status;
|
|
799
|
+
return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
|
|
800
|
+
}
|
|
754
801
|
};
|
|
755
802
|
var DEFAULT_MAX_PARALLEL_RETAINS = 10;
|
|
756
803
|
var DEFAULT_PAGE_SEARCH_LIMIT = 10;
|
|
@@ -761,8 +808,10 @@ var DEFAULT_RECALL_OPTIONS = {
|
|
|
761
808
|
include: { entities: null }
|
|
762
809
|
};
|
|
763
810
|
var POLL_CYCLE_MS = 5e3;
|
|
811
|
+
var POLL_MAX_SERVER_ERRORS = 12;
|
|
764
812
|
var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
|
|
765
813
|
var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
814
|
+
var RATE_LIMIT_BACKOFF_MS = 1e3;
|
|
766
815
|
function shapePage(page) {
|
|
767
816
|
const p = page ?? {};
|
|
768
817
|
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
@@ -775,6 +824,15 @@ function shapePage(page) {
|
|
|
775
824
|
body
|
|
776
825
|
};
|
|
777
826
|
}
|
|
827
|
+
var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
|
|
828
|
+
function signalOnlyDispatcher() {
|
|
829
|
+
void globalThis.Headers;
|
|
830
|
+
const d = globalThis[GLOBAL_DISPATCHER];
|
|
831
|
+
if (typeof d?.compose !== "function") return void 0;
|
|
832
|
+
return d.compose(
|
|
833
|
+
(dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
|
|
834
|
+
);
|
|
835
|
+
}
|
|
778
836
|
var HindsightClient = class {
|
|
779
837
|
apiUrl;
|
|
780
838
|
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
@@ -794,6 +852,7 @@ var HindsightClient = class {
|
|
|
794
852
|
observationScopes;
|
|
795
853
|
pageSearchLimit;
|
|
796
854
|
recallOptions;
|
|
855
|
+
rateLimitPatienceMs;
|
|
797
856
|
constructor(o) {
|
|
798
857
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
799
858
|
this.token = o.apiToken;
|
|
@@ -806,6 +865,7 @@ var HindsightClient = class {
|
|
|
806
865
|
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
807
866
|
this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
|
|
808
867
|
this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
|
|
868
|
+
this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
|
|
809
869
|
}
|
|
810
870
|
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
811
871
|
get apiToken() {
|
|
@@ -814,7 +874,8 @@ var HindsightClient = class {
|
|
|
814
874
|
headers() {
|
|
815
875
|
const h = {
|
|
816
876
|
"Content-Type": "application/json",
|
|
817
|
-
"Accept-Encoding": "identity"
|
|
877
|
+
"Accept-Encoding": "identity",
|
|
878
|
+
"User-Agent": USER_AGENT
|
|
818
879
|
};
|
|
819
880
|
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
820
881
|
return h;
|
|
@@ -846,7 +907,8 @@ var HindsightClient = class {
|
|
|
846
907
|
* bounds the whole call.
|
|
847
908
|
*/
|
|
848
909
|
async fetchWithAuth(url, init) {
|
|
849
|
-
const
|
|
910
|
+
const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
|
|
911
|
+
const send = () => fetch(url, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
|
|
850
912
|
const r = await send();
|
|
851
913
|
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
852
914
|
return send();
|
|
@@ -862,13 +924,22 @@ var HindsightClient = class {
|
|
|
862
924
|
}
|
|
863
925
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
864
926
|
async req(method, url, body, tolerate = [], timeoutMs = 15e3) {
|
|
865
|
-
const
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
927
|
+
const payload = body ? JSON.stringify(body) : void 0;
|
|
928
|
+
let r;
|
|
929
|
+
for (let attempt = 0, waited = 0; ; attempt++) {
|
|
930
|
+
r = await this.fetchWithAuth(url, {
|
|
931
|
+
method,
|
|
932
|
+
body: payload,
|
|
933
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
934
|
+
});
|
|
935
|
+
if (r.status !== 429 || tolerate.includes(429)) break;
|
|
936
|
+
const asked = retryAfterMs(r.headers.get("retry-after"));
|
|
937
|
+
const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
|
|
938
|
+
const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
|
|
939
|
+
if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
|
|
940
|
+
await sleep(wait);
|
|
941
|
+
waited += wait;
|
|
942
|
+
}
|
|
872
943
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
873
944
|
throw new Error(
|
|
874
945
|
`${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
@@ -903,7 +974,7 @@ var HindsightClient = class {
|
|
|
903
974
|
}
|
|
904
975
|
/**
|
|
905
976
|
* Whether this server honours `operation_id` on an async retain, and can therefore be appended to
|
|
906
|
-
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via
|
|
977
|
+
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
|
|
907
978
|
* unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
|
|
908
979
|
*/
|
|
909
980
|
async supportsIdempotentRetain() {
|
|
@@ -913,15 +984,21 @@ var HindsightClient = class {
|
|
|
913
984
|
}
|
|
914
985
|
return this.idempotentRetain;
|
|
915
986
|
}
|
|
987
|
+
/** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
|
|
988
|
+
* hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
|
|
989
|
+
* so append silently never turned on (#5286). Servers that predate the alias still answer
|
|
990
|
+
* `/version`, so that stays as the fallback. */
|
|
916
991
|
async probeIdempotentRetain() {
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
992
|
+
for (const path of ["/v1/version", "/version"]) {
|
|
993
|
+
try {
|
|
994
|
+
const r = await this.req("GET", `${this.apiUrl}${path}`);
|
|
995
|
+
if (!r.ok) continue;
|
|
996
|
+
const j = await r.json();
|
|
997
|
+
return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
|
|
998
|
+
} catch {
|
|
999
|
+
}
|
|
924
1000
|
}
|
|
1001
|
+
return false;
|
|
925
1002
|
}
|
|
926
1003
|
/**
|
|
927
1004
|
* Whether a session write-back may use `update_mode="append"`: the server must dedupe by
|
|
@@ -983,6 +1060,14 @@ var HindsightClient = class {
|
|
|
983
1060
|
if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
|
|
984
1061
|
}
|
|
985
1062
|
}
|
|
1063
|
+
/** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
|
|
1064
|
+
* yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
|
|
1065
|
+
async hasDocuments() {
|
|
1066
|
+
const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
|
|
1067
|
+
if (r.status === 404) return false;
|
|
1068
|
+
const j = await r.json();
|
|
1069
|
+
return (j.total ?? j.items?.length ?? 0) > 0;
|
|
1070
|
+
}
|
|
986
1071
|
/** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
|
|
987
1072
|
* entity labels), then seed knowledge pages when the server supports them. Both halves are
|
|
988
1073
|
* idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
|
|
@@ -1064,7 +1149,13 @@ var HindsightClient = class {
|
|
|
1064
1149
|
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
1065
1150
|
const start = Date.now();
|
|
1066
1151
|
const pending = new Set(ids);
|
|
1152
|
+
const serverErrors = /* @__PURE__ */ new Map();
|
|
1067
1153
|
let failed = 0;
|
|
1154
|
+
const giveUp = (id, status) => {
|
|
1155
|
+
pending.delete(id);
|
|
1156
|
+
failed++;
|
|
1157
|
+
this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
|
|
1158
|
+
};
|
|
1068
1159
|
while (pending.size && Date.now() - start < maxMs) {
|
|
1069
1160
|
let backoffMs = POLL_CYCLE_MS;
|
|
1070
1161
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
@@ -1077,7 +1168,14 @@ var HindsightClient = class {
|
|
|
1077
1168
|
);
|
|
1078
1169
|
return;
|
|
1079
1170
|
}
|
|
1080
|
-
if (
|
|
1171
|
+
if (r.status >= 500) {
|
|
1172
|
+
const n = (serverErrors.get(id) ?? 0) + 1;
|
|
1173
|
+
serverErrors.set(id, n);
|
|
1174
|
+
if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
if (!r.ok) return giveUp(id, r.status);
|
|
1178
|
+
serverErrors.delete(id);
|
|
1081
1179
|
const st = ((await r.json()).status || "").toLowerCase();
|
|
1082
1180
|
if (TERMINAL.has(st)) {
|
|
1083
1181
|
pending.delete(id);
|
|
@@ -1261,7 +1359,7 @@ var HindsightClient = class {
|
|
|
1261
1359
|
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
1262
1360
|
*/
|
|
1263
1361
|
async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
|
|
1264
|
-
const pages = pagesFor(this.project
|
|
1362
|
+
const pages = pagesFor(this.project, pagesConfig, customPages);
|
|
1265
1363
|
const existing = /* @__PURE__ */ new Map();
|
|
1266
1364
|
let roots;
|
|
1267
1365
|
try {
|
|
@@ -1336,7 +1434,7 @@ var HindsightClient = class {
|
|
|
1336
1434
|
}
|
|
1337
1435
|
const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
|
|
1338
1436
|
this.log(
|
|
1339
|
-
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ??
|
|
1437
|
+
`[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` : "")
|
|
1340
1438
|
);
|
|
1341
1439
|
}
|
|
1342
1440
|
/**
|
|
@@ -1347,23 +1445,33 @@ var HindsightClient = class {
|
|
|
1347
1445
|
* it: five taxonomy pages against one page per initiative, each an LLM synthesis per
|
|
1348
1446
|
* consolidation under the auto-refresh that used to be the default (#3506).
|
|
1349
1447
|
*
|
|
1350
|
-
*
|
|
1351
|
-
*
|
|
1352
|
-
*
|
|
1448
|
+
* Their `name` and `source_query` are written once, from the initiative's own title, and
|
|
1449
|
+
* re-stating either would rebuild a page whose question never changed. The one exception is
|
|
1450
|
+
* the scope clause: a page captured while the clause named the BANK is scoped to a project no
|
|
1451
|
+
* memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
|
|
1452
|
+
* one — the rest of the query, the user's wording included, is kept. The tree read above is
|
|
1453
|
+
* reused rather than re-fetched.
|
|
1353
1454
|
*/
|
|
1354
1455
|
async resyncInitiativeTriggers(roots, pageTrigger) {
|
|
1355
1456
|
const folder = roots.find(
|
|
1356
1457
|
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
|
|
1357
1458
|
);
|
|
1459
|
+
const bankScope = pageScopeRule(this.bank);
|
|
1358
1460
|
let updated = 0;
|
|
1359
1461
|
for (const page of folder?.children ?? []) {
|
|
1360
|
-
if (page.kind !== "page"
|
|
1361
|
-
const
|
|
1362
|
-
|
|
1462
|
+
if (page.kind !== "page") continue;
|
|
1463
|
+
const patch = {};
|
|
1464
|
+
const query = page.description?.replace(bankScope, pageScopeRule(this.project));
|
|
1465
|
+
if (query !== page.description) patch.source_query = query;
|
|
1466
|
+
if (page.trigger != null) {
|
|
1467
|
+
const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
|
|
1468
|
+
if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
|
|
1469
|
+
}
|
|
1470
|
+
if (!patch.trigger && !patch.source_query) continue;
|
|
1363
1471
|
const r = await this.req(
|
|
1364
1472
|
"PATCH",
|
|
1365
1473
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
|
|
1366
|
-
|
|
1474
|
+
patch
|
|
1367
1475
|
);
|
|
1368
1476
|
if (r.status === 404) continue;
|
|
1369
1477
|
updated++;
|
|
@@ -1391,10 +1499,9 @@ var HindsightClient = class {
|
|
|
1391
1499
|
let pageId = args.relatesToPageId;
|
|
1392
1500
|
if (!pageId) {
|
|
1393
1501
|
const folderId = await this.ensureFolder("Initiatives");
|
|
1394
|
-
const subject = this.project ?? this.bank;
|
|
1395
1502
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
1396
1503
|
name: args.title,
|
|
1397
|
-
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(
|
|
1504
|
+
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),
|
|
1398
1505
|
parent_id: folderId,
|
|
1399
1506
|
tags: ["knowledge:feature-work"],
|
|
1400
1507
|
max_tokens: PAGE_MAX_TOKENS,
|
|
@@ -1409,7 +1516,7 @@ var HindsightClient = class {
|
|
|
1409
1516
|
}
|
|
1410
1517
|
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
1411
1518
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
1412
|
-
const markerId = `initiative-marker-${this.slugify(
|
|
1519
|
+
const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
|
|
1413
1520
|
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
1414
1521
|
const context = `initiative marker for [[page:${pageId}]]`;
|
|
1415
1522
|
await this.retain(content, context, markerId, tags, "document", {
|
|
@@ -1646,7 +1753,7 @@ function resolveConfig(raw = {}) {
|
|
|
1646
1753
|
}
|
|
1647
1754
|
function readRaw(path) {
|
|
1648
1755
|
try {
|
|
1649
|
-
return JSON.parse(
|
|
1756
|
+
return JSON.parse(readFileSync3(path, "utf8"));
|
|
1650
1757
|
} catch (e) {
|
|
1651
1758
|
if (e?.code !== "ENOENT") {
|
|
1652
1759
|
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
@@ -1888,7 +1995,7 @@ This tool guide and the page list are re-injected for you periodically as things
|
|
|
1888
1995
|
}
|
|
1889
1996
|
|
|
1890
1997
|
// src/core/session-cache.ts
|
|
1891
|
-
import { mkdirSync as mkdirSync2, readFileSync as
|
|
1998
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync4, renameSync as renameSync2, rmSync, writeFileSync } from "fs";
|
|
1892
1999
|
import { tmpdir } from "os";
|
|
1893
2000
|
import { dirname as dirname5, join as join8 } from "path";
|
|
1894
2001
|
function sessionCacheFile(harness, sessionId) {
|
|
@@ -1914,6 +2021,24 @@ function writeSessionCache(cacheFile, cache) {
|
|
|
1914
2021
|
} catch {
|
|
1915
2022
|
}
|
|
1916
2023
|
}
|
|
2024
|
+
function pendingContextFile(harness, sessionId) {
|
|
2025
|
+
return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.pending`);
|
|
2026
|
+
}
|
|
2027
|
+
function stashPendingContext(harness, sessionId, context) {
|
|
2028
|
+
const path = pendingContextFile(harness, sessionId);
|
|
2029
|
+
let existing = "";
|
|
2030
|
+
try {
|
|
2031
|
+
existing = readFileSync4(path, "utf8");
|
|
2032
|
+
} catch {
|
|
2033
|
+
}
|
|
2034
|
+
if (existing.includes(context)) return;
|
|
2035
|
+
try {
|
|
2036
|
+
writeFileAtomic(path, existing ? `${existing}
|
|
2037
|
+
|
|
2038
|
+
${context}` : context);
|
|
2039
|
+
} catch {
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
1917
2042
|
function sessionRootFile(harness, sessionId) {
|
|
1918
2043
|
return join8(tmpdir(), `hindsight-${harness}`, `${sessionId}.root`);
|
|
1919
2044
|
}
|
|
@@ -1921,7 +2046,7 @@ function sessionRootDir(harness, sessionId, cwd) {
|
|
|
1921
2046
|
if (!sessionId || !cwd) return cwd;
|
|
1922
2047
|
const file = sessionRootFile(harness, sessionId);
|
|
1923
2048
|
try {
|
|
1924
|
-
const recorded =
|
|
2049
|
+
const recorded = readFileSync4(file, "utf8").trim();
|
|
1925
2050
|
if (recorded) return recorded;
|
|
1926
2051
|
} catch {
|
|
1927
2052
|
}
|
|
@@ -1933,7 +2058,7 @@ function sessionRootDir(harness, sessionId, cwd) {
|
|
|
1933
2058
|
}
|
|
1934
2059
|
|
|
1935
2060
|
// src/core/turn-journal.ts
|
|
1936
|
-
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as
|
|
2061
|
+
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
|
|
1937
2062
|
import { tmpdir as tmpdir2 } from "os";
|
|
1938
2063
|
import { dirname as dirname6, join as join9 } from "path";
|
|
1939
2064
|
|
|
@@ -1975,9 +2100,6 @@ function actionLine(tool, input) {
|
|
|
1975
2100
|
// src/core/turn-journal.ts
|
|
1976
2101
|
var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
1977
2102
|
|
|
1978
|
-
// src/core/retain-hook.ts
|
|
1979
|
-
import { readFileSync as readFileSync7 } from "fs";
|
|
1980
|
-
|
|
1981
2103
|
// src/core/retain-cursor.ts
|
|
1982
2104
|
import { createHash as createHash2 } from "crypto";
|
|
1983
2105
|
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
@@ -1993,7 +2115,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
1993
2115
|
var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
1994
2116
|
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
1995
2117
|
try {
|
|
1996
|
-
const res = await fetch(`${baseUrl}/health`, {
|
|
2118
|
+
const res = await fetch(`${baseUrl}/health`, {
|
|
2119
|
+
headers: { "User-Agent": USER_AGENT },
|
|
2120
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
2121
|
+
});
|
|
1997
2122
|
return res.ok;
|
|
1998
2123
|
} catch {
|
|
1999
2124
|
return false;
|
|
@@ -2236,15 +2361,15 @@ function* readJsonl(path) {
|
|
|
2236
2361
|
import { readFileSync as readFileSync6 } from "fs";
|
|
2237
2362
|
import { join as join11 } from "path";
|
|
2238
2363
|
|
|
2239
|
-
// src/core/session-start.ts
|
|
2240
|
-
import { readFileSync as readFileSync11 } from "fs";
|
|
2241
|
-
|
|
2242
2364
|
// src/core/git.ts
|
|
2243
2365
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
2244
2366
|
import { resolve as resolve2 } from "path";
|
|
2367
|
+
var US = "";
|
|
2368
|
+
var RS = "";
|
|
2245
2369
|
var GITLOG_HEAD = "gitlog-head:";
|
|
2370
|
+
var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
|
|
2246
2371
|
function git(repo, ...args) {
|
|
2247
|
-
return execFileSync2("git", ["-C", repo, ...args], {
|
|
2372
|
+
return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
|
|
2248
2373
|
encoding: "utf8",
|
|
2249
2374
|
maxBuffer: 1 << 28,
|
|
2250
2375
|
windowsHide: true,
|
|
@@ -2290,10 +2415,10 @@ async function gitLogIsCurrent(client, repo, head) {
|
|
|
2290
2415
|
}
|
|
2291
2416
|
|
|
2292
2417
|
// src/core/status.ts
|
|
2293
|
-
import { execFileSync as
|
|
2418
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
2294
2419
|
|
|
2295
2420
|
// src/core/survey.ts
|
|
2296
|
-
import { spawn as realSpawn4 } from "child_process";
|
|
2421
|
+
import { execFileSync as execFileSync3, spawn as realSpawn4 } from "child_process";
|
|
2297
2422
|
import { createHash as createHash4 } from "crypto";
|
|
2298
2423
|
import { existsSync as existsSync3 } from "fs";
|
|
2299
2424
|
import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
|
|
@@ -2306,7 +2431,9 @@ function resolveHostConfig(harness, directory) {
|
|
|
2306
2431
|
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
2307
2432
|
const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
|
|
2308
2433
|
if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
|
|
2309
|
-
|
|
2434
|
+
const resolved2 = applyBankConfig(cfg0, bankId, directory);
|
|
2435
|
+
const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
|
|
2436
|
+
return { ...resolved2, project };
|
|
2310
2437
|
}
|
|
2311
2438
|
|
|
2312
2439
|
// src/core/survey-lease.ts
|
|
@@ -2411,6 +2538,19 @@ function resolveAgentBin(harness, claudeBin) {
|
|
|
2411
2538
|
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
2412
2539
|
}
|
|
2413
2540
|
}
|
|
2541
|
+
function opencodeCanDefineSurveyAgent(bin) {
|
|
2542
|
+
try {
|
|
2543
|
+
const out = execFileSync3(bin, ["--version"], {
|
|
2544
|
+
encoding: "utf8",
|
|
2545
|
+
timeout: 5e3,
|
|
2546
|
+
windowsHide: true,
|
|
2547
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
2548
|
+
});
|
|
2549
|
+
return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
|
|
2550
|
+
} catch {
|
|
2551
|
+
return false;
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2414
2554
|
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.';
|
|
2415
2555
|
var SURVEY_DISALLOWED_TOOLS = [
|
|
2416
2556
|
"Bash",
|
|
@@ -2524,6 +2664,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
2524
2664
|
seen.add(harness);
|
|
2525
2665
|
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
2526
2666
|
if (!exists(bin)) continue;
|
|
2667
|
+
if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
|
|
2668
|
+
continue;
|
|
2527
2669
|
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
2528
2670
|
model: opts.model,
|
|
2529
2671
|
budgetUsd: opts.budgetUsd,
|
|
@@ -2584,7 +2726,7 @@ import { spawn as realSpawn5 } from "child_process";
|
|
|
2584
2726
|
import {
|
|
2585
2727
|
existsSync as existsSync4,
|
|
2586
2728
|
mkdirSync as mkdirSync5,
|
|
2587
|
-
readFileSync as
|
|
2729
|
+
readFileSync as readFileSync7,
|
|
2588
2730
|
realpathSync as realpathSync2,
|
|
2589
2731
|
unlinkSync as unlinkSync2,
|
|
2590
2732
|
writeFileSync as writeFileSync3
|
|
@@ -2615,7 +2757,7 @@ function sameDir(a, b) {
|
|
|
2615
2757
|
}
|
|
2616
2758
|
function stagedVersion(pkgRoot) {
|
|
2617
2759
|
try {
|
|
2618
|
-
const pkg = JSON.parse(
|
|
2760
|
+
const pkg = JSON.parse(readFileSync7(join14(pkgRoot, "package.json"), "utf8"));
|
|
2619
2761
|
return typeof pkg.version === "string" ? pkg.version : "";
|
|
2620
2762
|
} catch {
|
|
2621
2763
|
return "";
|
|
@@ -2640,7 +2782,7 @@ function isNewer(candidate, current2) {
|
|
|
2640
2782
|
}
|
|
2641
2783
|
function dueForCheck(file, now) {
|
|
2642
2784
|
try {
|
|
2643
|
-
const state = JSON.parse(
|
|
2785
|
+
const state = JSON.parse(readFileSync7(file, "utf8"));
|
|
2644
2786
|
return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
|
|
2645
2787
|
} catch {
|
|
2646
2788
|
return true;
|
|
@@ -2649,7 +2791,7 @@ function dueForCheck(file, now) {
|
|
|
2649
2791
|
var ORIGIN_FILE = ".install-origin.json";
|
|
2650
2792
|
function selfUpdatable(runtimeDir) {
|
|
2651
2793
|
try {
|
|
2652
|
-
const origin = JSON.parse(
|
|
2794
|
+
const origin = JSON.parse(readFileSync7(join14(runtimeDir, ORIGIN_FILE), "utf8"));
|
|
2653
2795
|
if (typeof origin.source !== "string" || !origin.source) return false;
|
|
2654
2796
|
return origin.source.split(/[\\/]/).includes("_npx");
|
|
2655
2797
|
} catch {
|
|
@@ -2662,7 +2804,7 @@ function lockFile() {
|
|
|
2662
2804
|
}
|
|
2663
2805
|
function acquireUpdateLock(file, now) {
|
|
2664
2806
|
try {
|
|
2665
|
-
const held = JSON.parse(
|
|
2807
|
+
const held = JSON.parse(readFileSync7(file, "utf8"));
|
|
2666
2808
|
if (held.ts && now - held.ts < LOCK_STALE_MS) {
|
|
2667
2809
|
let holderAlive = false;
|
|
2668
2810
|
if (held.pid) {
|
|
@@ -2703,6 +2845,9 @@ function stampCheck(file, now, latest) {
|
|
|
2703
2845
|
} catch {
|
|
2704
2846
|
}
|
|
2705
2847
|
}
|
|
2848
|
+
function spawnNpm(spawnImpl, bin, args, opts) {
|
|
2849
|
+
return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
|
|
2850
|
+
}
|
|
2706
2851
|
async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
|
|
2707
2852
|
return new Promise((resolve3) => {
|
|
2708
2853
|
let out = "";
|
|
@@ -2716,7 +2861,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn5) {
|
|
|
2716
2861
|
resolve3(v);
|
|
2717
2862
|
};
|
|
2718
2863
|
try {
|
|
2719
|
-
const child = spawnImpl
|
|
2864
|
+
const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
|
|
2720
2865
|
timeout: NPM_VIEW_TIMEOUT_MS,
|
|
2721
2866
|
stdio: ["ignore", "pipe", "ignore"],
|
|
2722
2867
|
windowsHide: true
|
|
@@ -2785,7 +2930,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
|
|
|
2785
2930
|
return "";
|
|
2786
2931
|
}
|
|
2787
2932
|
log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
|
|
2788
|
-
const child = (
|
|
2933
|
+
const child = spawnNpm(
|
|
2934
|
+
opts.spawn ?? realSpawn5,
|
|
2789
2935
|
"npx",
|
|
2790
2936
|
["-y", `${PACKAGE_NAME}@${latest}`, "update"],
|
|
2791
2937
|
{
|
|
@@ -2811,7 +2957,7 @@ async function maybeAutoUpdate(cfg, opts = {}) {
|
|
|
2811
2957
|
}
|
|
2812
2958
|
|
|
2813
2959
|
// src/core/skill-sync.ts
|
|
2814
|
-
import { cpSync, existsSync as existsSync6, readFileSync as
|
|
2960
|
+
import { cpSync, existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
|
|
2815
2961
|
import { homedir as homedir6 } from "os";
|
|
2816
2962
|
import { dirname as dirname10, join as join16 } from "path";
|
|
2817
2963
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
@@ -2847,7 +2993,12 @@ var SKILL_DIRS = {
|
|
|
2847
2993
|
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
2848
2994
|
// and dsh's copy with it.
|
|
2849
2995
|
pi: [".pi", "agent", "skills"],
|
|
2850
|
-
"prime-agent": [".prime", "agent", "skills"]
|
|
2996
|
+
"prime-agent": [".prime", "agent", "skills"],
|
|
2997
|
+
// WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
|
|
2998
|
+
workbuddy: [".workbuddy", "skills"],
|
|
2999
|
+
// CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
|
|
3000
|
+
// its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
|
|
3001
|
+
codebuddy: [".codebuddy", "skills"]
|
|
2851
3002
|
};
|
|
2852
3003
|
var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
|
|
2853
3004
|
var traecodeDotDirName = (home, exists = existsSync5) => {
|
|
@@ -2881,7 +3032,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
2881
3032
|
const dstMd = join16(dst, "SKILL.md");
|
|
2882
3033
|
const installed = existsSync6(dstMd);
|
|
2883
3034
|
if (!installed && !opts.install) return;
|
|
2884
|
-
if (!installed ||
|
|
3035
|
+
if (!installed || readFileSync8(srcMd, "utf8") !== readFileSync8(dstMd, "utf8")) {
|
|
2885
3036
|
cpSync(src, dst, { recursive: true });
|
|
2886
3037
|
}
|
|
2887
3038
|
} catch {
|
|
@@ -2889,7 +3040,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
2889
3040
|
}
|
|
2890
3041
|
|
|
2891
3042
|
// src/core/legacy.ts
|
|
2892
|
-
import { existsSync as existsSync7, readFileSync as
|
|
3043
|
+
import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
|
|
2893
3044
|
import { homedir as homedir7 } from "os";
|
|
2894
3045
|
import { join as join17, relative, isAbsolute as isAbsolute2 } from "path";
|
|
2895
3046
|
var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
|
|
@@ -2914,7 +3065,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join17(homedir7(), ".claude")
|
|
|
2914
3065
|
}
|
|
2915
3066
|
function readJson(path) {
|
|
2916
3067
|
try {
|
|
2917
|
-
const parsed = JSON.parse(
|
|
3068
|
+
const parsed = JSON.parse(readFileSync9(path, "utf8"));
|
|
2918
3069
|
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
2919
3070
|
} catch {
|
|
2920
3071
|
return void 0;
|
|
@@ -2943,9 +3094,9 @@ async function gitSyncNote(args) {
|
|
|
2943
3094
|
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
2944
3095
|
let target = DEEPEN_DIFF_TARGET;
|
|
2945
3096
|
try {
|
|
2946
|
-
const { execFileSync:
|
|
3097
|
+
const { execFileSync: execFileSync6 } = await import("child_process");
|
|
2947
3098
|
const n = Number(
|
|
2948
|
-
|
|
3099
|
+
execFileSync6("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
2949
3100
|
encoding: "utf8",
|
|
2950
3101
|
windowsHide: true,
|
|
2951
3102
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -2962,6 +3113,7 @@ async function buildSessionStartContext(args) {
|
|
|
2962
3113
|
const t0 = Date.now();
|
|
2963
3114
|
let cold;
|
|
2964
3115
|
let gitDocIds;
|
|
3116
|
+
let bankEmpty = false;
|
|
2965
3117
|
const harness = args.harness ?? "claude-code";
|
|
2966
3118
|
const hasGit = args.hasGit ?? hasGitHistory;
|
|
2967
3119
|
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
@@ -3001,11 +3153,21 @@ async function buildSessionStartContext(args) {
|
|
|
3001
3153
|
} catch {
|
|
3002
3154
|
docIds = void 0;
|
|
3003
3155
|
}
|
|
3004
|
-
|
|
3156
|
+
let baselines;
|
|
3157
|
+
if (docIds?.size === 0) {
|
|
3158
|
+
baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
|
|
3159
|
+
}
|
|
3160
|
+
cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
|
|
3005
3161
|
gitDocIds = docIds;
|
|
3162
|
+
if (cold === true && client.hasDocuments) {
|
|
3163
|
+
bankEmpty = await client.hasDocuments().then(
|
|
3164
|
+
(has) => !has,
|
|
3165
|
+
() => false
|
|
3166
|
+
);
|
|
3167
|
+
}
|
|
3006
3168
|
if (docIds !== void 0) {
|
|
3007
3169
|
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
3008
|
-
if (
|
|
3170
|
+
if (cold) {
|
|
3009
3171
|
if (cfg.codebaseSurvey !== false) {
|
|
3010
3172
|
const started = await startSurvey(cwd, {
|
|
3011
3173
|
harness,
|
|
@@ -3019,7 +3181,7 @@ async function buildSessionStartContext(args) {
|
|
|
3019
3181
|
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
3020
3182
|
const sha = resolveHeadSha(cwd);
|
|
3021
3183
|
if (sha) {
|
|
3022
|
-
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
3184
|
+
const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
3023
3185
|
const counts = [];
|
|
3024
3186
|
for (const id of markers) {
|
|
3025
3187
|
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
@@ -3053,10 +3215,8 @@ async function buildSessionStartContext(args) {
|
|
|
3053
3215
|
}
|
|
3054
3216
|
}
|
|
3055
3217
|
let pages = [];
|
|
3056
|
-
let pageListKnown = false;
|
|
3057
3218
|
try {
|
|
3058
3219
|
pages = parsePageList(await client.listPages());
|
|
3059
|
-
pageListKnown = true;
|
|
3060
3220
|
} catch {
|
|
3061
3221
|
if (client.knowledgePagesSupported === false) {
|
|
3062
3222
|
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
@@ -3066,7 +3226,7 @@ async function buildSessionStartContext(args) {
|
|
|
3066
3226
|
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
3067
3227
|
extra: cfg.toolGuideExtra
|
|
3068
3228
|
});
|
|
3069
|
-
const deferInitialReflect =
|
|
3229
|
+
const deferInitialReflect = bankEmpty;
|
|
3070
3230
|
let gitNote;
|
|
3071
3231
|
if (gitDocIds) {
|
|
3072
3232
|
gitNote = await gitSyncNote({
|
|
@@ -3091,12 +3251,8 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
|
|
|
3091
3251
|
async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
3092
3252
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
3093
3253
|
try {
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
ev = JSON.parse(readFileSync11(0, "utf8"));
|
|
3097
|
-
} catch {
|
|
3098
|
-
return;
|
|
3099
|
-
}
|
|
3254
|
+
const ev = readHookEvent(spec.harness);
|
|
3255
|
+
if (!ev) return;
|
|
3100
3256
|
if (spec.accept && !spec.accept(ev)) return;
|
|
3101
3257
|
const { harness } = spec;
|
|
3102
3258
|
const { cwd: rawCwd, sessionId } = spec.parse(ev);
|
|
@@ -3129,6 +3285,10 @@ ${mcpHint}` : mcpHint;
|
|
|
3129
3285
|
if (out.deferInitialReflect && sessionId) {
|
|
3130
3286
|
writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
|
|
3131
3287
|
}
|
|
3288
|
+
if (spec.deferContextToToolHook && out.additionalContext && sessionId) {
|
|
3289
|
+
stashPendingContext(harness, sessionId, out.additionalContext);
|
|
3290
|
+
out.additionalContext = void 0;
|
|
3291
|
+
}
|
|
3132
3292
|
const payload = spec.emit(out);
|
|
3133
3293
|
if (out.systemMessage || out.additionalContext) {
|
|
3134
3294
|
process.stdout.write(JSON.stringify(payload));
|
|
@@ -3138,8 +3298,8 @@ ${mcpHint}` : mcpHint;
|
|
|
3138
3298
|
}
|
|
3139
3299
|
|
|
3140
3300
|
// src/core/traecode-mcp.ts
|
|
3141
|
-
import { execFileSync as
|
|
3142
|
-
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as
|
|
3301
|
+
import { execFileSync as execFileSync5 } from "child_process";
|
|
3302
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "fs";
|
|
3143
3303
|
import { homedir as homedir8 } from "os";
|
|
3144
3304
|
import { dirname as dirname11, isAbsolute as isAbsolute3, join as join18 } from "path";
|
|
3145
3305
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
@@ -3176,7 +3336,7 @@ function gateStateFile() {
|
|
|
3176
3336
|
}
|
|
3177
3337
|
function readGateState(opts = {}) {
|
|
3178
3338
|
try {
|
|
3179
|
-
return JSON.parse(
|
|
3339
|
+
return JSON.parse(readFileSync10(opts.stateFile ?? gateStateFile(), "utf8"));
|
|
3180
3340
|
} catch {
|
|
3181
3341
|
return {};
|
|
3182
3342
|
}
|
|
@@ -3184,7 +3344,7 @@ function readGateState(opts = {}) {
|
|
|
3184
3344
|
function workspaceMcpGateState(settingsPath) {
|
|
3185
3345
|
let raw;
|
|
3186
3346
|
try {
|
|
3187
|
-
raw =
|
|
3347
|
+
raw = readFileSync10(settingsPath, "utf8");
|
|
3188
3348
|
} catch {
|
|
3189
3349
|
return "unknown";
|
|
3190
3350
|
}
|
|
@@ -3224,7 +3384,7 @@ function gitignoreCovers(lines) {
|
|
|
3224
3384
|
function ensureGitignored(repo) {
|
|
3225
3385
|
const gitignore = join18(repo, ".gitignore");
|
|
3226
3386
|
if (!existsSync8(gitignore)) return;
|
|
3227
|
-
const current2 =
|
|
3387
|
+
const current2 = readFileSync10(gitignore, "utf8");
|
|
3228
3388
|
if (gitignoreCovers(current2.split("\n"))) return;
|
|
3229
3389
|
const addition = (current2.endsWith("\n") || current2 === "" ? "" : "\n") + "# hindsight MCP registration (machine-specific)\n.trae/mcp.json\n";
|
|
3230
3390
|
writeFileSync4(gitignore, current2 + addition);
|
|
@@ -3245,7 +3405,7 @@ function registerTraecodeWorkspaceMcp(cwd, opts = {}) {
|
|
|
3245
3405
|
let doc = {};
|
|
3246
3406
|
let exists = false;
|
|
3247
3407
|
try {
|
|
3248
|
-
doc = JSON.parse(
|
|
3408
|
+
doc = JSON.parse(readFileSync10(file, "utf8"));
|
|
3249
3409
|
exists = true;
|
|
3250
3410
|
} catch {
|
|
3251
3411
|
if (existsSync8(file)) return "skipped";
|
|
@@ -3301,7 +3461,7 @@ function findWorkspaceStorageDir(storage, repo) {
|
|
|
3301
3461
|
}
|
|
3302
3462
|
for (const name of entries) {
|
|
3303
3463
|
try {
|
|
3304
|
-
const doc = JSON.parse(
|
|
3464
|
+
const doc = JSON.parse(readFileSync10(join18(storage, name, "workspace.json"), "utf8"));
|
|
3305
3465
|
if (typeof doc.folder !== "string") continue;
|
|
3306
3466
|
let folder;
|
|
3307
3467
|
try {
|
|
@@ -3324,7 +3484,7 @@ function ensureWorkspaceMcpEnabled(cwd, opts = {}) {
|
|
|
3324
3484
|
if (!dir) return "failed";
|
|
3325
3485
|
const db = join18(dir, "state.vscdb");
|
|
3326
3486
|
if (!existsSync8(db)) return "failed";
|
|
3327
|
-
const sqlite = opts.sqlite ??
|
|
3487
|
+
const sqlite = opts.sqlite ?? execFileSync5;
|
|
3328
3488
|
const run = (sql) => sqlite("sqlite3", [db, ".timeout 3000", sql], {
|
|
3329
3489
|
encoding: "utf8",
|
|
3330
3490
|
timeout: SQLITE_TIMEOUT_MS,
|
|
@@ -3372,6 +3532,14 @@ function isSyntheticUserText(text) {
|
|
|
3372
3532
|
const s = text.trimStart();
|
|
3373
3533
|
return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
|
|
3374
3534
|
}
|
|
3535
|
+
var AGENTS_BLOCK_HEADER = /^# AGENTS\.md instructions(?: for [^\n]*)?\n/;
|
|
3536
|
+
var STARTUP_TAG_BLOCK = /^<(recommended_plugins|environment_context)>(?:(?!<\1>)[\s\S])*<\/\1>$/;
|
|
3537
|
+
function isStartupItem(text) {
|
|
3538
|
+
const s = text.trim();
|
|
3539
|
+
if (AGENTS_BLOCK_HEADER.test(s))
|
|
3540
|
+
return s.includes("<INSTRUCTIONS>") && s.includes("</INSTRUCTIONS>");
|
|
3541
|
+
return STARTUP_TAG_BLOCK.test(s);
|
|
3542
|
+
}
|
|
3375
3543
|
function contentText(content) {
|
|
3376
3544
|
return (Array.isArray(content) ? content : []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
|
|
3377
3545
|
}
|
|
@@ -3388,7 +3556,10 @@ function fallbackUserText(payload) {
|
|
|
3388
3556
|
if (Array.isArray(content) && Array.isArray(kinds) && kinds.length === content.length && kinds.every((kind) => typeof kind === "string" && kind.length > 0)) {
|
|
3389
3557
|
return contentText(content.filter((_, index) => !startupKinds.has(kinds[index])));
|
|
3390
3558
|
}
|
|
3391
|
-
const
|
|
3559
|
+
const items = (Array.isArray(content) ? content : []).filter(
|
|
3560
|
+
(c) => !(c && typeof c.text === "string" && isStartupItem(stripInjectedMemory(c.text)))
|
|
3561
|
+
);
|
|
3562
|
+
const text = contentText(items);
|
|
3392
3563
|
return isSyntheticUserText(stripInjectedMemory(text)) ? "" : text;
|
|
3393
3564
|
}
|
|
3394
3565
|
function isUserMessageEvent(line) {
|
|
@@ -3565,7 +3736,7 @@ function readCopilotTranscript(path) {
|
|
|
3565
3736
|
}
|
|
3566
3737
|
|
|
3567
3738
|
// src/core/transcript-grok.ts
|
|
3568
|
-
import { existsSync as existsSync9, readFileSync as
|
|
3739
|
+
import { existsSync as existsSync9, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
|
|
3569
3740
|
import { homedir as homedir9 } from "os";
|
|
3570
3741
|
import { join as join19 } from "path";
|
|
3571
3742
|
var CHAT_HISTORY = "chat_history.jsonl";
|
|
@@ -3576,7 +3747,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
|
|
|
3576
3747
|
try {
|
|
3577
3748
|
for (const candidate of readdirSync3(sessionsDir)) {
|
|
3578
3749
|
const directory = join19(sessionsDir, candidate);
|
|
3579
|
-
if (
|
|
3750
|
+
if (readFileSync11(join19(directory, ".cwd"), "utf8").trim() === cwd) {
|
|
3580
3751
|
return join19(directory, sessionId, CHAT_HISTORY);
|
|
3581
3752
|
}
|
|
3582
3753
|
}
|
|
@@ -3927,7 +4098,7 @@ function readDroidTranscript(path) {
|
|
|
3927
4098
|
}
|
|
3928
4099
|
|
|
3929
4100
|
// src/core/transcript-zcode.ts
|
|
3930
|
-
import { readFileSync as
|
|
4101
|
+
import { readFileSync as readFileSync12 } from "fs";
|
|
3931
4102
|
function messageText(content) {
|
|
3932
4103
|
if (typeof content === "string") return content.trim();
|
|
3933
4104
|
if (!Array.isArray(content)) return "";
|
|
@@ -3937,7 +4108,7 @@ function readZcodeTranscript(path) {
|
|
|
3937
4108
|
if (!path) return [];
|
|
3938
4109
|
let body;
|
|
3939
4110
|
try {
|
|
3940
|
-
body =
|
|
4111
|
+
body = readFileSync12(path, "utf8");
|
|
3941
4112
|
} catch {
|
|
3942
4113
|
return [];
|
|
3943
4114
|
}
|
|
@@ -4096,6 +4267,135 @@ function readKimiTranscript(path) {
|
|
|
4096
4267
|
return turns;
|
|
4097
4268
|
}
|
|
4098
4269
|
|
|
4270
|
+
// src/core/transcript-workbuddy.ts
|
|
4271
|
+
function messageText2(content) {
|
|
4272
|
+
if (typeof content === "string") return content;
|
|
4273
|
+
if (!Array.isArray(content)) return "";
|
|
4274
|
+
return content.filter((b) => b && typeof b.text === "string").map((b) => b.text).join("\n");
|
|
4275
|
+
}
|
|
4276
|
+
var USER_QUERY_RE = /^\s*<user_query>([\s\S]*?)<\/user_query>\s*(?:<image_local_path>[\s\S]*?<\/image_local_path>\s*)?$/;
|
|
4277
|
+
function unwrapUserQuery(text) {
|
|
4278
|
+
const match = USER_QUERY_RE.exec(text);
|
|
4279
|
+
return (match ? match[1] : text).trim();
|
|
4280
|
+
}
|
|
4281
|
+
function isSyntheticUserText2(text) {
|
|
4282
|
+
const s = text.trimStart();
|
|
4283
|
+
return s.startsWith("<cb_summary>") || s.startsWith("<conversation_history_summary>") || s.startsWith("Use the TaskOutput tool ");
|
|
4284
|
+
}
|
|
4285
|
+
function parseArgs2(raw) {
|
|
4286
|
+
if (!raw) return void 0;
|
|
4287
|
+
try {
|
|
4288
|
+
return JSON.parse(raw);
|
|
4289
|
+
} catch {
|
|
4290
|
+
return raw;
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
function stampOf3(line) {
|
|
4294
|
+
return typeof line.timestamp === "number" ? { timestamp: new Date(line.timestamp).toISOString() } : {};
|
|
4295
|
+
}
|
|
4296
|
+
function readWorkbuddyTranscript(path) {
|
|
4297
|
+
const turns = [];
|
|
4298
|
+
for (const rawLine of readJsonl(path)) {
|
|
4299
|
+
const trimmed = rawLine.trim();
|
|
4300
|
+
if (!trimmed) continue;
|
|
4301
|
+
let parsed;
|
|
4302
|
+
try {
|
|
4303
|
+
parsed = JSON.parse(trimmed);
|
|
4304
|
+
} catch {
|
|
4305
|
+
continue;
|
|
4306
|
+
}
|
|
4307
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
4308
|
+
const line = parsed;
|
|
4309
|
+
const stamp = stampOf3(line);
|
|
4310
|
+
if (line.type === "message") {
|
|
4311
|
+
if (line.role !== "user" && line.role !== "assistant") continue;
|
|
4312
|
+
let text = stripInjectedMemory(messageText2(line.content)).trim();
|
|
4313
|
+
if (!text) continue;
|
|
4314
|
+
if (line.role === "user") {
|
|
4315
|
+
if (isSyntheticUserText2(text)) continue;
|
|
4316
|
+
text = unwrapUserQuery(text);
|
|
4317
|
+
if (!text) continue;
|
|
4318
|
+
}
|
|
4319
|
+
turns.push({ role: line.role, content: text, ...stamp });
|
|
4320
|
+
} else if (line.type === "function_call" && typeof line.name === "string") {
|
|
4321
|
+
turns.push({
|
|
4322
|
+
role: "action",
|
|
4323
|
+
content: actionLine(line.name, parseArgs2(line.arguments)),
|
|
4324
|
+
...stamp
|
|
4325
|
+
});
|
|
4326
|
+
}
|
|
4327
|
+
}
|
|
4328
|
+
return turns;
|
|
4329
|
+
}
|
|
4330
|
+
|
|
4331
|
+
// src/core/transcript-codebuddy-ide.ts
|
|
4332
|
+
import { readFileSync as readFileSync13 } from "fs";
|
|
4333
|
+
import { basename as basename3, dirname as dirname12, join as join22 } from "path";
|
|
4334
|
+
var IDE_CONTEXT_RE = /<(user_info|git_status|additional_data|system_reminder)\b[\s\S]*?<\/\1>/g;
|
|
4335
|
+
function readJson2(path) {
|
|
4336
|
+
try {
|
|
4337
|
+
return JSON.parse(readFileSync13(path, "utf8"));
|
|
4338
|
+
} catch {
|
|
4339
|
+
return void 0;
|
|
4340
|
+
}
|
|
4341
|
+
}
|
|
4342
|
+
function ideUserText(raw) {
|
|
4343
|
+
let text = stripInjectedMemory(raw).replace(IDE_CONTEXT_RE, "").trim();
|
|
4344
|
+
if (!text || isSyntheticUserText2(text)) return "";
|
|
4345
|
+
return unwrapUserQuery(text).trim();
|
|
4346
|
+
}
|
|
4347
|
+
function readCodebuddyIdeTranscript(indexPath) {
|
|
4348
|
+
const index = readJson2(indexPath);
|
|
4349
|
+
const entries = index?.messages;
|
|
4350
|
+
if (!Array.isArray(entries)) return [];
|
|
4351
|
+
const messagesDir = join22(dirname12(indexPath), "messages");
|
|
4352
|
+
const turns = [];
|
|
4353
|
+
for (const entry of entries) {
|
|
4354
|
+
const id = entry?.id;
|
|
4355
|
+
if (typeof id !== "string") continue;
|
|
4356
|
+
const file = readJson2(join22(messagesDir, `${id}.json`));
|
|
4357
|
+
const encoded = file?.message;
|
|
4358
|
+
if (typeof encoded !== "string") continue;
|
|
4359
|
+
let inner;
|
|
4360
|
+
try {
|
|
4361
|
+
inner = JSON.parse(encoded);
|
|
4362
|
+
} catch {
|
|
4363
|
+
continue;
|
|
4364
|
+
}
|
|
4365
|
+
const role = typeof inner.role === "string" ? inner.role : file?.role;
|
|
4366
|
+
const isUser = role === "user";
|
|
4367
|
+
const isAssistant = role === "assistant";
|
|
4368
|
+
const stamp = typeof file?.createdAt === "string" ? { timestamp: file.createdAt } : {};
|
|
4369
|
+
const blocks = Array.isArray(inner.content) ? inner.content : [];
|
|
4370
|
+
const texts = [];
|
|
4371
|
+
const calls = [];
|
|
4372
|
+
for (const block of blocks) {
|
|
4373
|
+
if (!block || typeof block !== "object") continue;
|
|
4374
|
+
const { type, text, toolName, args } = block;
|
|
4375
|
+
if (type === "text" && typeof text === "string") texts.push(text);
|
|
4376
|
+
else if (type === "tool-call" && typeof toolName === "string")
|
|
4377
|
+
calls.push({ name: toolName, args });
|
|
4378
|
+
}
|
|
4379
|
+
if (texts.length) {
|
|
4380
|
+
const raw = texts.join("\n");
|
|
4381
|
+
if (isUser) {
|
|
4382
|
+
const text = ideUserText(raw);
|
|
4383
|
+
if (text) turns.push({ role: "user", content: text, ...stamp });
|
|
4384
|
+
} else if (isAssistant) {
|
|
4385
|
+
const text = stripInjectedMemory(raw).trim();
|
|
4386
|
+
if (text) turns.push({ role: "assistant", content: text, ...stamp });
|
|
4387
|
+
}
|
|
4388
|
+
}
|
|
4389
|
+
for (const call of calls) {
|
|
4390
|
+
turns.push({ role: "action", content: actionLine(call.name, call.args), ...stamp });
|
|
4391
|
+
}
|
|
4392
|
+
}
|
|
4393
|
+
return turns;
|
|
4394
|
+
}
|
|
4395
|
+
function readCodebuddyTranscript(path) {
|
|
4396
|
+
return basename3(path) === "index.json" ? readCodebuddyIdeTranscript(path) : readWorkbuddyTranscript(path);
|
|
4397
|
+
}
|
|
4398
|
+
|
|
4099
4399
|
// src/harness/hook-lifecycle.ts
|
|
4100
4400
|
var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
|
|
4101
4401
|
var claudePrompt = {
|
|
@@ -4201,6 +4501,35 @@ var standardSessionStart = (harness) => ({
|
|
|
4201
4501
|
}
|
|
4202
4502
|
})
|
|
4203
4503
|
});
|
|
4504
|
+
var genieSessionStart = (harness) => {
|
|
4505
|
+
const base = standardSessionStart(harness);
|
|
4506
|
+
return {
|
|
4507
|
+
...base,
|
|
4508
|
+
parse: (ev) => ({
|
|
4509
|
+
cwd: ev.cwd || process.env.CODEBUDDY_PROJECT_DIR,
|
|
4510
|
+
sessionId: ev.session_id
|
|
4511
|
+
}),
|
|
4512
|
+
emit: (out) => ({ ...base.emit(out), suppressOutput: true })
|
|
4513
|
+
};
|
|
4514
|
+
};
|
|
4515
|
+
var geniePrompt = (harness) => ({
|
|
4516
|
+
...claudePrompt,
|
|
4517
|
+
harness,
|
|
4518
|
+
emit: (context, notice, ev) => ({
|
|
4519
|
+
...claudePrompt.emit(context, notice, ev),
|
|
4520
|
+
suppressOutput: true
|
|
4521
|
+
})
|
|
4522
|
+
});
|
|
4523
|
+
var genieRetain = (harness, readTranscript) => ({
|
|
4524
|
+
hostTimeoutSec: 60,
|
|
4525
|
+
harness,
|
|
4526
|
+
parse: (ev) => ({
|
|
4527
|
+
sessionId: ev.session_id,
|
|
4528
|
+
transcriptPath: ev.transcript_path,
|
|
4529
|
+
cwd: ev.cwd
|
|
4530
|
+
}),
|
|
4531
|
+
readTranscript
|
|
4532
|
+
});
|
|
4204
4533
|
var notGrokHosted = () => !process.env.GROK_HOOK_EVENT;
|
|
4205
4534
|
var HOOK_HARNESSES = {
|
|
4206
4535
|
"claude-code": {
|
|
@@ -4398,17 +4727,29 @@ var HOOK_HARNESSES = {
|
|
|
4398
4727
|
prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
|
|
4399
4728
|
stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
|
|
4400
4729
|
},
|
|
4730
|
+
// Grok hands the model `additionalContext` from TOOL hooks only: SessionStart is observe-only
|
|
4731
|
+
// and UserPromptSubmit can only block (#5467). Both stash their context instead, and the
|
|
4732
|
+
// prompt entry, also registered on PostToolUse, delivers it beside the next tool result.
|
|
4733
|
+
additionalHooks: [{ event: "PostToolUse", entry: "grok-hook.js", timeout: 30 }],
|
|
4401
4734
|
sessionStart: {
|
|
4402
4735
|
...standardSessionStart("grok-build"),
|
|
4403
4736
|
// Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
|
|
4404
4737
|
parse: (ev) => ({
|
|
4405
4738
|
cwd: ev.cwd,
|
|
4406
4739
|
sessionId: ev.sessionId
|
|
4407
|
-
})
|
|
4740
|
+
}),
|
|
4741
|
+
deferContextToToolHook: true
|
|
4408
4742
|
},
|
|
4409
4743
|
prompt: {
|
|
4410
4744
|
...claudePrompt,
|
|
4411
4745
|
harness: "grok-build",
|
|
4746
|
+
toolHook: {
|
|
4747
|
+
// Grok names the event twice: snake_case `hookEventName`, plus a Claude-named alias.
|
|
4748
|
+
accept: (ev) => ev.hookEventName === "post_tool_use" || ev.hook_event_name === "PostToolUse",
|
|
4749
|
+
emit: (context) => ({
|
|
4750
|
+
hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: context }
|
|
4751
|
+
})
|
|
4752
|
+
},
|
|
4412
4753
|
parse: (ev) => ({
|
|
4413
4754
|
prompt: ev.prompt,
|
|
4414
4755
|
cwd: ev.cwd,
|
|
@@ -4642,6 +4983,48 @@ var HOOK_HARNESSES = {
|
|
|
4642
4983
|
},
|
|
4643
4984
|
readTranscript: readKimiTranscript
|
|
4644
4985
|
}
|
|
4986
|
+
},
|
|
4987
|
+
/**
|
|
4988
|
+
* WorkBuddy (Tencent's AI workbench) keeps a durable transcript at
|
|
4989
|
+
* ~/.workbuddy/projects/<cwd-encoded>/<uuid>.jsonl and speaks Claude's hook protocol —
|
|
4990
|
+
* `session_id` / `transcript_path` / `cwd` in, hookSpecificOutput + systemMessage out — apart
|
|
4991
|
+
* from the two quirks genieSessionStart/geniePrompt handle. The other host-specific piece is the
|
|
4992
|
+
* transcript SCHEMA: `type:"message"` records carrying top-level `role`/`content`, which
|
|
4993
|
+
* core/transcript-workbuddy.ts normalizes. Its Stop payload fills `transcript_path` for real (the
|
|
4994
|
+
* engine's own getHookTranscriptPath), so it retains through `readTranscript` like every other
|
|
4995
|
+
* file-backed host rather than the journal ZCode needs.
|
|
4996
|
+
* CodeBuddy Code ships the same @genie/agent-cli engine and reuses this reader (see `codebuddy`).
|
|
4997
|
+
*/
|
|
4998
|
+
workbuddy: {
|
|
4999
|
+
configStyle: "nested",
|
|
5000
|
+
install: {
|
|
5001
|
+
sessionStart: { event: "SessionStart", entry: "workbuddy-sessionstart-hook.js", timeout: 30 },
|
|
5002
|
+
prompt: { event: "UserPromptSubmit", entry: "workbuddy-hook.js", timeout: 30 },
|
|
5003
|
+
stop: { event: "Stop", entry: "workbuddy-stop-hook.js", timeout: 60 }
|
|
5004
|
+
},
|
|
5005
|
+
sessionStart: genieSessionStart("workbuddy"),
|
|
5006
|
+
prompt: geniePrompt("workbuddy"),
|
|
5007
|
+
retain: genieRetain("workbuddy", readWorkbuddyTranscript)
|
|
5008
|
+
},
|
|
5009
|
+
/**
|
|
5010
|
+
* CodeBuddy — the same `@genie/agent-cli` engine WorkBuddy ships, running under its own product
|
|
5011
|
+
* config (`~/.codebuddy`; WorkBuddy only renames the home folder). Hook names and payload shape
|
|
5012
|
+
* are identical, so this spec differs from `workbuddy` in the files the installer writes, the
|
|
5013
|
+
* harness name stamped on what it retains — and ONE thing more: CodeBuddy ships in two hosts whose
|
|
5014
|
+
* transcripts do NOT look alike. CodeBuddy Code (the CLI) writes the WorkBuddy JSONL, while the
|
|
5015
|
+
* IDE hands the Stop hook its own `<conversation>/index.json` directory layout. So the reader is
|
|
5016
|
+
* a dispatcher on the shape it was handed (core/transcript-codebuddy-ide.ts).
|
|
5017
|
+
*/
|
|
5018
|
+
codebuddy: {
|
|
5019
|
+
configStyle: "nested",
|
|
5020
|
+
install: {
|
|
5021
|
+
sessionStart: { event: "SessionStart", entry: "codebuddy-sessionstart-hook.js", timeout: 30 },
|
|
5022
|
+
prompt: { event: "UserPromptSubmit", entry: "codebuddy-hook.js", timeout: 30 },
|
|
5023
|
+
stop: { event: "Stop", entry: "codebuddy-stop-hook.js", timeout: 60 }
|
|
5024
|
+
},
|
|
5025
|
+
sessionStart: genieSessionStart("codebuddy"),
|
|
5026
|
+
prompt: geniePrompt("codebuddy"),
|
|
5027
|
+
retain: genieRetain("codebuddy", readCodebuddyTranscript)
|
|
4645
5028
|
}
|
|
4646
5029
|
};
|
|
4647
5030
|
var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);
|