@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.
Files changed (62) hide show
  1. package/README.md +67 -6
  2. package/dist/antigravity-hook.js +441 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +441 -95
  5. package/dist/claude-hook.js +441 -80
  6. package/dist/claude-sessionstart-hook.js +473 -93
  7. package/dist/claude-stop-hook.js +441 -95
  8. package/dist/cline.js +290 -95
  9. package/dist/codebuddy-hook.js +4270 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5030 -0
  11. package/dist/codebuddy-stop-hook.js +4564 -0
  12. package/dist/codex-hook.js +441 -80
  13. package/dist/codex-sessionstart-hook.js +473 -93
  14. package/dist/codex-stop-hook.js +441 -95
  15. package/dist/copilot-hook.js +441 -80
  16. package/dist/copilot-sessionstart-hook.js +473 -93
  17. package/dist/copilot-stop-hook.js +441 -95
  18. package/dist/cursor-hook.js +441 -80
  19. package/dist/cursor-sessionstart-hook.js +473 -93
  20. package/dist/cursor-stop-hook.js +441 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +441 -80
  23. package/dist/dcode-sessionstart-hook.js +473 -93
  24. package/dist/dcode-stop-hook.js +441 -95
  25. package/dist/deepen.js +140 -49
  26. package/dist/devin-hook.js +441 -80
  27. package/dist/devin-sessionstart-hook.js +473 -93
  28. package/dist/devin-stop-hook.js +441 -95
  29. package/dist/droid-hook.js +441 -80
  30. package/dist/droid-sessionstart-hook.js +473 -93
  31. package/dist/droid-stop-hook.js +441 -95
  32. package/dist/dsh.js +297 -95
  33. package/dist/grok-hook.js +441 -80
  34. package/dist/grok-sessionstart-hook.js +473 -93
  35. package/dist/grok-stop-hook.js +441 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +299 -104
  38. package/dist/installer.js +1043 -647
  39. package/dist/kilo.js +299 -104
  40. package/dist/kimi-hook.js +441 -80
  41. package/dist/kimi-sessionstart-hook.js +473 -93
  42. package/dist/kimi-stop-hook.js +441 -95
  43. package/dist/mcp-server.js +261 -86
  44. package/dist/opencode2.js +296 -101
  45. package/dist/pi.js +352 -107
  46. package/dist/prime-agent.js +352 -107
  47. package/dist/qwen-hook.js +441 -80
  48. package/dist/qwen-sessionstart-hook.js +473 -93
  49. package/dist/qwen-stop-hook.js +441 -95
  50. package/dist/status.js +115 -42
  51. package/dist/traecode-hook.js +441 -80
  52. package/dist/traecode-sessionstart-hook.js +473 -93
  53. package/dist/traecode-stop-hook.js +441 -95
  54. package/dist/workbuddy-hook.js +4270 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5030 -0
  56. package/dist/workbuddy-stop-hook.js +4564 -0
  57. package/dist/zcode-hook.js +441 -80
  58. package/dist/zcode-sessionstart-hook.js +473 -93
  59. package/dist/zcode-stop-hook.js +441 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +4 -4
package/dist/pi.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 = (version2) => {
1602
- if (!version2)
1601
+ var uuid = (version3) => {
1602
+ if (!version3)
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}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1604
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
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 version2 = detectVersion(normalized, params?.defaultTarget);
14480
+ const version3 = detectVersion(normalized, params?.defaultTarget);
14481
14481
  const defs = normalized.$defs || normalized.definitions || {};
14482
14482
  const ctx = {
14483
- version: version2,
14483
+ version: version3,
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 readFileSync2 } from "fs";
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 readFileSync(path, "utf8");
14665
+ return readFileSync2(path, "utf8");
14665
14666
  } catch (error51) {
14666
14667
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
14667
14668
  return null;
@@ -14876,6 +14877,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
14876
14877
  };
14877
14878
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14878
14879
  }
