@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
package/dist/opencode2.js
CHANGED
|
@@ -1598,10 +1598,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
1598
1598
|
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
1599
1599
|
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)?)??$/;
|
|
1600
1600
|
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})$/;
|
|
1601
|
-
var uuid = (
|
|
1602
|
-
if (!
|
|
1601
|
+
var uuid = (version4) => {
|
|
1602
|
+
if (!version4)
|
|
1603
1603
|
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)$/;
|
|
1604
|
-
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${
|
|
1604
|
+
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
1605
1605
|
};
|
|
1606
1606
|
var uuid4 = /* @__PURE__ */ uuid(4);
|
|
1607
1607
|
var uuid6 = /* @__PURE__ */ uuid(6);
|
|
@@ -14477,10 +14477,10 @@ function fromJSONSchema(schema, params) {
|
|
|
14477
14477
|
} catch {
|
|
14478
14478
|
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
|
|
14479
14479
|
}
|
|
14480
|
-
const
|
|
14480
|
+
const version4 = detectVersion(normalized, params?.defaultTarget);
|
|
14481
14481
|
const defs = normalized.$defs || normalized.definitions || {};
|
|
14482
14482
|
const ctx = {
|
|
14483
|
-
version:
|
|
14483
|
+
version: version4,
|
|
14484
14484
|
defs,
|
|
14485
14485
|
refs: /* @__PURE__ */ new Map(),
|
|
14486
14486
|
processing: /* @__PURE__ */ new Set(),
|
|
@@ -14519,7 +14519,7 @@ function date4(params) {
|
|
|
14519
14519
|
config(en_default());
|
|
14520
14520
|
|
|
14521
14521
|
// src/core/config.ts
|
|
14522
|
-
import { readFileSync as
|
|
14522
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
14523
14523
|
import { homedir as homedir3 } from "os";
|
|
14524
14524
|
import { join as join7 } from "path";
|
|
14525
14525
|
|
|
@@ -14562,6 +14562,7 @@ import { homedir as homedir2 } from "os";
|
|
|
14562
14562
|
import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
|
|
14563
14563
|
|
|
14564
14564
|
// src/core/diag.ts
|
|
14565
|
+
import { readFileSync } from "fs";
|
|
14565
14566
|
import { join as join3 } from "path";
|
|
14566
14567
|
|
|
14567
14568
|
// src/core/log.ts
|
|
@@ -14637,7 +14638,7 @@ function diag(harness, event, extra = {}) {
|
|
|
14637
14638
|
}
|
|
14638
14639
|
|
|
14639
14640
|
// src/core/git-layout.ts
|
|
14640
|
-
import { lstatSync, readFileSync, realpathSync } from "fs";
|
|
14641
|
+
import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
|
|
14641
14642
|
import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
|
|
14642
14643
|
var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
|
|
14643
14644
|
var ATTEMPTS = 3;
|
|
@@ -14661,7 +14662,7 @@ function entryKind(path) {
|
|
|
14661
14662
|
}
|
|
14662
14663
|
function readTextOrNull(path) {
|
|
14663
14664
|
try {
|
|
14664
|
-
return
|
|
14665
|
+
return readFileSync2(path, "utf8");
|
|
14665
14666
|
} catch (error95) {
|
|
14666
14667
|
if (TRANSIENT.has(errorCode(error95))) throw new TransientProbeError(errorCode(error95));
|
|
14667
14668
|
return null;
|
|
@@ -14876,6 +14877,19 @@ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
|
|
|
14876
14877
|
};
|
|
14877
14878
|
return applyTemplate(config3.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
14878
14879
|
}
|
|
14880
|
+
function bankProjectName(config3, directory, sessionRoot) {
|
|
14881
|
+
if (mappedBank(config3, directory, sessionRoot)) return void 0;
|
|
14882
|
+
const dynamic = config3.dynamicBankId ?? !config3.bankId;
|
|
14883
|
+
if (!dynamic) return void 0;
|
|
14884
|
+
const template = config3.bankIdTemplate || DEFAULT_TEMPLATE;
|
|
14885
|
+
if (!template.includes("{gitProject}")) return void 0;
|
|
14886
|
+
try {
|
|
14887
|
+
return gitProjectName(directory, config3.resolveWorktrees ?? true, sessionRoot);
|
|
14888
|
+
} catch (error95) {
|
|
14889
|
+
if (error95 instanceof BankResolutionError) return void 0;
|
|
14890
|
+
throw error95;
|
|
14891
|
+
}
|
|
14892
|
+
}
|
|
14879
14893
|
function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot) {
|
|
14880
14894
|
try {
|
|
14881
14895
|
return deriveBankId(config3, directory, harness, sessionRoot);
|
|
@@ -14893,7 +14907,7 @@ function deriveBankIdOrSkip(config3, directory, harness = "coding", sessionRoot)
|
|
|
14893
14907
|
// src/core/missions.ts
|
|
14894
14908
|
import { createHash } from "crypto";
|
|
14895
14909
|
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.";
|
|
14896
|
-
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history,
|
|
14910
|
+
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.";
|
|
14897
14911
|
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.`;
|
|
14898
14912
|
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.";
|
|
14899
14913
|
var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
|
|
@@ -14969,6 +14983,8 @@ var KNOWLEDGE_LABELS = {
|
|
|
14969
14983
|
]
|
|
14970
14984
|
};
|
|
14971
14985
|
function pageScopeRule(project) {
|
|
14986
|
+
if (project === void 0)
|
|
14987
|
+
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.`;
|
|
14972
14988
|
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.`;
|
|
14973
14989
|
}
|
|
14974
14990
|
var PAGE_TAXONOMY = [
|
|
@@ -15150,6 +15166,9 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
|
|
|
15150
15166
|
return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
|
|
15151
15167
|
}
|
|
15152
15168
|
|
|
15169
|
+
// package.json
|
|
15170
|
+
var version2 = "0.8.2";
|
|
15171
|
+
|
|
15153
15172
|
// src/core/util.ts
|
|
15154
15173
|
import { accessSync, constants } from "fs";
|
|
15155
15174
|
import { delimiter, join as join6 } from "path";
|
|
@@ -15173,12 +15192,12 @@ function binOnPath(bin) {
|
|
|
15173
15192
|
}
|
|
15174
15193
|
}
|
|
15175
15194
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
15176
|
-
function semverGte(
|
|
15195
|
+
function semverGte(version4, min) {
|
|
15177
15196
|
const parts = (v) => {
|
|
15178
15197
|
const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
15179
15198
|
return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
|
|
15180
15199
|
};
|
|
15181
|
-
const a =
|
|
15200
|
+
const a = version4 ? parts(version4) : void 0;
|
|
15182
15201
|
const b = parts(min);
|
|
15183
15202
|
if (!a || !b) return false;
|
|
15184
15203
|
for (let i = 0; i < 3; i++) {
|
|
@@ -15203,6 +15222,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
15203
15222
|
}
|
|
15204
15223
|
|
|
15205
15224
|
// src/core/hindsight.ts
|
|
15225
|
+
var USER_AGENT = `hindsight-coding-agents/${version2}`;
|
|
15206
15226
|
function resolveRetainScopes(tags, configured) {
|
|
15207
15227
|
if (configured !== "per_source") return configured;
|
|
15208
15228
|
const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
|
|
@@ -15238,7 +15258,7 @@ async function isEndpointMissing(r) {
|
|
|
15238
15258
|
const j = await r.json();
|
|
15239
15259
|
return String(j?.detail ?? "").trim().toLowerCase() === "not found";
|
|
15240
15260
|
} catch {
|
|
15241
|
-
return
|
|
15261
|
+
return false;
|
|
15242
15262
|
}
|
|
15243
15263
|
}
|
|
15244
15264
|
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
@@ -15257,6 +15277,12 @@ var ReflectError = class extends Error {
|
|
|
15257
15277
|
get fallbackEligible() {
|
|
15258
15278
|
return this.timedOut || this.status !== void 0 && this.status >= 500;
|
|
15259
15279
|
}
|
|
15280
|
+
/** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
|
|
15281
|
+
* only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
|
|
15282
|
+
get permanent() {
|
|
15283
|
+
const s = this.status;
|
|
15284
|
+
return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
|
|
15285
|
+
}
|
|
15260
15286
|
};
|
|
15261
15287
|
var DEFAULT_MAX_PARALLEL_RETAINS = 10;
|
|
15262
15288
|
var DEFAULT_PAGE_SEARCH_LIMIT = 10;
|
|
@@ -15267,8 +15293,10 @@ var DEFAULT_RECALL_OPTIONS = {
|
|
|
15267
15293
|
include: { entities: null }
|
|
15268
15294
|
};
|
|
15269
15295
|
var POLL_CYCLE_MS = 5e3;
|
|
15296
|
+
var POLL_MAX_SERVER_ERRORS = 12;
|
|
15270
15297
|
var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
|
|
15271
15298
|
var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
15299
|
+
var RATE_LIMIT_BACKOFF_MS = 1e3;
|
|
15272
15300
|
function shapePage(page) {
|
|
15273
15301
|
const p = page ?? {};
|
|
15274
15302
|
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
@@ -15281,6 +15309,15 @@ function shapePage(page) {
|
|
|
15281
15309
|
body
|
|
15282
15310
|
};
|
|
15283
15311
|
}
|
|
15312
|
+
var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
|
|
15313
|
+
function signalOnlyDispatcher() {
|
|
15314
|
+
void globalThis.Headers;
|
|
15315
|
+
const d = globalThis[GLOBAL_DISPATCHER];
|
|
15316
|
+
if (typeof d?.compose !== "function") return void 0;
|
|
15317
|
+
return d.compose(
|
|
15318
|
+
(dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
|
|
15319
|
+
);
|
|
15320
|
+
}
|
|
15284
15321
|
var HindsightClient = class {
|
|
15285
15322
|
apiUrl;
|
|
15286
15323
|
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
@@ -15300,6 +15337,7 @@ var HindsightClient = class {
|
|
|
15300
15337
|
observationScopes;
|
|
15301
15338
|
pageSearchLimit;
|
|
15302
15339
|
recallOptions;
|
|
15340
|
+
rateLimitPatienceMs;
|
|
15303
15341
|
constructor(o) {
|
|
15304
15342
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
15305
15343
|
this.token = o.apiToken;
|
|
@@ -15312,6 +15350,7 @@ var HindsightClient = class {
|
|
|
15312
15350
|
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
15313
15351
|
this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
|
|
15314
15352
|
this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
|
|
15353
|
+
this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
|
|
15315
15354
|
}
|
|
15316
15355
|
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
15317
15356
|
get apiToken() {
|
|
@@ -15320,7 +15359,8 @@ var HindsightClient = class {
|
|
|
15320
15359
|
headers() {
|
|
15321
15360
|
const h = {
|
|
15322
15361
|
"Content-Type": "application/json",
|
|
15323
|
-
"Accept-Encoding": "identity"
|
|
15362
|
+
"Accept-Encoding": "identity",
|
|
15363
|
+
"User-Agent": USER_AGENT
|
|
15324
15364
|
};
|
|
15325
15365
|
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
15326
15366
|
return h;
|
|
@@ -15352,7 +15392,8 @@ var HindsightClient = class {
|
|
|
15352
15392
|
* bounds the whole call.
|
|
15353
15393
|
*/
|
|
15354
15394
|
async fetchWithAuth(url3, init) {
|
|
15355
|
-
const
|
|
15395
|
+
const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
|
|
15396
|
+
const send = () => fetch(url3, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
|
|
15356
15397
|
const r = await send();
|
|
15357
15398
|
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
15358
15399
|
return send();
|
|
@@ -15368,13 +15409,22 @@ var HindsightClient = class {
|
|
|
15368
15409
|
}
|
|
15369
15410
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
15370
15411
|
async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
|
|
15371
|
-
const
|
|
15372
|
-
|
|
15373
|
-
|
|
15374
|
-
|
|
15375
|
-
|
|
15376
|
-
|
|
15377
|
-
|
|
15412
|
+
const payload = body ? JSON.stringify(body) : void 0;
|
|
15413
|
+
let r;
|
|
15414
|
+
for (let attempt = 0, waited = 0; ; attempt++) {
|
|
15415
|
+
r = await this.fetchWithAuth(url3, {
|
|
15416
|
+
method,
|
|
15417
|
+
body: payload,
|
|
15418
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
15419
|
+
});
|
|
15420
|
+
if (r.status !== 429 || tolerate.includes(429)) break;
|
|
15421
|
+
const asked = retryAfterMs(r.headers.get("retry-after"));
|
|
15422
|
+
const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
|
|
15423
|
+
const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
|
|
15424
|
+
if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
|
|
15425
|
+
await sleep(wait);
|
|
15426
|
+
waited += wait;
|
|
15427
|
+
}
|
|
15378
15428
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
15379
15429
|
throw new Error(
|
|
15380
15430
|
`${method} ${url3} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
@@ -15409,7 +15459,7 @@ var HindsightClient = class {
|
|
|
15409
15459
|
}
|
|
15410
15460
|
/**
|
|
15411
15461
|
* Whether this server honours `operation_id` on an async retain, and can therefore be appended to
|
|
15412
|
-
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via
|
|
15462
|
+
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
|
|
15413
15463
|
* unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
|
|
15414
15464
|
*/
|
|
15415
15465
|
async supportsIdempotentRetain() {
|
|
@@ -15419,15 +15469,21 @@ var HindsightClient = class {
|
|
|
15419
15469
|
}
|
|
15420
15470
|
return this.idempotentRetain;
|
|
15421
15471
|
}
|
|
15472
|
+
/** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
|
|
15473
|
+
* hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
|
|
15474
|
+
* so append silently never turned on (#5286). Servers that predate the alias still answer
|
|
15475
|
+
* `/version`, so that stays as the fallback. */
|
|
15422
15476
|
async probeIdempotentRetain() {
|
|
15423
|
-
|
|
15424
|
-
|
|
15425
|
-
|
|
15426
|
-
|
|
15427
|
-
|
|
15428
|
-
|
|
15429
|
-
|
|
15477
|
+
for (const path of ["/v1/version", "/version"]) {
|
|
15478
|
+
try {
|
|
15479
|
+
const r = await this.req("GET", `${this.apiUrl}${path}`);
|
|
15480
|
+
if (!r.ok) continue;
|
|
15481
|
+
const j = await r.json();
|
|
15482
|
+
return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
|
|
15483
|
+
} catch {
|
|
15484
|
+
}
|
|
15430
15485
|
}
|
|
15486
|
+
return false;
|
|
15431
15487
|
}
|
|
15432
15488
|
/**
|
|
15433
15489
|
* Whether a session write-back may use `update_mode="append"`: the server must dedupe by
|
|
@@ -15489,6 +15545,14 @@ var HindsightClient = class {
|
|
|
15489
15545
|
if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
|
|
15490
15546
|
}
|
|
15491
15547
|
}
|
|
15548
|
+
/** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
|
|
15549
|
+
* yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
|
|
15550
|
+
async hasDocuments() {
|
|
15551
|
+
const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
|
|
15552
|
+
if (r.status === 404) return false;
|
|
15553
|
+
const j = await r.json();
|
|
15554
|
+
return (j.total ?? j.items?.length ?? 0) > 0;
|
|
15555
|
+
}
|
|
15492
15556
|
/** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
|
|
15493
15557
|
* entity labels), then seed knowledge pages when the server supports them. Both halves are
|
|
15494
15558
|
* idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
|
|
@@ -15570,7 +15634,13 @@ var HindsightClient = class {
|
|
|
15570
15634
|
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
15571
15635
|
const start = Date.now();
|
|
15572
15636
|
const pending = new Set(ids);
|
|
15637
|
+
const serverErrors = /* @__PURE__ */ new Map();
|
|
15573
15638
|
let failed = 0;
|
|
15639
|
+
const giveUp = (id, status) => {
|
|
15640
|
+
pending.delete(id);
|
|
15641
|
+
failed++;
|
|
15642
|
+
this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
|
|
15643
|
+
};
|
|
15574
15644
|
while (pending.size && Date.now() - start < maxMs) {
|
|
15575
15645
|
let backoffMs = POLL_CYCLE_MS;
|
|
15576
15646
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
@@ -15583,7 +15653,14 @@ var HindsightClient = class {
|
|
|
15583
15653
|
);
|
|
15584
15654
|
return;
|
|
15585
15655
|
}
|
|
15586
|
-
if (
|
|
15656
|
+
if (r.status >= 500) {
|
|
15657
|
+
const n = (serverErrors.get(id) ?? 0) + 1;
|
|
15658
|
+
serverErrors.set(id, n);
|
|
15659
|
+
if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
|
|
15660
|
+
return;
|
|
15661
|
+
}
|
|
15662
|
+
if (!r.ok) return giveUp(id, r.status);
|
|
15663
|
+
serverErrors.delete(id);
|
|
15587
15664
|
const st = ((await r.json()).status || "").toLowerCase();
|
|
15588
15665
|
if (TERMINAL.has(st)) {
|
|
15589
15666
|
pending.delete(id);
|
|
@@ -15767,7 +15844,7 @@ var HindsightClient = class {
|
|
|
15767
15844
|
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
15768
15845
|
*/
|
|
15769
15846
|
async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
|
|
15770
|
-
const pages = pagesFor(this.project
|
|
15847
|
+
const pages = pagesFor(this.project, pagesConfig, customPages);
|
|
15771
15848
|
const existing = /* @__PURE__ */ new Map();
|
|
15772
15849
|
let roots;
|
|
15773
15850
|
try {
|
|
@@ -15842,7 +15919,7 @@ var HindsightClient = class {
|
|
|
15842
15919
|
}
|
|
15843
15920
|
const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
|
|
15844
15921
|
this.log(
|
|
15845
|
-
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ??
|
|
15922
|
+
`[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` : "")
|
|
15846
15923
|
);
|
|
15847
15924
|
}
|
|
15848
15925
|
/**
|
|
@@ -15853,23 +15930,33 @@ var HindsightClient = class {
|
|
|
15853
15930
|
* it: five taxonomy pages against one page per initiative, each an LLM synthesis per
|
|
15854
15931
|
* consolidation under the auto-refresh that used to be the default (#3506).
|
|
15855
15932
|
*
|
|
15856
|
-
*
|
|
15857
|
-
*
|
|
15858
|
-
*
|
|
15933
|
+
* Their `name` and `source_query` are written once, from the initiative's own title, and
|
|
15934
|
+
* re-stating either would rebuild a page whose question never changed. The one exception is
|
|
15935
|
+
* the scope clause: a page captured while the clause named the BANK is scoped to a project no
|
|
15936
|
+
* memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
|
|
15937
|
+
* one — the rest of the query, the user's wording included, is kept. The tree read above is
|
|
15938
|
+
* reused rather than re-fetched.
|
|
15859
15939
|
*/
|
|
15860
15940
|
async resyncInitiativeTriggers(roots, pageTrigger) {
|
|
15861
15941
|
const folder = roots.find(
|
|
15862
15942
|
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
|
|
15863
15943
|
);
|
|
15944
|
+
const bankScope = pageScopeRule(this.bank);
|
|
15864
15945
|
let updated = 0;
|
|
15865
15946
|
for (const page of folder?.children ?? []) {
|
|
15866
|
-
if (page.kind !== "page"
|
|
15867
|
-
const
|
|
15868
|
-
|
|
15947
|
+
if (page.kind !== "page") continue;
|
|
15948
|
+
const patch = {};
|
|
15949
|
+
const query = page.description?.replace(bankScope, pageScopeRule(this.project));
|
|
15950
|
+
if (query !== page.description) patch.source_query = query;
|
|
15951
|
+
if (page.trigger != null) {
|
|
15952
|
+
const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
|
|
15953
|
+
if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
|
|
15954
|
+
}
|
|
15955
|
+
if (!patch.trigger && !patch.source_query) continue;
|
|
15869
15956
|
const r = await this.req(
|
|
15870
15957
|
"PATCH",
|
|
15871
15958
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
|
|
15872
|
-
|
|
15959
|
+
patch
|
|
15873
15960
|
);
|
|
15874
15961
|
if (r.status === 404) continue;
|
|
15875
15962
|
updated++;
|
|
@@ -15897,10 +15984,9 @@ var HindsightClient = class {
|
|
|
15897
15984
|
let pageId = args.relatesToPageId;
|
|
15898
15985
|
if (!pageId) {
|
|
15899
15986
|
const folderId = await this.ensureFolder("Initiatives");
|
|
15900
|
-
const subject = this.project ?? this.bank;
|
|
15901
15987
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
15902
15988
|
name: args.title,
|
|
15903
|
-
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(
|
|
15989
|
+
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),
|
|
15904
15990
|
parent_id: folderId,
|
|
15905
15991
|
tags: ["knowledge:feature-work"],
|
|
15906
15992
|
max_tokens: PAGE_MAX_TOKENS,
|
|
@@ -15915,7 +16001,7 @@ var HindsightClient = class {
|
|
|
15915
16001
|
}
|
|
15916
16002
|
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
15917
16003
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
15918
|
-
const markerId = `initiative-marker-${this.slugify(
|
|
16004
|
+
const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
|
|
15919
16005
|
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
15920
16006
|
const context = `initiative marker for [[page:${pageId}]]`;
|
|
15921
16007
|
await this.retain(content, context, markerId, tags, "document", {
|
|
@@ -16152,7 +16238,7 @@ function resolveConfig(raw = {}) {
|
|
|
16152
16238
|
}
|
|
16153
16239
|
function readRaw(path) {
|
|
16154
16240
|
try {
|
|
16155
|
-
return JSON.parse(
|
|
16241
|
+
return JSON.parse(readFileSync3(path, "utf8"));
|
|
16156
16242
|
} catch (e) {
|
|
16157
16243
|
if (e?.code !== "ENOENT") {
|
|
16158
16244
|
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
@@ -16339,10 +16425,12 @@ function resolveHostConfig(harness, directory) {
|
|
|
16339
16425
|
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
16340
16426
|
const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
|
|
16341
16427
|
if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
|
|
16342
|
-
|
|
16428
|
+
const resolved2 = applyBankConfig(cfg0, bankId, directory);
|
|
16429
|
+
const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
|
|
16430
|
+
return { ...resolved2, project };
|
|
16343
16431
|
}
|
|
16344
16432
|
function resolveHostMemory(harness, directory) {
|
|
16345
|
-
const { cfg, bankId } = resolveHostConfig(harness, directory);
|
|
16433
|
+
const { cfg, bankId, project } = resolveHostConfig(harness, directory);
|
|
16346
16434
|
return {
|
|
16347
16435
|
cfg,
|
|
16348
16436
|
bankId,
|
|
@@ -16350,6 +16438,8 @@ function resolveHostMemory(harness, directory) {
|
|
|
16350
16438
|
apiUrl: cfg.apiUrl,
|
|
16351
16439
|
apiToken: cfg.apiToken,
|
|
16352
16440
|
bank: bankId,
|
|
16441
|
+
// Names the repo in the initiative pages this host captures, as the seeded pages do.
|
|
16442
|
+
project,
|
|
16353
16443
|
maxParallelRetains: cfg.maxParallelRetains,
|
|
16354
16444
|
observationScopes: cfg.observationScopes,
|
|
16355
16445
|
pageSearchLimit: cfg.pageSearchLimit,
|
|
@@ -16373,7 +16463,7 @@ import { spawn as realSpawn2 } from "child_process";
|
|
|
16373
16463
|
import {
|
|
16374
16464
|
existsSync as existsSync2,
|
|
16375
16465
|
mkdirSync as mkdirSync2,
|
|
16376
|
-
readFileSync as
|
|
16466
|
+
readFileSync as readFileSync4,
|
|
16377
16467
|
realpathSync as realpathSync2,
|
|
16378
16468
|
unlinkSync,
|
|
16379
16469
|
writeFileSync
|
|
@@ -16404,7 +16494,7 @@ function sameDir(a, b) {
|
|
|
16404
16494
|
}
|
|
16405
16495
|
function stagedVersion(pkgRoot) {
|
|
16406
16496
|
try {
|
|
16407
|
-
const pkg = JSON.parse(
|
|
16497
|
+
const pkg = JSON.parse(readFileSync4(join8(pkgRoot, "package.json"), "utf8"));
|
|
16408
16498
|
return typeof pkg.version === "string" ? pkg.version : "";
|
|
16409
16499
|
} catch {
|
|
16410
16500
|
return "";
|
|
@@ -16429,7 +16519,7 @@ function isNewer(candidate, current2) {
|
|
|
16429
16519
|
}
|
|
16430
16520
|
function dueForCheck(file3, now) {
|
|
16431
16521
|
try {
|
|
16432
|
-
const state = JSON.parse(
|
|
16522
|
+
const state = JSON.parse(readFileSync4(file3, "utf8"));
|
|
16433
16523
|
return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
|
|
16434
16524
|
} catch {
|
|
16435
16525
|
return true;
|
|
@@ -16438,7 +16528,7 @@ function dueForCheck(file3, now) {
|
|
|
16438
16528
|
var ORIGIN_FILE = ".install-origin.json";
|
|
16439
16529
|
function selfUpdatable(runtimeDir) {
|
|
16440
16530
|
try {
|
|
16441
|
-
const origin = JSON.parse(
|
|
16531
|
+
const origin = JSON.parse(readFileSync4(join8(runtimeDir, ORIGIN_FILE), "utf8"));
|
|
16442
16532
|
if (typeof origin.source !== "string" || !origin.source) return false;
|
|
16443
16533
|
return origin.source.split(/[\\/]/).includes("_npx");
|
|
16444
16534
|
} catch {
|
|
@@ -16451,7 +16541,7 @@ function lockFile() {
|
|
|
16451
16541
|
}
|
|
16452
16542
|
function acquireUpdateLock(file3, now) {
|
|
16453
16543
|
try {
|
|
16454
|
-
const held = JSON.parse(
|
|
16544
|
+
const held = JSON.parse(readFileSync4(file3, "utf8"));
|
|
16455
16545
|
if (held.ts && now - held.ts < LOCK_STALE_MS) {
|
|
16456
16546
|
let holderAlive = false;
|
|
16457
16547
|
if (held.pid) {
|
|
@@ -16492,6 +16582,9 @@ function stampCheck(file3, now, latest) {
|
|
|
16492
16582
|
} catch {
|
|
16493
16583
|
}
|
|
16494
16584
|
}
|
|
16585
|
+
function spawnNpm(spawnImpl, bin, args, opts) {
|
|
16586
|
+
return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
|
|
16587
|
+
}
|
|
16495
16588
|
async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
|
|
16496
16589
|
return new Promise((resolve3) => {
|
|
16497
16590
|
let out = "";
|
|
@@ -16505,7 +16598,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
|
|
|
16505
16598
|
resolve3(v);
|
|
16506
16599
|
};
|
|
16507
16600
|
try {
|
|
16508
|
-
const child = spawnImpl
|
|
16601
|
+
const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
|
|
16509
16602
|
timeout: NPM_VIEW_TIMEOUT_MS,
|
|
16510
16603
|
stdio: ["ignore", "pipe", "ignore"],
|
|
16511
16604
|
windowsHide: true
|
|
@@ -16574,7 +16667,8 @@ async function maybeAutoUpdate(cfg, opts = {}) {
|
|
|
16574
16667
|
return "";
|
|
16575
16668
|
}
|
|
16576
16669
|
log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
|
|
16577
|
-
const child = (
|
|
16670
|
+
const child = spawnNpm(
|
|
16671
|
+
opts.spawn ?? realSpawn2,
|
|
16578
16672
|
"npx",
|
|
16579
16673
|
["-y", `${PACKAGE_NAME}@${latest}`, "update"],
|
|
16580
16674
|
{
|
|
@@ -16607,7 +16701,10 @@ var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
|
16607
16701
|
var DAEMON_WAIT_RETAIN_MS = 4e4;
|
|
16608
16702
|
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
16609
16703
|
try {
|
|
16610
|
-
const res = await fetch(`${baseUrl}/health`, {
|
|
16704
|
+
const res = await fetch(`${baseUrl}/health`, {
|
|
16705
|
+
headers: { "User-Agent": USER_AGENT },
|
|
16706
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
16707
|
+
});
|
|
16611
16708
|
return res.ok;
|
|
16612
16709
|
} catch {
|
|
16613
16710
|
return false;
|
|
@@ -16817,20 +16914,46 @@ ${toolGuide(opts)}
|
|
|
16817
16914
|
}
|
|
16818
16915
|
|
|
16819
16916
|
// src/core/knowledge-tools.ts
|
|
16820
|
-
import { createHash as
|
|
16917
|
+
import { createHash as createHash4 } from "crypto";
|
|
16821
16918
|
import { existsSync as existsSync4 } from "fs";
|
|
16822
16919
|
import { homedir as homedir6 } from "os";
|
|
16823
16920
|
import { join as join12 } from "path";
|
|
16824
16921
|
|
|
16825
16922
|
// src/core/status.ts
|
|
16826
|
-
import { execFileSync as
|
|
16923
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
16827
16924
|
|
|
16828
16925
|
// src/core/git.ts
|
|
16829
16926
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
16830
16927
|
import { resolve as resolve2 } from "path";
|
|
16928
|
+
|
|
16929
|
+
// src/core/uuid.ts
|
|
16930
|
+
import { createHash as createHash2 } from "crypto";
|
|
16931
|
+
var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
|
|
16932
|
+
function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
|
|
16933
|
+
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
16934
|
+
if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
|
|
16935
|
+
const bytes = Buffer.from(
|
|
16936
|
+
createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
|
|
16937
|
+
);
|
|
16938
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
16939
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
16940
|
+
const hex5 = bytes.toString("hex");
|
|
16941
|
+
return [
|
|
16942
|
+
hex5.slice(0, 8),
|
|
16943
|
+
hex5.slice(8, 12),
|
|
16944
|
+
hex5.slice(12, 16),
|
|
16945
|
+
hex5.slice(16, 20),
|
|
16946
|
+
hex5.slice(20)
|
|
16947
|
+
].join("-");
|
|
16948
|
+
}
|
|
16949
|
+
|
|
16950
|
+
// src/core/git.ts
|
|
16951
|
+
var US = "";
|
|
16952
|
+
var RS = "";
|
|
16831
16953
|
var GITLOG_HEAD = "gitlog-head:";
|
|
16954
|
+
var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
|
|
16832
16955
|
function git(repo, ...args) {
|
|
16833
|
-
return execFileSync2("git", ["-C", repo, ...args], {
|
|
16956
|
+
return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
|
|
16834
16957
|
encoding: "utf8",
|
|
16835
16958
|
maxBuffer: 1 << 28,
|
|
16836
16959
|
windowsHide: true,
|
|
@@ -16876,8 +16999,8 @@ async function gitLogIsCurrent(client, repo, head) {
|
|
|
16876
16999
|
}
|
|
16877
17000
|
|
|
16878
17001
|
// src/core/survey.ts
|
|
16879
|
-
import { spawn as realSpawn5 } from "child_process";
|
|
16880
|
-
import { createHash as
|
|
17002
|
+
import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
|
|
17003
|
+
import { createHash as createHash3 } from "crypto";
|
|
16881
17004
|
import { existsSync as existsSync3 } from "fs";
|
|
16882
17005
|
import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
|
|
16883
17006
|
import { dirname as dirname7, join as join11 } from "path";
|
|
@@ -16985,6 +17108,19 @@ function resolveAgentBin(harness, claudeBin) {
|
|
|
16985
17108
|
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
16986
17109
|
}
|
|
16987
17110
|
}
|
|
17111
|
+
function opencodeCanDefineSurveyAgent(bin) {
|
|
17112
|
+
try {
|
|
17113
|
+
const out = execFileSync3(bin, ["--version"], {
|
|
17114
|
+
encoding: "utf8",
|
|
17115
|
+
timeout: 5e3,
|
|
17116
|
+
windowsHide: true,
|
|
17117
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
17118
|
+
});
|
|
17119
|
+
return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
|
|
17120
|
+
} catch {
|
|
17121
|
+
return false;
|
|
17122
|
+
}
|
|
17123
|
+
}
|
|
16988
17124
|
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.';
|
|
16989
17125
|
var SURVEY_DISALLOWED_TOOLS = [
|
|
16990
17126
|
"Bash",
|
|
@@ -17098,6 +17234,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
17098
17234
|
seen.add(harness);
|
|
17099
17235
|
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
17100
17236
|
if (!exists(bin)) continue;
|
|
17237
|
+
if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
|
|
17238
|
+
continue;
|
|
17101
17239
|
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
17102
17240
|
model: opts.model,
|
|
17103
17241
|
budgetUsd: opts.budgetUsd,
|
|
@@ -17105,7 +17243,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
17105
17243
|
});
|
|
17106
17244
|
const { cfg, bankId } = resolveHostConfig(harness, repoDir);
|
|
17107
17245
|
if (cfg.disabled) return false;
|
|
17108
|
-
const key =
|
|
17246
|
+
const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
|
|
17109
17247
|
const lease = acquireLease(
|
|
17110
17248
|
opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
|
|
17111
17249
|
key,
|
|
@@ -17154,7 +17292,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
17154
17292
|
var DEEPEN_DIFF_TARGET = 300;
|
|
17155
17293
|
function commitCount(repoDir) {
|
|
17156
17294
|
try {
|
|
17157
|
-
const out =
|
|
17295
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
17158
17296
|
encoding: "utf8",
|
|
17159
17297
|
windowsHide: true,
|
|
17160
17298
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17378,7 +17516,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17378
17516
|
annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
|
|
17379
17517
|
handler: guarded(async ({ title, content }) => {
|
|
17380
17518
|
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
17381
|
-
const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${
|
|
17519
|
+
const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
|
|
17382
17520
|
const stamp = opts.stampFor?.();
|
|
17383
17521
|
const metadata = {
|
|
17384
17522
|
...stamp?.metadata,
|
|
@@ -17405,7 +17543,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
17405
17543
|
}
|
|
17406
17544
|
|
|
17407
17545
|
// src/core/retain-cursor.ts
|
|
17408
|
-
import { createHash as
|
|
17546
|
+
import { createHash as createHash5 } from "crypto";
|
|
17409
17547
|
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
17410
17548
|
var PENDING_MAX_BYTES = 256 * 1024;
|
|
17411
17549
|
var MAX_CURSOR_PATHS = 16;
|
|
@@ -17419,8 +17557,9 @@ function pendingReplayable(cursor, now) {
|
|
|
17419
17557
|
if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
|
|
17420
17558
|
return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
|
|
17421
17559
|
}
|
|
17560
|
+
var MAX_CURSOR_OPS = 8;
|
|
17422
17561
|
function fingerprintTurns(turns, count) {
|
|
17423
|
-
const h =
|
|
17562
|
+
const h = createHash5("sha1").update(String(count));
|
|
17424
17563
|
for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
|
|
17425
17564
|
return h.digest("hex");
|
|
17426
17565
|
}
|
|
@@ -17444,27 +17583,6 @@ function memoryCursorStore() {
|
|
|
17444
17583
|
};
|
|
17445
17584
|
}
|
|
17446
17585
|
|
|
17447
|
-
// src/core/uuid.ts
|
|
17448
|
-
import { createHash as createHash5 } from "crypto";
|
|
17449
|
-
var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
|
|
17450
|
-
function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
|
|
17451
|
-
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
17452
|
-
if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
|
|
17453
|
-
const bytes = Buffer.from(
|
|
17454
|
-
createHash5("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
|
|
17455
|
-
);
|
|
17456
|
-
bytes[6] = bytes[6] & 15 | 80;
|
|
17457
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
17458
|
-
const hex5 = bytes.toString("hex");
|
|
17459
|
-
return [
|
|
17460
|
-
hex5.slice(0, 8),
|
|
17461
|
-
hex5.slice(8, 12),
|
|
17462
|
-
hex5.slice(12, 16),
|
|
17463
|
-
hex5.slice(16, 20),
|
|
17464
|
-
hex5.slice(20)
|
|
17465
|
-
].join("-");
|
|
17466
|
-
}
|
|
17467
|
-
|
|
17468
17586
|
// src/core/chat.ts
|
|
17469
17587
|
function withRefId(refId, turns, baseTs) {
|
|
17470
17588
|
return [{ role: "system", content: `REF-ID: ${refId}`, timestamp: baseTs }, ...turns];
|
|
@@ -17479,6 +17597,31 @@ async function supportsAppend(client) {
|
|
|
17479
17597
|
return false;
|
|
17480
17598
|
}
|
|
17481
17599
|
}
|
|
17600
|
+
var OP_CHECK_TIMEOUT_MS = 5e3;
|
|
17601
|
+
var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
|
|
17602
|
+
async function settleOps(client, cursor) {
|
|
17603
|
+
const ops = cursor.ops ?? [];
|
|
17604
|
+
const statuses = await Promise.all(
|
|
17605
|
+
ops.map(async (id) => {
|
|
17606
|
+
try {
|
|
17607
|
+
const r = await client.req(
|
|
17608
|
+
"GET",
|
|
17609
|
+
client.bankUrl(`/operations/${encodeURIComponent(id)}`),
|
|
17610
|
+
void 0,
|
|
17611
|
+
[],
|
|
17612
|
+
OP_CHECK_TIMEOUT_MS
|
|
17613
|
+
);
|
|
17614
|
+
if (r.status === 404) return "not_found";
|
|
17615
|
+
return String((await r.json()).status ?? "").toLowerCase();
|
|
17616
|
+
} catch {
|
|
17617
|
+
return "";
|
|
17618
|
+
}
|
|
17619
|
+
})
|
|
17620
|
+
);
|
|
17621
|
+
const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
|
|
17622
|
+
const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
|
|
17623
|
+
return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
|
|
17624
|
+
}
|
|
17482
17625
|
var DEFAULT_RETRY_WINDOW_MS = 6e4;
|
|
17483
17626
|
var RETAIN_RETRY_ATTEMPTS = 2;
|
|
17484
17627
|
var REQUEST_BUDGET_MS = 15e3;
|
|
@@ -17542,13 +17685,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
|
|
|
17542
17685
|
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
|
|
17543
17686
|
if (!turns.length) return;
|
|
17544
17687
|
const refId = `conversation:${sessionId}`;
|
|
17545
|
-
|
|
17688
|
+
let cursor = cursors?.read(sessionId);
|
|
17689
|
+
const probed = Boolean(cursors) && cursor?.appendSupported !== true;
|
|
17546
17690
|
const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
|
|
17691
|
+
let ops = [];
|
|
17692
|
+
if (appendSupported && cursor?.ops?.length && !cursor.dirty)
|
|
17693
|
+
({ cursor, ops } = await settleOps(client, cursor));
|
|
17547
17694
|
const plan = planRetain(turns, cursor, {
|
|
17548
17695
|
appendSupported,
|
|
17549
17696
|
bank: client.bank,
|
|
17550
17697
|
path: transcriptPath
|
|
17551
17698
|
});
|
|
17699
|
+
if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
|
|
17552
17700
|
const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
|
|
17553
17701
|
const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
|
|
17554
17702
|
if (plan.mode === "skip" && !outbox.length) return;
|
|
@@ -17594,6 +17742,10 @@ ${content}`);
|
|
|
17594
17742
|
...paths ? { paths } : {},
|
|
17595
17743
|
...appendSupported ? { appendSupported: true } : {}
|
|
17596
17744
|
};
|
|
17745
|
+
const accepted = (id) => {
|
|
17746
|
+
if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
|
|
17747
|
+
return ops.length ? { ...next, ops } : next;
|
|
17748
|
+
};
|
|
17597
17749
|
const stillOurs = () => {
|
|
17598
17750
|
if (!cursors) return true;
|
|
17599
17751
|
const now = cursors.read(sessionId);
|
|
@@ -17602,12 +17754,10 @@ ${content}`);
|
|
|
17602
17754
|
if (plan.mode === "replace") {
|
|
17603
17755
|
const content = renderSessionJsonl(refId, turns, startTs);
|
|
17604
17756
|
cursors?.write(sessionId, { ...next, dirty: true });
|
|
17605
|
-
|
|
17606
|
-
|
|
17607
|
-
|
|
17608
|
-
|
|
17609
|
-
);
|
|
17610
|
-
cursors?.write(sessionId, next);
|
|
17757
|
+
const operationId = opId("replace", content);
|
|
17758
|
+
await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
|
|
17759
|
+
ops = [];
|
|
17760
|
+
cursors?.write(sessionId, accepted(operationId));
|
|
17611
17761
|
return;
|
|
17612
17762
|
}
|
|
17613
17763
|
const queue = [...outbox];
|
|
@@ -17615,7 +17765,7 @@ ${content}`);
|
|
|
17615
17765
|
const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
|
|
17616
17766
|
queue.push({ content, operationId: opId("append", content), at: Date.now() });
|
|
17617
17767
|
}
|
|
17618
|
-
cursors?.write(sessionId, { ...
|
|
17768
|
+
cursors?.write(sessionId, { ...accepted(), pending: queue });
|
|
17619
17769
|
for (let i = 0; i < queue.length; i++) {
|
|
17620
17770
|
if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
|
|
17621
17771
|
const entry = queue[i];
|
|
@@ -17625,12 +17775,13 @@ ${content}`);
|
|
|
17625
17775
|
retryUntil
|
|
17626
17776
|
);
|
|
17627
17777
|
const remaining = queue.slice(i + 1);
|
|
17628
|
-
|
|
17778
|
+
const done = accepted(entry.operationId);
|
|
17779
|
+
cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
|
|
17629
17780
|
}
|
|
17630
17781
|
}
|
|
17631
17782
|
|
|
17632
17783
|
// src/core/usage.ts
|
|
17633
|
-
import { readFileSync as
|
|
17784
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
17634
17785
|
import { join as join13 } from "path";
|
|
17635
17786
|
function usageFilePath() {
|
|
17636
17787
|
return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
|
|
@@ -17737,11 +17888,8 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
17737
17888
|
return { tags, metadata, context };
|
|
17738
17889
|
}
|
|
17739
17890
|
|
|
17740
|
-
// src/core/session-start.ts
|
|
17741
|
-
import { readFileSync as readFileSync8 } from "fs";
|
|
17742
|
-
|
|
17743
17891
|
// src/core/skill-sync.ts
|
|
17744
|
-
import { cpSync, existsSync as existsSync6, readFileSync as
|
|
17892
|
+
import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
17745
17893
|
import { homedir as homedir7 } from "os";
|
|
17746
17894
|
import { dirname as dirname8, join as join15 } from "path";
|
|
17747
17895
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
@@ -17777,7 +17925,12 @@ var SKILL_DIRS = {
|
|
|
17777
17925
|
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
17778
17926
|
// and dsh's copy with it.
|
|
17779
17927
|
pi: [".pi", "agent", "skills"],
|
|
17780
|
-
"prime-agent": [".prime", "agent", "skills"]
|
|
17928
|
+
"prime-agent": [".prime", "agent", "skills"],
|
|
17929
|
+
// WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
|
|
17930
|
+
workbuddy: [".workbuddy", "skills"],
|
|
17931
|
+
// CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
|
|
17932
|
+
// its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
|
|
17933
|
+
codebuddy: [".codebuddy", "skills"]
|
|
17781
17934
|
};
|
|
17782
17935
|
var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
|
|
17783
17936
|
var traecodeDotDirName = (home, exists = existsSync5) => {
|
|
@@ -17811,7 +17964,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
17811
17964
|
const dstMd = join15(dst, "SKILL.md");
|
|
17812
17965
|
const installed = existsSync6(dstMd);
|
|
17813
17966
|
if (!installed && !opts.install) return;
|
|
17814
|
-
if (!installed ||
|
|
17967
|
+
if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
|
|
17815
17968
|
cpSync(src, dst, { recursive: true });
|
|
17816
17969
|
}
|
|
17817
17970
|
} catch {
|
|
@@ -17820,7 +17973,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
17820
17973
|
function readPackagedSkill(srcDir = packagedSkillDir()) {
|
|
17821
17974
|
try {
|
|
17822
17975
|
const path = join15(srcDir, "SKILL.md");
|
|
17823
|
-
const raw =
|
|
17976
|
+
const raw = readFileSync6(path, "utf8");
|
|
17824
17977
|
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
|
|
17825
17978
|
return {
|
|
17826
17979
|
location: srcDir,
|
|
@@ -17848,7 +18001,7 @@ function brandWord() {
|
|
|
17848
18001
|
}
|
|
17849
18002
|
|
|
17850
18003
|
// src/core/legacy.ts
|
|
17851
|
-
import { existsSync as existsSync7, readFileSync as
|
|
18004
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
|
|
17852
18005
|
import { homedir as homedir8 } from "os";
|
|
17853
18006
|
import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
|
|
17854
18007
|
var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
|
|
@@ -17873,7 +18026,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
|
|
|
17873
18026
|
}
|
|
17874
18027
|
function readJson(path) {
|
|
17875
18028
|
try {
|
|
17876
|
-
const parsed = JSON.parse(
|
|
18029
|
+
const parsed = JSON.parse(readFileSync7(path, "utf8"));
|
|
17877
18030
|
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
17878
18031
|
} catch {
|
|
17879
18032
|
return void 0;
|
|
@@ -17885,7 +18038,7 @@ function legacyClaudePluginWarning(key) {
|
|
|
17885
18038
|
}
|
|
17886
18039
|
|
|
17887
18040
|
// src/core/session-cache.ts
|
|
17888
|
-
import { mkdirSync as mkdirSync4, readFileSync as
|
|
18041
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
17889
18042
|
import { tmpdir as tmpdir3 } from "os";
|
|
17890
18043
|
import { dirname as dirname9, join as join17 } from "path";
|
|
17891
18044
|
function sessionCacheFile(harness, sessionId) {
|
|
@@ -17893,7 +18046,7 @@ function sessionCacheFile(harness, sessionId) {
|
|
|
17893
18046
|
}
|
|
17894
18047
|
function readSessionCache(cacheFile) {
|
|
17895
18048
|
try {
|
|
17896
|
-
return JSON.parse(
|
|
18049
|
+
return JSON.parse(readFileSync8(cacheFile, "utf8"));
|
|
17897
18050
|
} catch {
|
|
17898
18051
|
return {};
|
|
17899
18052
|
}
|
|
@@ -17937,9 +18090,9 @@ async function gitSyncNote(args) {
|
|
|
17937
18090
|
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
17938
18091
|
let target = DEEPEN_DIFF_TARGET;
|
|
17939
18092
|
try {
|
|
17940
|
-
const { execFileSync:
|
|
18093
|
+
const { execFileSync: execFileSync5 } = await import("child_process");
|
|
17941
18094
|
const n = Number(
|
|
17942
|
-
|
|
18095
|
+
execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
17943
18096
|
encoding: "utf8",
|
|
17944
18097
|
windowsHide: true,
|
|
17945
18098
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17956,6 +18109,7 @@ async function buildSessionStartContext(args) {
|
|
|
17956
18109
|
const t0 = Date.now();
|
|
17957
18110
|
let cold;
|
|
17958
18111
|
let gitDocIds;
|
|
18112
|
+
let bankEmpty = false;
|
|
17959
18113
|
const harness = args.harness ?? "claude-code";
|
|
17960
18114
|
const hasGit = args.hasGit ?? hasGitHistory;
|
|
17961
18115
|
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
@@ -17995,11 +18149,21 @@ async function buildSessionStartContext(args) {
|
|
|
17995
18149
|
} catch {
|
|
17996
18150
|
docIds = void 0;
|
|
17997
18151
|
}
|
|
17998
|
-
|
|
18152
|
+
let baselines;
|
|
18153
|
+
if (docIds?.size === 0) {
|
|
18154
|
+
baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
|
|
18155
|
+
}
|
|
18156
|
+
cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
|
|
17999
18157
|
gitDocIds = docIds;
|
|
18158
|
+
if (cold === true && client.hasDocuments) {
|
|
18159
|
+
bankEmpty = await client.hasDocuments().then(
|
|
18160
|
+
(has) => !has,
|
|
18161
|
+
() => false
|
|
18162
|
+
);
|
|
18163
|
+
}
|
|
18000
18164
|
if (docIds !== void 0) {
|
|
18001
18165
|
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
18002
|
-
if (
|
|
18166
|
+
if (cold) {
|
|
18003
18167
|
if (cfg.codebaseSurvey !== false) {
|
|
18004
18168
|
const started = await startSurvey(cwd, {
|
|
18005
18169
|
harness,
|
|
@@ -18013,7 +18177,7 @@ async function buildSessionStartContext(args) {
|
|
|
18013
18177
|
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
18014
18178
|
const sha = resolveHeadSha(cwd);
|
|
18015
18179
|
if (sha) {
|
|
18016
|
-
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18180
|
+
const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18017
18181
|
const counts = [];
|
|
18018
18182
|
for (const id of markers) {
|
|
18019
18183
|
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
@@ -18047,10 +18211,8 @@ async function buildSessionStartContext(args) {
|
|
|
18047
18211
|
}
|
|
18048
18212
|
}
|
|
18049
18213
|
let pages = [];
|
|
18050
|
-
let pageListKnown = false;
|
|
18051
18214
|
try {
|
|
18052
18215
|
pages = parsePageList(await client.listPages());
|
|
18053
|
-
pageListKnown = true;
|
|
18054
18216
|
} catch {
|
|
18055
18217
|
if (client.knowledgePagesSupported === false) {
|
|
18056
18218
|
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
@@ -18060,7 +18222,7 @@ async function buildSessionStartContext(args) {
|
|
|
18060
18222
|
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18061
18223
|
extra: cfg.toolGuideExtra
|
|
18062
18224
|
});
|
|
18063
|
-
const deferInitialReflect =
|
|
18225
|
+
const deferInitialReflect = bankEmpty;
|
|
18064
18226
|
let gitNote;
|
|
18065
18227
|
if (gitDocIds) {
|
|
18066
18228
|
gitNote = await gitSyncNote({
|
|
@@ -18084,7 +18246,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
|
|
|
18084
18246
|
}
|
|
18085
18247
|
|
|
18086
18248
|
// src/core/hook.ts
|
|
18087
|
-
import { existsSync as existsSync8
|
|
18249
|
+
import { existsSync as existsSync8 } from "fs";
|
|
18088
18250
|
|
|
18089
18251
|
// src/core/inject.ts
|
|
18090
18252
|
function buildReflectQuery(prompt) {
|
|
@@ -18175,9 +18337,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
|
18175
18337
|
|
|
18176
18338
|
// src/core/hook.ts
|
|
18177
18339
|
var HOOK_INJECT_ATTEMPTS = 2;
|
|
18340
|
+
var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
|
|
18178
18341
|
function resolveInjection(got, attempts) {
|
|
18179
18342
|
if (got != null) return got;
|
|
18180
|
-
|
|
18343
|
+
const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
|
|
18344
|
+
return attempts >= budget ? "" : void 0;
|
|
18345
|
+
}
|
|
18346
|
+
var RECALL_QUERY_MAX_TOKENS = 500;
|
|
18347
|
+
function boundRecallQuery(prompt) {
|
|
18348
|
+
let cost = 0;
|
|
18349
|
+
let end = 0;
|
|
18350
|
+
for (const ch of prompt) {
|
|
18351
|
+
const cp = ch.codePointAt(0);
|
|
18352
|
+
cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
|
|
18353
|
+
if (cost > RECALL_QUERY_MAX_TOKENS) break;
|
|
18354
|
+
end += ch.length;
|
|
18355
|
+
}
|
|
18356
|
+
return prompt.slice(0, end);
|
|
18181
18357
|
}
|
|
18182
18358
|
async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
18183
18359
|
const t0 = Date.now();
|
|
@@ -18193,7 +18369,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
18193
18369
|
async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
18194
18370
|
const t0 = Date.now();
|
|
18195
18371
|
try {
|
|
18196
|
-
const observations = await client.recallObservations(prompt
|
|
18372
|
+
const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
|
|
18197
18373
|
diag(harness, event, { ms: Date.now() - t0, count: observations.length });
|
|
18198
18374
|
return observations.length ? formatRecallFallback(observations, lead) : null;
|
|
18199
18375
|
} catch (e) {
|
|
@@ -18268,7 +18444,7 @@ async function buildHookOutput(args) {
|
|
|
18268
18444
|
answer: reflectAnswer.slice(0, 8e3)
|
|
18269
18445
|
});
|
|
18270
18446
|
} catch (e) {
|
|
18271
|
-
reflectAnswer = resolveInjection(void 0, reflectAttempts);
|
|
18447
|
+
reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
|
|
18272
18448
|
reflectFailed = true;
|
|
18273
18449
|
log.warn(harness, "reflect failed \u2014 session runs without memory", {
|
|
18274
18450
|
error: describeError(e)
|
|
@@ -18340,6 +18516,7 @@ async function buildHookOutput(args) {
|
|
|
18340
18516
|
|
|
18341
18517
|
// src/core/runtime.ts
|
|
18342
18518
|
var HARNESS = "opencode";
|
|
18519
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
18343
18520
|
var RuntimeCore = class {
|
|
18344
18521
|
constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
|
|
18345
18522
|
this.client = client;
|
|
@@ -18365,6 +18542,8 @@ var RuntimeCore = class {
|
|
|
18365
18542
|
usageCursors = memoryUsageCursorStore();
|
|
18366
18543
|
/** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
|
|
18367
18544
|
fetchTranscript;
|
|
18545
|
+
/** Write-backs started and not yet settled — what `flush` waits for. */
|
|
18546
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
18368
18547
|
lastInjection = "";
|
|
18369
18548
|
// most recent turn's injection block, keyed by nothing (see getInjection)
|
|
18370
18549
|
deferInitialReflect = false;
|
|
@@ -18497,8 +18676,9 @@ var RuntimeCore = class {
|
|
|
18497
18676
|
*/
|
|
18498
18677
|
async onTranscript(sessionId, turns, lastTurnComplete) {
|
|
18499
18678
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18500
|
-
if (!
|
|
18679
|
+
if (!sessionId || !turns.length) return;
|
|
18501
18680
|
this.recordUsage(sessionId, turns, lastTurnComplete);
|
|
18681
|
+
if (!this.writeBackEnabled) return;
|
|
18502
18682
|
const st = this.stateFor(sessionId);
|
|
18503
18683
|
this.retain(sessionId, turns, st.startTs);
|
|
18504
18684
|
}
|
|
@@ -18516,7 +18696,7 @@ var RuntimeCore = class {
|
|
|
18516
18696
|
*/
|
|
18517
18697
|
async onSessionIdle(sessionId) {
|
|
18518
18698
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18519
|
-
if (!
|
|
18699
|
+
if (!sessionId || !this.fetchTranscript) return;
|
|
18520
18700
|
let turns;
|
|
18521
18701
|
try {
|
|
18522
18702
|
turns = await this.fetchTranscript(sessionId);
|
|
@@ -18529,6 +18709,7 @@ var RuntimeCore = class {
|
|
|
18529
18709
|
}
|
|
18530
18710
|
if (!turns.length) return;
|
|
18531
18711
|
this.recordUsage(sessionId, turns, true);
|
|
18712
|
+
if (!this.writeBackEnabled) return;
|
|
18532
18713
|
const st = this.stateFor(sessionId);
|
|
18533
18714
|
if (turns.length <= st.retainedTurns) return;
|
|
18534
18715
|
st.retainedTurns = turns.length;
|
|
@@ -18556,10 +18737,27 @@ var RuntimeCore = class {
|
|
|
18556
18737
|
}
|
|
18557
18738
|
return st;
|
|
18558
18739
|
}
|
|
18740
|
+
/**
|
|
18741
|
+
* Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
|
|
18742
|
+
* so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
|
|
18743
|
+
* calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
|
|
18744
|
+
* stalled server cannot hold the host's exit open. Never throws.
|
|
18745
|
+
*/
|
|
18746
|
+
async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
18747
|
+
if (!this.inFlight.size) return;
|
|
18748
|
+
let timer;
|
|
18749
|
+
await Promise.race([
|
|
18750
|
+
Promise.all(this.inFlight),
|
|
18751
|
+
new Promise((r) => {
|
|
18752
|
+
timer = setTimeout(r, timeoutMs);
|
|
18753
|
+
})
|
|
18754
|
+
]);
|
|
18755
|
+
clearTimeout(timer);
|
|
18756
|
+
}
|
|
18559
18757
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
18560
18758
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
18561
18759
|
const t0 = Date.now();
|
|
18562
|
-
|
|
18760
|
+
const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
18563
18761
|
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
18564
18762
|
cursors: this.cursors,
|
|
18565
18763
|
stamp: buildRetainStamp(this.cfg, {
|
|
@@ -18584,6 +18782,8 @@ var RuntimeCore = class {
|
|
|
18584
18782
|
trigger
|
|
18585
18783
|
})
|
|
18586
18784
|
);
|
|
18785
|
+
this.inFlight.add(write2);
|
|
18786
|
+
void write2.finally(() => this.inFlight.delete(write2));
|
|
18587
18787
|
}
|
|
18588
18788
|
};
|
|
18589
18789
|
|
|
@@ -19106,7 +19306,7 @@ __export(core_exports4, {
|
|
|
19106
19306
|
toJSONSchema: () => toJSONSchema2,
|
|
19107
19307
|
treeifyError: () => treeifyError2,
|
|
19108
19308
|
util: () => util_exports2,
|
|
19109
|
-
version: () =>
|
|
19309
|
+
version: () => version3
|
|
19110
19310
|
});
|
|
19111
19311
|
|
|
19112
19312
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
|
|
@@ -20109,10 +20309,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
20109
20309
|
var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
20110
20310
|
var extendedDuration2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
|
20111
20311
|
var guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
20112
|
-
var uuid3 = (
|
|
20113
|
-
if (!
|
|
20312
|
+
var uuid3 = (version4) => {
|
|
20313
|
+
if (!version4)
|
|
20114
20314
|
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)$/;
|
|
20115
|
-
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${
|
|
20315
|
+
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
20116
20316
|
};
|
|
20117
20317
|
var uuid42 = /* @__PURE__ */ uuid3(4);
|
|
20118
20318
|
var uuid62 = /* @__PURE__ */ uuid3(6);
|
|
@@ -20770,7 +20970,7 @@ var Doc2 = class {
|
|
|
20770
20970
|
};
|
|
20771
20971
|
|
|
20772
20972
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
|
|
20773
|
-
var
|
|
20973
|
+
var version3 = {
|
|
20774
20974
|
major: 4,
|
|
20775
20975
|
minor: 1,
|
|
20776
20976
|
patch: 8
|
|
@@ -20782,7 +20982,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
|
|
|
20782
20982
|
inst ?? (inst = {});
|
|
20783
20983
|
inst._zod.def = def;
|
|
20784
20984
|
inst._zod.bag = inst._zod.bag || {};
|
|
20785
|
-
inst._zod.version =
|
|
20985
|
+
inst._zod.version = version3;
|
|
20786
20986
|
const checks = [...inst._zod.def.checks ?? []];
|
|
20787
20987
|
if (inst._zod.traits.has("$ZodCheck")) {
|
|
20788
20988
|
checks.unshift(inst);
|
|
@@ -31038,12 +31238,12 @@ function tool(input) {
|
|
|
31038
31238
|
tool.schema = external_exports2;
|
|
31039
31239
|
|
|
31040
31240
|
// src/harness/registry.ts
|
|
31041
|
-
import { readFileSync as
|
|
31241
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
31042
31242
|
var jsonChatReader = (harness) => ({
|
|
31043
31243
|
describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
|
|
31044
31244
|
async read(opts) {
|
|
31045
31245
|
if (!opts.conversations) return [];
|
|
31046
|
-
return JSON.parse(
|
|
31246
|
+
return JSON.parse(readFileSync10(opts.conversations, "utf8"));
|
|
31047
31247
|
}
|
|
31048
31248
|
});
|
|
31049
31249
|
|