@vectorize-io/hindsight-coding-agents 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -6
- package/dist/antigravity-hook.js +441 -80
- package/dist/antigravity-statusline.js +9 -4
- package/dist/antigravity-stop-hook.js +441 -95
- package/dist/claude-hook.js +441 -80
- package/dist/claude-sessionstart-hook.js +473 -93
- package/dist/claude-stop-hook.js +441 -95
- package/dist/cline.js +290 -95
- package/dist/codebuddy-hook.js +4270 -0
- package/dist/codebuddy-sessionstart-hook.js +5030 -0
- package/dist/codebuddy-stop-hook.js +4564 -0
- package/dist/codex-hook.js +441 -80
- package/dist/codex-sessionstart-hook.js +473 -93
- package/dist/codex-stop-hook.js +441 -95
- package/dist/copilot-hook.js +441 -80
- package/dist/copilot-sessionstart-hook.js +473 -93
- package/dist/copilot-stop-hook.js +441 -95
- package/dist/cursor-hook.js +441 -80
- package/dist/cursor-sessionstart-hook.js +473 -93
- package/dist/cursor-stop-hook.js +441 -95
- package/dist/daemon-start.js +16 -8
- package/dist/dcode-hook.js +441 -80
- package/dist/dcode-sessionstart-hook.js +473 -93
- package/dist/dcode-stop-hook.js +441 -95
- package/dist/deepen.js +140 -49
- package/dist/devin-hook.js +441 -80
- package/dist/devin-sessionstart-hook.js +473 -93
- package/dist/devin-stop-hook.js +441 -95
- package/dist/droid-hook.js +441 -80
- package/dist/droid-sessionstart-hook.js +473 -93
- package/dist/droid-stop-hook.js +441 -95
- package/dist/dsh.js +297 -95
- package/dist/grok-hook.js +441 -80
- package/dist/grok-sessionstart-hook.js +473 -93
- package/dist/grok-stop-hook.js +441 -95
- package/dist/hindsight-seed.js +9 -4
- package/dist/index.js +299 -104
- package/dist/installer.js +1043 -647
- package/dist/kilo.js +299 -104
- package/dist/kimi-hook.js +441 -80
- package/dist/kimi-sessionstart-hook.js +473 -93
- package/dist/kimi-stop-hook.js +441 -95
- package/dist/mcp-server.js +261 -86
- package/dist/opencode2.js +296 -101
- package/dist/pi.js +352 -107
- package/dist/prime-agent.js +352 -107
- package/dist/qwen-hook.js +441 -80
- package/dist/qwen-sessionstart-hook.js +473 -93
- package/dist/qwen-stop-hook.js +441 -95
- package/dist/status.js +115 -42
- package/dist/traecode-hook.js +441 -80
- package/dist/traecode-sessionstart-hook.js +473 -93
- package/dist/traecode-stop-hook.js +441 -95
- package/dist/workbuddy-hook.js +4270 -0
- package/dist/workbuddy-sessionstart-hook.js +5030 -0
- package/dist/workbuddy-stop-hook.js +4564 -0
- package/dist/zcode-hook.js +441 -80
- package/dist/zcode-sessionstart-hook.js +473 -93
- package/dist/zcode-stop-hook.js +441 -95
- package/package.json +9 -3
- package/plugin.json +1 -1
- package/skill/SKILL.md +4 -4
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.1";
|
|
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;
|
|
@@ -16823,14 +16920,14 @@ 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";
|
|
16831
16928
|
var GITLOG_HEAD = "gitlog-head:";
|
|
16832
16929
|
function git(repo, ...args) {
|
|
16833
|
-
return execFileSync2("git", ["-C", repo, ...args], {
|
|
16930
|
+
return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
|
|
16834
16931
|
encoding: "utf8",
|
|
16835
16932
|
maxBuffer: 1 << 28,
|
|
16836
16933
|
windowsHide: true,
|
|
@@ -16876,7 +16973,7 @@ async function gitLogIsCurrent(client, repo, head) {
|
|
|
16876
16973
|
}
|
|
16877
16974
|
|
|
16878
16975
|
// src/core/survey.ts
|
|
16879
|
-
import { spawn as realSpawn5 } from "child_process";
|
|
16976
|
+
import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
|
|
16880
16977
|
import { createHash as createHash2 } from "crypto";
|
|
16881
16978
|
import { existsSync as existsSync3 } from "fs";
|
|
16882
16979
|
import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
|
|
@@ -16985,6 +17082,19 @@ function resolveAgentBin(harness, claudeBin) {
|
|
|
16985
17082
|
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
16986
17083
|
}
|
|
16987
17084
|
}
|
|
17085
|
+
function opencodeCanDefineSurveyAgent(bin) {
|
|
17086
|
+
try {
|
|
17087
|
+
const out = execFileSync3(bin, ["--version"], {
|
|
17088
|
+
encoding: "utf8",
|
|
17089
|
+
timeout: 5e3,
|
|
17090
|
+
windowsHide: true,
|
|
17091
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
17092
|
+
});
|
|
17093
|
+
return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
|
|
17094
|
+
} catch {
|
|
17095
|
+
return false;
|
|
17096
|
+
}
|
|
17097
|
+
}
|
|
16988
17098
|
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
17099
|
var SURVEY_DISALLOWED_TOOLS = [
|
|
16990
17100
|
"Bash",
|
|
@@ -17098,6 +17208,8 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
17098
17208
|
seen.add(harness);
|
|
17099
17209
|
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
17100
17210
|
if (!exists(bin)) continue;
|
|
17211
|
+
if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
|
|
17212
|
+
continue;
|
|
17101
17213
|
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
17102
17214
|
model: opts.model,
|
|
17103
17215
|
budgetUsd: opts.budgetUsd,
|
|
@@ -17154,7 +17266,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
17154
17266
|
var DEEPEN_DIFF_TARGET = 300;
|
|
17155
17267
|
function commitCount(repoDir) {
|
|
17156
17268
|
try {
|
|
17157
|
-
const out =
|
|
17269
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
17158
17270
|
encoding: "utf8",
|
|
17159
17271
|
windowsHide: true,
|
|
17160
17272
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17419,6 +17531,7 @@ function pendingReplayable(cursor, now) {
|
|
|
17419
17531
|
if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
|
|
17420
17532
|
return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
|
|
17421
17533
|
}
|
|
17534
|
+
var MAX_CURSOR_OPS = 8;
|
|
17422
17535
|
function fingerprintTurns(turns, count) {
|
|
17423
17536
|
const h = createHash4("sha1").update(String(count));
|
|
17424
17537
|
for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
|
|
@@ -17479,6 +17592,31 @@ async function supportsAppend(client) {
|
|
|
17479
17592
|
return false;
|
|
17480
17593
|
}
|
|
17481
17594
|
}
|
|
17595
|
+
var OP_CHECK_TIMEOUT_MS = 5e3;
|
|
17596
|
+
var LOST_OP_STATUSES = /* @__PURE__ */ new Set(["failed", "cancelled", "error"]);
|
|
17597
|
+
async function settleOps(client, cursor) {
|
|
17598
|
+
const ops = cursor.ops ?? [];
|
|
17599
|
+
const statuses = await Promise.all(
|
|
17600
|
+
ops.map(async (id) => {
|
|
17601
|
+
try {
|
|
17602
|
+
const r = await client.req(
|
|
17603
|
+
"GET",
|
|
17604
|
+
client.bankUrl(`/operations/${encodeURIComponent(id)}`),
|
|
17605
|
+
void 0,
|
|
17606
|
+
[],
|
|
17607
|
+
OP_CHECK_TIMEOUT_MS
|
|
17608
|
+
);
|
|
17609
|
+
if (r.status === 404) return "not_found";
|
|
17610
|
+
return String((await r.json()).status ?? "").toLowerCase();
|
|
17611
|
+
} catch {
|
|
17612
|
+
return "";
|
|
17613
|
+
}
|
|
17614
|
+
})
|
|
17615
|
+
);
|
|
17616
|
+
const lost = statuses.some((s) => LOST_OP_STATUSES.has(s));
|
|
17617
|
+
const open = ops.filter((_, i) => !["completed", "not_found"].includes(statuses[i]));
|
|
17618
|
+
return { cursor: lost ? { ...cursor, dirty: true } : cursor, ops: lost ? [] : open };
|
|
17619
|
+
}
|
|
17482
17620
|
var DEFAULT_RETRY_WINDOW_MS = 6e4;
|
|
17483
17621
|
var RETAIN_RETRY_ATTEMPTS = 2;
|
|
17484
17622
|
var REQUEST_BUDGET_MS = 15e3;
|
|
@@ -17542,13 +17680,18 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
|
|
|
17542
17680
|
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS, transcriptPath) {
|
|
17543
17681
|
if (!turns.length) return;
|
|
17544
17682
|
const refId = `conversation:${sessionId}`;
|
|
17545
|
-
|
|
17683
|
+
let cursor = cursors?.read(sessionId);
|
|
17684
|
+
const probed = Boolean(cursors) && cursor?.appendSupported !== true;
|
|
17546
17685
|
const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
|
|
17686
|
+
let ops = [];
|
|
17687
|
+
if (appendSupported && cursor?.ops?.length && !cursor.dirty)
|
|
17688
|
+
({ cursor, ops } = await settleOps(client, cursor));
|
|
17547
17689
|
const plan = planRetain(turns, cursor, {
|
|
17548
17690
|
appendSupported,
|
|
17549
17691
|
bank: client.bank,
|
|
17550
17692
|
path: transcriptPath
|
|
17551
17693
|
});
|
|
17694
|
+
if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
|
|
17552
17695
|
const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
|
|
17553
17696
|
const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
|
|
17554
17697
|
if (plan.mode === "skip" && !outbox.length) return;
|
|
@@ -17594,6 +17737,10 @@ ${content}`);
|
|
|
17594
17737
|
...paths ? { paths } : {},
|
|
17595
17738
|
...appendSupported ? { appendSupported: true } : {}
|
|
17596
17739
|
};
|
|
17740
|
+
const accepted = (id) => {
|
|
17741
|
+
if (id) ops = [...ops, id].slice(-MAX_CURSOR_OPS);
|
|
17742
|
+
return ops.length ? { ...next, ops } : next;
|
|
17743
|
+
};
|
|
17597
17744
|
const stillOurs = () => {
|
|
17598
17745
|
if (!cursors) return true;
|
|
17599
17746
|
const now = cursors.read(sessionId);
|
|
@@ -17602,12 +17749,10 @@ ${content}`);
|
|
|
17602
17749
|
if (plan.mode === "replace") {
|
|
17603
17750
|
const content = renderSessionJsonl(refId, turns, startTs);
|
|
17604
17751
|
cursors?.write(sessionId, { ...next, dirty: true });
|
|
17605
|
-
|
|
17606
|
-
|
|
17607
|
-
|
|
17608
|
-
|
|
17609
|
-
);
|
|
17610
|
-
cursors?.write(sessionId, next);
|
|
17752
|
+
const operationId = opId("replace", content);
|
|
17753
|
+
await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
|
|
17754
|
+
ops = [];
|
|
17755
|
+
cursors?.write(sessionId, accepted(operationId));
|
|
17611
17756
|
return;
|
|
17612
17757
|
}
|
|
17613
17758
|
const queue = [...outbox];
|
|
@@ -17615,7 +17760,7 @@ ${content}`);
|
|
|
17615
17760
|
const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
|
|
17616
17761
|
queue.push({ content, operationId: opId("append", content), at: Date.now() });
|
|
17617
17762
|
}
|
|
17618
|
-
cursors?.write(sessionId, { ...
|
|
17763
|
+
cursors?.write(sessionId, { ...accepted(), pending: queue });
|
|
17619
17764
|
for (let i = 0; i < queue.length; i++) {
|
|
17620
17765
|
if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
|
|
17621
17766
|
const entry = queue[i];
|
|
@@ -17625,12 +17770,13 @@ ${content}`);
|
|
|
17625
17770
|
retryUntil
|
|
17626
17771
|
);
|
|
17627
17772
|
const remaining = queue.slice(i + 1);
|
|
17628
|
-
|
|
17773
|
+
const done = accepted(entry.operationId);
|
|
17774
|
+
cursors?.write(sessionId, remaining.length ? { ...done, pending: remaining } : done);
|
|
17629
17775
|
}
|
|
17630
17776
|
}
|
|
17631
17777
|
|
|
17632
17778
|
// src/core/usage.ts
|
|
17633
|
-
import { readFileSync as
|
|
17779
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
17634
17780
|
import { join as join13 } from "path";
|
|
17635
17781
|
function usageFilePath() {
|
|
17636
17782
|
return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
|
|
@@ -17737,11 +17883,8 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
17737
17883
|
return { tags, metadata, context };
|
|
17738
17884
|
}
|
|
17739
17885
|
|
|
17740
|
-
// src/core/session-start.ts
|
|
17741
|
-
import { readFileSync as readFileSync8 } from "fs";
|
|
17742
|
-
|
|
17743
17886
|
// src/core/skill-sync.ts
|
|
17744
|
-
import { cpSync, existsSync as existsSync6, readFileSync as
|
|
17887
|
+
import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
17745
17888
|
import { homedir as homedir7 } from "os";
|
|
17746
17889
|
import { dirname as dirname8, join as join15 } from "path";
|
|
17747
17890
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
@@ -17777,7 +17920,12 @@ var SKILL_DIRS = {
|
|
|
17777
17920
|
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
17778
17921
|
// and dsh's copy with it.
|
|
17779
17922
|
pi: [".pi", "agent", "skills"],
|
|
17780
|
-
"prime-agent": [".prime", "agent", "skills"]
|
|
17923
|
+
"prime-agent": [".prime", "agent", "skills"],
|
|
17924
|
+
// WorkBuddy's own user-level skills root (the @genie/agent-cli engine reads ~/.workbuddy).
|
|
17925
|
+
workbuddy: [".workbuddy", "skills"],
|
|
17926
|
+
// CodeBuddy Code reads that SAME engine's default root, ~/.codebuddy — WorkBuddy only overrides
|
|
17927
|
+
// its home folder (product config `dataLayout.configDir.userDirName`), so the two differ by config.
|
|
17928
|
+
codebuddy: [".codebuddy", "skills"]
|
|
17781
17929
|
};
|
|
17782
17930
|
var TRAE_DOT_DIRS = [".trae-cn", ".trae"];
|
|
17783
17931
|
var traecodeDotDirName = (home, exists = existsSync5) => {
|
|
@@ -17811,7 +17959,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
17811
17959
|
const dstMd = join15(dst, "SKILL.md");
|
|
17812
17960
|
const installed = existsSync6(dstMd);
|
|
17813
17961
|
if (!installed && !opts.install) return;
|
|
17814
|
-
if (!installed ||
|
|
17962
|
+
if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
|
|
17815
17963
|
cpSync(src, dst, { recursive: true });
|
|
17816
17964
|
}
|
|
17817
17965
|
} catch {
|
|
@@ -17820,7 +17968,7 @@ function syncCompanionSkill(harness, opts = {}) {
|
|
|
17820
17968
|
function readPackagedSkill(srcDir = packagedSkillDir()) {
|
|
17821
17969
|
try {
|
|
17822
17970
|
const path = join15(srcDir, "SKILL.md");
|
|
17823
|
-
const raw =
|
|
17971
|
+
const raw = readFileSync6(path, "utf8");
|
|
17824
17972
|
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
|
|
17825
17973
|
return {
|
|
17826
17974
|
location: srcDir,
|
|
@@ -17848,7 +17996,7 @@ function brandWord() {
|
|
|
17848
17996
|
}
|
|
17849
17997
|
|
|
17850
17998
|
// src/core/legacy.ts
|
|
17851
|
-
import { existsSync as existsSync7, readFileSync as
|
|
17999
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
|
|
17852
18000
|
import { homedir as homedir8 } from "os";
|
|
17853
18001
|
import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
|
|
17854
18002
|
var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
|
|
@@ -17873,7 +18021,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
|
|
|
17873
18021
|
}
|
|
17874
18022
|
function readJson(path) {
|
|
17875
18023
|
try {
|
|
17876
|
-
const parsed = JSON.parse(
|
|
18024
|
+
const parsed = JSON.parse(readFileSync7(path, "utf8"));
|
|
17877
18025
|
return parsed && typeof parsed === "object" ? parsed : void 0;
|
|
17878
18026
|
} catch {
|
|
17879
18027
|
return void 0;
|
|
@@ -17885,7 +18033,7 @@ function legacyClaudePluginWarning(key) {
|
|
|
17885
18033
|
}
|
|
17886
18034
|
|
|
17887
18035
|
// src/core/session-cache.ts
|
|
17888
|
-
import { mkdirSync as mkdirSync4, readFileSync as
|
|
18036
|
+
import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
17889
18037
|
import { tmpdir as tmpdir3 } from "os";
|
|
17890
18038
|
import { dirname as dirname9, join as join17 } from "path";
|
|
17891
18039
|
function sessionCacheFile(harness, sessionId) {
|
|
@@ -17893,7 +18041,7 @@ function sessionCacheFile(harness, sessionId) {
|
|
|
17893
18041
|
}
|
|
17894
18042
|
function readSessionCache(cacheFile) {
|
|
17895
18043
|
try {
|
|
17896
|
-
return JSON.parse(
|
|
18044
|
+
return JSON.parse(readFileSync8(cacheFile, "utf8"));
|
|
17897
18045
|
} catch {
|
|
17898
18046
|
return {};
|
|
17899
18047
|
}
|
|
@@ -17937,9 +18085,9 @@ async function gitSyncNote(args) {
|
|
|
17937
18085
|
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
17938
18086
|
let target = DEEPEN_DIFF_TARGET;
|
|
17939
18087
|
try {
|
|
17940
|
-
const { execFileSync:
|
|
18088
|
+
const { execFileSync: execFileSync5 } = await import("child_process");
|
|
17941
18089
|
const n = Number(
|
|
17942
|
-
|
|
18090
|
+
execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
17943
18091
|
encoding: "utf8",
|
|
17944
18092
|
windowsHide: true,
|
|
17945
18093
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -17956,6 +18104,7 @@ async function buildSessionStartContext(args) {
|
|
|
17956
18104
|
const t0 = Date.now();
|
|
17957
18105
|
let cold;
|
|
17958
18106
|
let gitDocIds;
|
|
18107
|
+
let bankEmpty = false;
|
|
17959
18108
|
const harness = args.harness ?? "claude-code";
|
|
17960
18109
|
const hasGit = args.hasGit ?? hasGitHistory;
|
|
17961
18110
|
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
@@ -17995,11 +18144,21 @@ async function buildSessionStartContext(args) {
|
|
|
17995
18144
|
} catch {
|
|
17996
18145
|
docIds = void 0;
|
|
17997
18146
|
}
|
|
17998
|
-
|
|
18147
|
+
let baselines;
|
|
18148
|
+
if (docIds?.size === 0) {
|
|
18149
|
+
baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
|
|
18150
|
+
}
|
|
18151
|
+
cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
|
|
17999
18152
|
gitDocIds = docIds;
|
|
18153
|
+
if (cold === true && client.hasDocuments) {
|
|
18154
|
+
bankEmpty = await client.hasDocuments().then(
|
|
18155
|
+
(has) => !has,
|
|
18156
|
+
() => false
|
|
18157
|
+
);
|
|
18158
|
+
}
|
|
18000
18159
|
if (docIds !== void 0) {
|
|
18001
18160
|
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
18002
|
-
if (
|
|
18161
|
+
if (cold) {
|
|
18003
18162
|
if (cfg.codebaseSurvey !== false) {
|
|
18004
18163
|
const started = await startSurvey(cwd, {
|
|
18005
18164
|
harness,
|
|
@@ -18013,7 +18172,7 @@ async function buildSessionStartContext(args) {
|
|
|
18013
18172
|
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
18014
18173
|
const sha = resolveHeadSha(cwd);
|
|
18015
18174
|
if (sha) {
|
|
18016
|
-
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18175
|
+
const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
18017
18176
|
const counts = [];
|
|
18018
18177
|
for (const id of markers) {
|
|
18019
18178
|
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
@@ -18047,10 +18206,8 @@ async function buildSessionStartContext(args) {
|
|
|
18047
18206
|
}
|
|
18048
18207
|
}
|
|
18049
18208
|
let pages = [];
|
|
18050
|
-
let pageListKnown = false;
|
|
18051
18209
|
try {
|
|
18052
18210
|
pages = parsePageList(await client.listPages());
|
|
18053
|
-
pageListKnown = true;
|
|
18054
18211
|
} catch {
|
|
18055
18212
|
if (client.knowledgePagesSupported === false) {
|
|
18056
18213
|
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
@@ -18060,7 +18217,7 @@ async function buildSessionStartContext(args) {
|
|
|
18060
18217
|
reflectOnNewGoals: cfg.autoInject !== "reflect",
|
|
18061
18218
|
extra: cfg.toolGuideExtra
|
|
18062
18219
|
});
|
|
18063
|
-
const deferInitialReflect =
|
|
18220
|
+
const deferInitialReflect = bankEmpty;
|
|
18064
18221
|
let gitNote;
|
|
18065
18222
|
if (gitDocIds) {
|
|
18066
18223
|
gitNote = await gitSyncNote({
|
|
@@ -18084,7 +18241,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
|
|
|
18084
18241
|
}
|
|
18085
18242
|
|
|
18086
18243
|
// src/core/hook.ts
|
|
18087
|
-
import { existsSync as existsSync8
|
|
18244
|
+
import { existsSync as existsSync8 } from "fs";
|
|
18088
18245
|
|
|
18089
18246
|
// src/core/inject.ts
|
|
18090
18247
|
function buildReflectQuery(prompt) {
|
|
@@ -18175,9 +18332,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
|
18175
18332
|
|
|
18176
18333
|
// src/core/hook.ts
|
|
18177
18334
|
var HOOK_INJECT_ATTEMPTS = 2;
|
|
18335
|
+
var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
|
|
18178
18336
|
function resolveInjection(got, attempts) {
|
|
18179
18337
|
if (got != null) return got;
|
|
18180
|
-
|
|
18338
|
+
const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
|
|
18339
|
+
return attempts >= budget ? "" : void 0;
|
|
18340
|
+
}
|
|
18341
|
+
var RECALL_QUERY_MAX_TOKENS = 500;
|
|
18342
|
+
function boundRecallQuery(prompt) {
|
|
18343
|
+
let cost = 0;
|
|
18344
|
+
let end = 0;
|
|
18345
|
+
for (const ch of prompt) {
|
|
18346
|
+
const cp = ch.codePointAt(0);
|
|
18347
|
+
cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
|
|
18348
|
+
if (cost > RECALL_QUERY_MAX_TOKENS) break;
|
|
18349
|
+
end += ch.length;
|
|
18350
|
+
}
|
|
18351
|
+
return prompt.slice(0, end);
|
|
18181
18352
|
}
|
|
18182
18353
|
async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
18183
18354
|
const t0 = Date.now();
|
|
@@ -18193,7 +18364,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
|
|
|
18193
18364
|
async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
|
|
18194
18365
|
const t0 = Date.now();
|
|
18195
18366
|
try {
|
|
18196
|
-
const observations = await client.recallObservations(prompt
|
|
18367
|
+
const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
|
|
18197
18368
|
diag(harness, event, { ms: Date.now() - t0, count: observations.length });
|
|
18198
18369
|
return observations.length ? formatRecallFallback(observations, lead) : null;
|
|
18199
18370
|
} catch (e) {
|
|
@@ -18268,7 +18439,7 @@ async function buildHookOutput(args) {
|
|
|
18268
18439
|
answer: reflectAnswer.slice(0, 8e3)
|
|
18269
18440
|
});
|
|
18270
18441
|
} catch (e) {
|
|
18271
|
-
reflectAnswer = resolveInjection(void 0, reflectAttempts);
|
|
18442
|
+
reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
|
|
18272
18443
|
reflectFailed = true;
|
|
18273
18444
|
log.warn(harness, "reflect failed \u2014 session runs without memory", {
|
|
18274
18445
|
error: describeError(e)
|
|
@@ -18340,6 +18511,7 @@ async function buildHookOutput(args) {
|
|
|
18340
18511
|
|
|
18341
18512
|
// src/core/runtime.ts
|
|
18342
18513
|
var HARNESS = "opencode";
|
|
18514
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
18343
18515
|
var RuntimeCore = class {
|
|
18344
18516
|
constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
|
|
18345
18517
|
this.client = client;
|
|
@@ -18365,6 +18537,8 @@ var RuntimeCore = class {
|
|
|
18365
18537
|
usageCursors = memoryUsageCursorStore();
|
|
18366
18538
|
/** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
|
|
18367
18539
|
fetchTranscript;
|
|
18540
|
+
/** Write-backs started and not yet settled — what `flush` waits for. */
|
|
18541
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
18368
18542
|
lastInjection = "";
|
|
18369
18543
|
// most recent turn's injection block, keyed by nothing (see getInjection)
|
|
18370
18544
|
deferInitialReflect = false;
|
|
@@ -18497,8 +18671,9 @@ var RuntimeCore = class {
|
|
|
18497
18671
|
*/
|
|
18498
18672
|
async onTranscript(sessionId, turns, lastTurnComplete) {
|
|
18499
18673
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18500
|
-
if (!
|
|
18674
|
+
if (!sessionId || !turns.length) return;
|
|
18501
18675
|
this.recordUsage(sessionId, turns, lastTurnComplete);
|
|
18676
|
+
if (!this.writeBackEnabled) return;
|
|
18502
18677
|
const st = this.stateFor(sessionId);
|
|
18503
18678
|
this.retain(sessionId, turns, st.startTs);
|
|
18504
18679
|
}
|
|
@@ -18516,7 +18691,7 @@ var RuntimeCore = class {
|
|
|
18516
18691
|
*/
|
|
18517
18692
|
async onSessionIdle(sessionId) {
|
|
18518
18693
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
18519
|
-
if (!
|
|
18694
|
+
if (!sessionId || !this.fetchTranscript) return;
|
|
18520
18695
|
let turns;
|
|
18521
18696
|
try {
|
|
18522
18697
|
turns = await this.fetchTranscript(sessionId);
|
|
@@ -18529,6 +18704,7 @@ var RuntimeCore = class {
|
|
|
18529
18704
|
}
|
|
18530
18705
|
if (!turns.length) return;
|
|
18531
18706
|
this.recordUsage(sessionId, turns, true);
|
|
18707
|
+
if (!this.writeBackEnabled) return;
|
|
18532
18708
|
const st = this.stateFor(sessionId);
|
|
18533
18709
|
if (turns.length <= st.retainedTurns) return;
|
|
18534
18710
|
st.retainedTurns = turns.length;
|
|
@@ -18556,10 +18732,27 @@ var RuntimeCore = class {
|
|
|
18556
18732
|
}
|
|
18557
18733
|
return st;
|
|
18558
18734
|
}
|
|
18735
|
+
/**
|
|
18736
|
+
* Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
|
|
18737
|
+
* so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
|
|
18738
|
+
* calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
|
|
18739
|
+
* stalled server cannot hold the host's exit open. Never throws.
|
|
18740
|
+
*/
|
|
18741
|
+
async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
|
|
18742
|
+
if (!this.inFlight.size) return;
|
|
18743
|
+
let timer;
|
|
18744
|
+
await Promise.race([
|
|
18745
|
+
Promise.all(this.inFlight),
|
|
18746
|
+
new Promise((r) => {
|
|
18747
|
+
timer = setTimeout(r, timeoutMs);
|
|
18748
|
+
})
|
|
18749
|
+
]);
|
|
18750
|
+
clearTimeout(timer);
|
|
18751
|
+
}
|
|
18559
18752
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
18560
18753
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
18561
18754
|
const t0 = Date.now();
|
|
18562
|
-
|
|
18755
|
+
const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
18563
18756
|
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
18564
18757
|
cursors: this.cursors,
|
|
18565
18758
|
stamp: buildRetainStamp(this.cfg, {
|
|
@@ -18584,6 +18777,8 @@ var RuntimeCore = class {
|
|
|
18584
18777
|
trigger
|
|
18585
18778
|
})
|
|
18586
18779
|
);
|
|
18780
|
+
this.inFlight.add(write2);
|
|
18781
|
+
void write2.finally(() => this.inFlight.delete(write2));
|
|
18587
18782
|
}
|
|
18588
18783
|
};
|
|
18589
18784
|
|
|
@@ -19106,7 +19301,7 @@ __export(core_exports4, {
|
|
|
19106
19301
|
toJSONSchema: () => toJSONSchema2,
|
|
19107
19302
|
treeifyError: () => treeifyError2,
|
|
19108
19303
|
util: () => util_exports2,
|
|
19109
|
-
version: () =>
|
|
19304
|
+
version: () => version3
|
|
19110
19305
|
});
|
|
19111
19306
|
|
|
19112
19307
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/core.js
|
|
@@ -20109,10 +20304,10 @@ var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
20109
20304
|
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
20305
|
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
20306
|
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 (!
|
|
20307
|
+
var uuid3 = (version4) => {
|
|
20308
|
+
if (!version4)
|
|
20114
20309
|
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}-${
|
|
20310
|
+
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
20311
|
};
|
|
20117
20312
|
var uuid42 = /* @__PURE__ */ uuid3(4);
|
|
20118
20313
|
var uuid62 = /* @__PURE__ */ uuid3(6);
|
|
@@ -20770,7 +20965,7 @@ var Doc2 = class {
|
|
|
20770
20965
|
};
|
|
20771
20966
|
|
|
20772
20967
|
// node_modules/@opencode-ai/plugin/node_modules/zod/v4/core/versions.js
|
|
20773
|
-
var
|
|
20968
|
+
var version3 = {
|
|
20774
20969
|
major: 4,
|
|
20775
20970
|
minor: 1,
|
|
20776
20971
|
patch: 8
|
|
@@ -20782,7 +20977,7 @@ var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
|
|
|
20782
20977
|
inst ?? (inst = {});
|
|
20783
20978
|
inst._zod.def = def;
|
|
20784
20979
|
inst._zod.bag = inst._zod.bag || {};
|
|
20785
|
-
inst._zod.version =
|
|
20980
|
+
inst._zod.version = version3;
|
|
20786
20981
|
const checks = [...inst._zod.def.checks ?? []];
|
|
20787
20982
|
if (inst._zod.traits.has("$ZodCheck")) {
|
|
20788
20983
|
checks.unshift(inst);
|
|
@@ -31038,12 +31233,12 @@ function tool(input) {
|
|
|
31038
31233
|
tool.schema = external_exports2;
|
|
31039
31234
|
|
|
31040
31235
|
// src/harness/registry.ts
|
|
31041
|
-
import { readFileSync as
|
|
31236
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
31042
31237
|
var jsonChatReader = (harness) => ({
|
|
31043
31238
|
describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
|
|
31044
31239
|
async read(opts) {
|
|
31045
31240
|
if (!opts.conversations) return [];
|
|
31046
|
-
return JSON.parse(
|
|
31241
|
+
return JSON.parse(readFileSync10(opts.conversations, "utf8"));
|
|
31047
31242
|
}
|
|
31048
31243
|
});
|
|
31049
31244
|
|