14880
+ function bankProjectName(config2, directory, sessionRoot) {
14881
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
14882
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
14883
+ if (!dynamic) return void 0;
14884
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
14885
+ if (!template.includes("{gitProject}")) return void 0;
14886
+ try {
14887
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
14888
+ } catch (error51) {
14889
+ if (error51 instanceof BankResolutionError) return void 0;
14890
+ throw error51;
14891
+ }
14892
+ }
14879
14893
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
14880
14894
  try {
14881
14895
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -14893,7 +14907,7 @@ function deriveBankIdOrSkip(config2, 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, newest 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.";
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(version2, min) {
15195
+ function semverGte(version3, 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 = version2 ? parts(version2) : void 0;
15200
+ const a = version3 ? parts(version3) : 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 true;
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(url2, init) {
15355
- const send = () => fetch(url2, { ...init, headers: this.headers() });
15395
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
15396
+ const send = () => fetch(url2, { ...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, url2, body, tolerate = [], timeoutMs = 15e3) {
15371
- const r = await this.fetchWithAuth(url2, {
15372
- method,
15373
- body: body ? JSON.stringify(body) : void 0,
15374
- signal: AbortSignal.timeout(timeoutMs)
15375
- });
15376
- if (r.status === 429 && !tolerate.includes(429))
15377
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
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(url2, {
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} ${url2} -> ${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 GET /version; anything
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
- try {
15424
- const r = await this.req("GET", `${this.apiUrl}/version`);
15425
- if (!r.ok) return false;
15426
- const j = await r.json();
15427
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
15428
- } catch {
15429
- return false;
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 (!r.ok) return;
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 ?? this.bank, pagesConfig, customPages);
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 ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
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
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
15857
- * initiative's own title, and re-stating either would rebuild a page whose question never
15858
- * changed. The tree read above is reused rather than re-fetched.
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" || page.trigger == null) continue;
15867
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
15868
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
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
- { trigger: pageTriggerPatch(desired) }
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(subject),
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(args.title)}-${Date.now()}`;
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(readFileSync2(path, "utf8"));
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
- return applyBankConfig(cfg0, bankId, directory);
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 readFileSync3,
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(readFileSync3(join8(pkgRoot, "package.json"), "utf8"));
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(file2, now) {
16431
16521
  try {
16432
- const state = JSON.parse(readFileSync3(file2, "utf8"));
16522
+ const state = JSON.parse(readFileSync4(file2, "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(file2, now) {
16438
16528
  var ORIGIN_FILE = ".install-origin.json";
16439
16529
  function selfUpdatable(runtimeDir) {
16440
16530
  try {
16441
- const origin = JSON.parse(readFileSync3(join8(runtimeDir, ORIGIN_FILE), "utf8"));
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(file2, now) {
16453
16543
  try {
16454
- const held = JSON.parse(readFileSync3(file2, "utf8"));
16544
+ const held = JSON.parse(readFileSync4(file2, "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(file2, 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("npm", ["view", pkg, "version", "--json"], {
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 = (opts.spawn ?? realSpawn2)(
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`, { signal: AbortSignal.timeout(timeoutMs) });
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 execFileSync3 } from "child_process";
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 = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
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
- const cursor = cursors?.read(sessionId);
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
- await submitWithRetry(
17606
- () => submit(content, opId("replace", content), false),
17607
- stillOurs,
17608
- retryUntil
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, { ...next, pending: queue });
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
- cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
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 readFileSync4 } from "fs";
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 readFileSync5 } from "fs";
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 || readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
17962
+ if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
17815
17963
  cpSync(src, dst, { recursive: true });
17816
17964
  }
17817
17965
  } catch {
@@ -17833,7 +17981,7 @@ function brandWord() {
17833
17981
  }
17834
17982
 
17835
17983
  // src/core/legacy.ts
17836
- import { existsSync as existsSync7, readFileSync as readFileSync6 } from "fs";
17984
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
17837
17985
  import { homedir as homedir8 } from "os";
17838
17986
  import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
17839
17987
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
@@ -17858,7 +18006,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
17858
18006
  }
17859
18007
  function readJson(path) {
17860
18008
  try {
17861
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
18009
+ const parsed = JSON.parse(readFileSync7(path, "utf8"));
17862
18010
  return parsed && typeof parsed === "object" ? parsed : void 0;
17863
18011
  } catch {
17864
18012
  return void 0;
@@ -17870,7 +18018,7 @@ function legacyClaudePluginWarning(key) {
17870
18018
  }
17871
18019
 
17872
18020
  // src/core/session-cache.ts
17873
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18021
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17874
18022
  import { tmpdir as tmpdir3 } from "os";
17875
18023
  import { dirname as dirname9, join as join17 } from "path";
17876
18024
  function sessionCacheFile(harness, sessionId) {
@@ -17878,7 +18026,7 @@ function sessionCacheFile(harness, sessionId) {
17878
18026
  }
17879
18027
  function readSessionCache(cacheFile) {
17880
18028
  try {
17881
- return JSON.parse(readFileSync7(cacheFile, "utf8"));
18029
+ return JSON.parse(readFileSync8(cacheFile, "utf8"));
17882
18030
  } catch {
17883
18031
  return {};
17884
18032
  }
@@ -17922,9 +18070,9 @@ async function gitSyncNote(args) {
17922
18070
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
17923
18071
  let target = DEEPEN_DIFF_TARGET;
17924
18072
  try {
17925
- const { execFileSync: execFileSync4 } = await import("child_process");
18073
+ const { execFileSync: execFileSync5 } = await import("child_process");
17926
18074
  const n = Number(
17927
- execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
18075
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17928
18076
  encoding: "utf8",
17929
18077
  windowsHide: true,
17930
18078
  stdio: ["ignore", "pipe", "pipe"]
@@ -17941,6 +18089,7 @@ async function buildSessionStartContext(args) {
17941
18089
  const t0 = Date.now();
17942
18090
  let cold;
17943
18091
  let gitDocIds;
18092
+ let bankEmpty = false;
17944
18093
  const harness = args.harness ?? "claude-code";
17945
18094
  const hasGit = args.hasGit ?? hasGitHistory;
17946
18095
  const startSeed = args.startSeed ?? startBackgroundSeed;
@@ -17980,11 +18129,21 @@ async function buildSessionStartContext(args) {
17980
18129
  } catch {
17981
18130
  docIds = void 0;
17982
18131
  }
17983
- cold = docIds !== void 0 ? docIds.size === 0 : void 0;
18132
+ let baselines;
18133
+ if (docIds?.size === 0) {
18134
+ baselines = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => void 0);
18135
+ }
18136
+ cold = docIds !== void 0 ? docIds.size === 0 && !baselines?.size : void 0;
17984
18137
  gitDocIds = docIds;
18138
+ if (cold === true && client.hasDocuments) {
18139
+ bankEmpty = await client.hasDocuments().then(
18140
+ (has) => !has,
18141
+ () => false
18142
+ );
18143
+ }
17985
18144
  if (docIds !== void 0) {
17986
18145
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17987
- if (docIds.size === 0) {
18146
+ if (cold) {
17988
18147
  if (cfg.codebaseSurvey !== false) {
17989
18148
  const started = await startSurvey(cwd, {
17990
18149
  harness,
@@ -17998,7 +18157,7 @@ async function buildSessionStartContext(args) {
17998
18157
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
17999
18158
  const sha = resolveHeadSha(cwd);
18000
18159
  if (sha) {
18001
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18160
+ const markers = baselines ?? await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
18002
18161
  const counts = [];
18003
18162
  for (const id of markers) {
18004
18163
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -18032,10 +18191,8 @@ async function buildSessionStartContext(args) {
18032
18191
  }
18033
18192
  }
18034
18193
  let pages = [];
18035
- let pageListKnown = false;
18036
18194
  try {
18037
18195
  pages = parsePageList(await client.listPages());
18038
- pageListKnown = true;
18039
18196
  } catch {
18040
18197
  if (client.knowledgePagesSupported === false) {
18041
18198
  diag(harness, "knowledge_pages_unavailable", { bank: bankId });
@@ -18045,7 +18202,7 @@ async function buildSessionStartContext(args) {
18045
18202
  reflectOnNewGoals: cfg.autoInject !== "reflect",
18046
18203
  extra: cfg.toolGuideExtra
18047
18204
  });
18048
- const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
18205
+ const deferInitialReflect = bankEmpty;
18049
18206
  let gitNote;
18050
18207
  if (gitDocIds) {
18051
18208
  gitNote = await gitSyncNote({
@@ -18069,7 +18226,7 @@ ${legacyClaudePluginWarning(legacyPlugin)}`;
18069
18226
  }
18070
18227
 
18071
18228
  // src/core/hook.ts
18072
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
18229
+ import { existsSync as existsSync8 } from "fs";
18073
18230
 
18074
18231
  // src/core/inject.ts
18075
18232
  function buildReflectQuery(prompt) {
@@ -18160,9 +18317,23 @@ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
18160
18317
 
18161
18318
  // src/core/hook.ts
18162
18319
  var HOOK_INJECT_ATTEMPTS = 2;
18320
+ var HOOK_INJECT_EMPTY_ATTEMPTS = 5;
18163
18321
  function resolveInjection(got, attempts) {
18164
18322
  if (got != null) return got;
18165
- return got === null || attempts >= HOOK_INJECT_ATTEMPTS ? "" : void 0;
18323
+ const budget = got === null ? HOOK_INJECT_EMPTY_ATTEMPTS : HOOK_INJECT_ATTEMPTS;
18324
+ return attempts >= budget ? "" : void 0;
18325
+ }
18326
+ var RECALL_QUERY_MAX_TOKENS = 500;
18327
+ function boundRecallQuery(prompt) {
18328
+ let cost = 0;
18329
+ let end = 0;
18330
+ for (const ch of prompt) {
18331
+ const cp = ch.codePointAt(0);
18332
+ cost += cp < 128 ? 0.5 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
18333
+ if (cost > RECALL_QUERY_MAX_TOKENS) break;
18334
+ end += ch.length;
18335
+ }
18336
+ return prompt.slice(0, end);
18166
18337
  }
18167
18338
  async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18168
18339
  const t0 = Date.now();
@@ -18178,7 +18349,7 @@ async function injectPages(harness, prompt, client, timeoutMs, event, lead) {
18178
18349
  async function injectRecall(harness, prompt, client, timeoutMs, event, lead) {
18179
18350
  const t0 = Date.now();
18180
18351
  try {
18181
- const observations = await client.recallObservations(prompt.slice(0, 2e3), { timeoutMs });
18352
+ const observations = await client.recallObservations(boundRecallQuery(prompt), { timeoutMs });
18182
18353
  diag(harness, event, { ms: Date.now() - t0, count: observations.length });
18183
18354
  return observations.length ? formatRecallFallback(observations, lead) : null;
18184
18355
  } catch (e) {
@@ -18253,7 +18424,7 @@ async function buildHookOutput(args) {
18253
18424
  answer: reflectAnswer.slice(0, 8e3)
18254
18425
  });
18255
18426
  } catch (e) {
18256
- reflectAnswer = resolveInjection(void 0, reflectAttempts);
18427
+ reflectAnswer = e instanceof ReflectError && e.permanent ? "" : resolveInjection(void 0, reflectAttempts);
18257
18428
  reflectFailed = true;
18258
18429
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
18259
18430
  error: describeError(e)
@@ -18325,6 +18496,7 @@ async function buildHookOutput(args) {
18325
18496
 
18326
18497
  // src/core/runtime.ts
18327
18498
  var HARNESS = "opencode";
18499
+ var FLUSH_TIMEOUT_MS = 1e4;
18328
18500
  var RuntimeCore = class {
18329
18501
  constructor(client, bankId, cfg, harness = HARNESS, projectDir = process.cwd()) {
18330
18502
  this.client = client;
@@ -18350,6 +18522,8 @@ var RuntimeCore = class {
18350
18522
  usageCursors = memoryUsageCursorStore();
18351
18523
  /** Pulls a session's CURRENT transcript from the host (set by the adapter); see onSessionIdle. */
18352
18524
  fetchTranscript;
18525
+ /** Write-backs started and not yet settled — what `flush` waits for. */
18526
+ inFlight = /* @__PURE__ */ new Set();
18353
18527
  lastInjection = "";
18354
18528
  // most recent turn's injection block, keyed by nothing (see getInjection)
18355
18529
  deferInitialReflect = false;
@@ -18482,8 +18656,9 @@ var RuntimeCore = class {
18482
18656
  */
18483
18657
  async onTranscript(sessionId, turns, lastTurnComplete) {
18484
18658
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18485
- if (!this.writeBackEnabled || !sessionId || !turns.length) return;
18659
+ if (!sessionId || !turns.length) return;
18486
18660
  this.recordUsage(sessionId, turns, lastTurnComplete);
18661
+ if (!this.writeBackEnabled) return;
18487
18662
  const st = this.stateFor(sessionId);
18488
18663
  this.retain(sessionId, turns, st.startTs);
18489
18664
  }
@@ -18501,7 +18676,7 @@ var RuntimeCore = class {
18501
18676
  */
18502
18677
  async onSessionIdle(sessionId) {
18503
18678
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18504
- if (!this.writeBackEnabled || !sessionId || !this.fetchTranscript) return;
18679
+ if (!sessionId || !this.fetchTranscript) return;
18505
18680
  let turns;
18506
18681
  try {
18507
18682
  turns = await this.fetchTranscript(sessionId);
@@ -18514,6 +18689,7 @@ var RuntimeCore = class {
18514
18689
  }
18515
18690
  if (!turns.length) return;
18516
18691
  this.recordUsage(sessionId, turns, true);
18692
+ if (!this.writeBackEnabled) return;
18517
18693
  const st = this.stateFor(sessionId);
18518
18694
  if (turns.length <= st.retainedTurns) return;
18519
18695
  st.retainedTurns = turns.length;
@@ -18541,10 +18717,27 @@ var RuntimeCore = class {
18541
18717
  }
18542
18718
  return st;
18543
18719
  }
18720
+ /**
18721
+ * Wait for every write-back still in flight, at most `timeoutMs`. Write-backs stay fire-and-forget
18722
+ * so a turn never blocks on the network; a host that announces its exit (pi's `session_shutdown`)
18723
+ * calls this so the session's final retain is not dropped with the process (#5081). Bounded so a
18724
+ * stalled server cannot hold the host's exit open. Never throws.
18725
+ */
18726
+ async flush(timeoutMs = FLUSH_TIMEOUT_MS) {
18727
+ if (!this.inFlight.size) return;
18728
+ let timer;
18729
+ await Promise.race([
18730
+ Promise.all(this.inFlight),
18731
+ new Promise((r) => {
18732
+ timer = setTimeout(r, timeoutMs);
18733
+ })
18734
+ ]);
18735
+ clearTimeout(timer);
18736
+ }
18544
18737
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
18545
18738
  retain(sessionId, turns, startTs, trigger = "turn") {
18546
18739
  const t0 = Date.now();
18547
- void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18740
+ const write2 = ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
18548
18741
  () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
18549
18742
  cursors: this.cursors,
18550
18743
  stamp: buildRetainStamp(this.cfg, {
@@ -18569,6 +18762,8 @@ var RuntimeCore = class {
18569
18762
  trigger
18570
18763
  })
18571
18764
  );
18765
+ this.inFlight.add(write2);
18766
+ void write2.finally(() => this.inFlight.delete(write2));
18572
18767
  }
18573
18768
  };
18574
18769
 
@@ -18608,17 +18803,32 @@ function renderMessage(m) {
18608
18803
  function readPiMessages(messages) {
18609
18804
  return (messages || []).flatMap((m) => renderMessage(m));
18610
18805
  }
18806
+ function readPiEntries(entries) {
18807
+ const turns = [];
18808
+ for (const entry of entries) {
18809
+ if (!entry || entry.type !== "message" || !entry.message) continue;
18810
+ for (const turn of renderMessage(entry.message)) {
18811
+ turns.push(entry.timestamp ? { ...turn, timestamp: entry.timestamp } : turn);
18812
+ }
18813
+ }
18814
+ return turns;
18815
+ }
18611
18816
 
18612
18817
  // src/harness/pi-extension.ts
18613
- function toPiTool(spec) {
18818
+ function toPiTool(spec, bind = () => spec) {
18614
18819
  const parameters = external_exports.toJSONSchema(external_exports.object(spec.inputSchema));
18615
18820
  return {
18616
18821
  name: spec.name,
18617
18822
  label: spec.name,
18618
18823
  description: spec.description,
18619
18824
  parameters,
18620
- async execute(_toolCallId, params) {
18621
- const r = await spec.handler(params);
18825
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
18826
+ const bound = bind(ctx);
18827
+ if (!bound) {
18828
+ const text2 = "Hindsight memory is disabled for this workspace.";
18829
+ return { content: [{ type: "text", text: text2 }], details: null };
18830
+ }
18831
+ const r = await bound.handler(params);
18622
18832
  const text = r.content?.map((c) => c.text).join("\n") || "";
18623
18833
  return { content: [{ type: "text", text }], details: null };
18624
18834
  }
@@ -18648,10 +18858,14 @@ function createPiHooks(core, harness, sessionStart) {
18648
18858
 
18649
18859
  ${injection}` };
18650
18860
  },
18651
- async agentEnd(event, sessionId) {
18652
- const turns = readPiMessages(event.messages);
18861
+ /** `branch` is the session's entries (`sessionManager.getBranch()`): the event alone holds only
18862
+ * the latest run, and writing that back replaced the session's earlier runs (#4963). */
18863
+ async agentEnd(event, sessionId, branch) {
18864
+ const turns = branch ? readPiEntries(branch) : readPiMessages(event.messages);
18653
18865
  if (turns.length) await core.onTranscript(sessionId, turns, true);
18654
- }
18866
+ },
18867
+ /** The host is exiting: the last agent_end's write-back is still in flight (#5081). */
18868
+ sessionShutdown: () => core.flush()
18655
18869
  };
18656
18870
  }
18657
18871
  function createRuntime(harness, repoPath) {
@@ -18659,19 +18873,50 @@ function createRuntime(harness, repoPath) {
18659
18873
  if (cfg.disabled) return void 0;
18660
18874
  return new RuntimeCore(client, bankId, cfg, harness, repoPath);
18661
18875
  }
18662
- function createPiExtension(harness) {
18876
+ function createPiExtension(harness, makeRuntime = createRuntime) {
18663
18877
  return (pi) => {
18664
- const repoPath = process.cwd();
18665
- const core = createRuntime(harness, repoPath);
18666
- if (!core) return;
18667
- for (const spec of core.toolSpecs()) pi.registerTool(toPiTool(spec));
18668
- const sessionStart = core.seedIfCold(repoPath);
18669
- const hooks = createPiHooks(core, harness, sessionStart);
18878
+ const launchDir = process.cwd();
18879
+ const dirOf = (ctx) => ctx?.cwd || launchDir;
18880
+ const workspaces = /* @__PURE__ */ new Map();
18881
+ const workspaceFor = (dir) => {
18882
+ const cached2 = workspaces.get(dir);
18883
+ if (cached2 !== void 0) return cached2 ?? void 0;
18884
+ const core = makeRuntime(harness, dir);
18885
+ const ws = core ? { hooks: createPiHooks(core, harness, core.seedIfCold(dir)), tools: core.toolSpecs() } : null;
18886
+ workspaces.set(dir, ws);
18887
+ return ws ?? void 0;
18888
+ };
18889
+ let toolsRegistered = false;
18890
+ const at = (ctx) => {
18891
+ const ws = workspaceFor(dirOf(ctx));
18892
+ if (ws && !toolsRegistered) {
18893
+ toolsRegistered = true;
18894
+ for (const spec of ws.tools)
18895
+ pi.registerTool(
18896
+ toPiTool(spec, (c) => workspaceFor(dirOf(c))?.tools.find((t) => t.name === spec.name))
18897
+ );
18898
+ }
18899
+ return ws;
18900
+ };
18901
+ at(void 0);
18902
+ pi.on("session_start", (_event, ctx) => {
18903
+ at(ctx);
18904
+ });
18670
18905
  pi.on(
18671
18906
  "before_agent_start",
18672
- (event, ctx) => hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
18907
+ async (event, ctx) => at(ctx)?.hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
18673
18908
  );
18674
- pi.on("agent_end", (event, ctx) => hooks.agentEnd(event, ctx.sessionManager.getSessionId()));
18909
+ pi.on(
18910
+ "agent_end",
18911
+ async (event, ctx) => at(ctx)?.hooks.agentEnd(
18912
+ event,
18913
+ ctx.sessionManager.getSessionId(),
18914
+ ctx.sessionManager.getBranch?.()
18915
+ )
18916
+ );
18917
+ pi.on("session_shutdown", async () => {
18918
+ await Promise.all([...workspaces.values()].map((ws) => ws?.hooks.sessionShutdown()));
18919
+ });
18675
18920
  };
18676
18921
  }
18677
18922