@vectorize-io/hindsight-coding-agents 0.8.2 → 0.8.4

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 (64) hide show
  1. package/README.md +13 -3
  2. package/dist/antigravity-hook.js +95 -42
  3. package/dist/antigravity-statusline.js +6 -6
  4. package/dist/antigravity-stop-hook.js +132 -51
  5. package/dist/claude-hook.js +95 -42
  6. package/dist/claude-sessionstart-hook.js +385 -100
  7. package/dist/claude-stop-hook.js +132 -51
  8. package/dist/cline.js +403 -92
  9. package/dist/codebuddy-hook.js +95 -42
  10. package/dist/codebuddy-sessionstart-hook.js +385 -100
  11. package/dist/codebuddy-stop-hook.js +132 -51
  12. package/dist/codex-hook.js +95 -42
  13. package/dist/codex-sessionstart-hook.js +385 -100
  14. package/dist/codex-stop-hook.js +132 -51
  15. package/dist/copilot-hook.js +95 -42
  16. package/dist/copilot-sessionstart-hook.js +385 -100
  17. package/dist/copilot-stop-hook.js +132 -51
  18. package/dist/cursor-hook.js +95 -42
  19. package/dist/cursor-sessionstart-hook.js +385 -100
  20. package/dist/cursor-stop-hook.js +132 -51
  21. package/dist/daemon-start.js +10 -10
  22. package/dist/dcode-hook.js +95 -42
  23. package/dist/dcode-sessionstart-hook.js +385 -100
  24. package/dist/dcode-stop-hook.js +132 -51
  25. package/dist/deepen.js +82 -23
  26. package/dist/devin-hook.js +95 -42
  27. package/dist/devin-sessionstart-hook.js +385 -100
  28. package/dist/devin-stop-hook.js +132 -51
  29. package/dist/droid-hook.js +95 -42
  30. package/dist/droid-sessionstart-hook.js +385 -100
  31. package/dist/droid-stop-hook.js +132 -51
  32. package/dist/dsh.js +422 -99
  33. package/dist/grok-hook.js +95 -42
  34. package/dist/grok-sessionstart-hook.js +385 -100
  35. package/dist/grok-stop-hook.js +132 -51
  36. package/dist/hindsight-seed.js +6 -6
  37. package/dist/index.js +427 -111
  38. package/dist/installer.js +89 -80
  39. package/dist/kilo.js +427 -111
  40. package/dist/kimi-hook.js +95 -42
  41. package/dist/kimi-sessionstart-hook.js +385 -100
  42. package/dist/kimi-stop-hook.js +132 -51
  43. package/dist/mcp-server.js +169 -62
  44. package/dist/opencode2.js +583 -105
  45. package/dist/pi.js +403 -99
  46. package/dist/prime-agent.js +403 -99
  47. package/dist/qwen-hook.js +95 -42
  48. package/dist/qwen-sessionstart-hook.js +385 -100
  49. package/dist/qwen-stop-hook.js +132 -51
  50. package/dist/status.js +67 -17
  51. package/dist/survey-supervisor.js +73 -9
  52. package/dist/traecode-hook.js +95 -42
  53. package/dist/traecode-sessionstart-hook.js +385 -100
  54. package/dist/traecode-stop-hook.js +132 -51
  55. package/dist/workbuddy-hook.js +95 -42
  56. package/dist/workbuddy-sessionstart-hook.js +385 -100
  57. package/dist/workbuddy-stop-hook.js +132 -51
  58. package/dist/zcode-hook.js +95 -42
  59. package/dist/zcode-sessionstart-hook.js +385 -100
  60. package/dist/zcode-stop-hook.js +132 -51
  61. package/index.js +4 -1
  62. package/package.json +7 -4
  63. package/plugin.json +1 -1
  64. package/skill/SKILL.md +10 -2
package/dist/dsh.js CHANGED
@@ -228,14 +228,14 @@ function probeGitLayout(directory) {
228
228
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
229
229
  function applyTemplate(template, resolvers, what) {
230
230
  return template.replace(PLACEHOLDER, (_, name2) => {
231
- const resolve3 = resolvers[name2];
232
- if (!resolve3) {
231
+ const resolve4 = resolvers[name2];
232
+ if (!resolve4) {
233
233
  console.error(
234
234
  `hindsight: unknown ${what} placeholder "{${name2}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
235
235
  );
236
236
  return "unknown";
237
237
  }
238
- return resolve3();
238
+ return resolve4();
239
239
  });
240
240
  }
241
241
 
@@ -656,29 +656,33 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
656
656
  }
657
657
 
658
658
  // package.json
659
- var version = "0.8.2";
659
+ var version = "0.8.4";
660
660
 
661
661
  // src/core/util.ts
662
- import { accessSync, constants } from "fs";
663
- import { delimiter, join as join6 } from "path";
664
- function binOnPath(bin) {
665
- try {
666
- if (bin.includes("/")) {
667
- accessSync(bin, constants.X_OK);
662
+ import { accessSync, constants, statSync as statSync2 } from "fs";
663
+ import { delimiter, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "path";
664
+ function binOnPath(bin, opts = {}) {
665
+ const platform = opts.platform ?? process.platform;
666
+ const env = opts.env ?? process.env;
667
+ const runnable = (file2) => {
668
+ try {
669
+ if (!statSync2(file2).isFile()) return false;
670
+ if (platform !== "win32") accessSync(file2, constants.X_OK);
668
671
  return true;
672
+ } catch {
673
+ return false;
669
674
  }
670
- for (const dir of (process.env.PATH || "").split(delimiter)) {
671
- if (!dir) continue;
672
- try {
673
- accessSync(join6(dir, bin), constants.X_OK);
674
- return true;
675
- } catch {
676
- }
675
+ };
676
+ if (isAbsolute2(bin) || /[\\/]/.test(bin)) return runnable(bin) ? resolve2(bin) : void 0;
677
+ const names = platform !== "win32" || extname(bin) ? [bin] : (opts.exts ?? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";")).filter(Boolean).map((ext) => bin + ext.toLowerCase());
678
+ for (const dir of (env.PATH || "").split(delimiter)) {
679
+ if (!dir) continue;
680
+ for (const name2 of names) {
681
+ const file2 = join6(dir, name2);
682
+ if (runnable(file2)) return resolve2(file2);
677
683
  }
678
- return false;
679
- } catch {
680
- return false;
681
684
  }
685
+ return void 0;
682
686
  }
683
687
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
684
688
  function semverGte(version3, min) {
@@ -948,15 +952,19 @@ var HindsightClient = class {
948
952
  }
949
953
  /**
950
954
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
951
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
955
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed via the version endpoint; anything
952
956
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
957
+ * Only a "yes" is cached: a long-lived plugin client would otherwise keep replacing for the rest
958
+ * of the process after one probe that hit a restarting server (#5735).
953
959
  */
954
960
  async supportsIdempotentRetain() {
955
- if (this.idempotentRetain === void 0) {
956
- this.idempotentRetain = await this.probeIdempotentRetain();
957
- this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
961
+ if (this.idempotentRetain) return true;
962
+ const supported = await this.probeIdempotentRetain();
963
+ if (supported || this.idempotentRetain === void 0) {
964
+ this.log(`server retain idempotency: ${supported ? "supported" : "unavailable"}`);
958
965
  }
959
- return this.idempotentRetain;
966
+ this.idempotentRetain = supported;
967
+ return supported;
960
968
  }
961
969
  /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
962
970
  * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
@@ -1990,15 +1998,15 @@ function stagedVersion(pkgRoot) {
1990
1998
  }
1991
1999
  }
1992
2000
  function isNewer(candidate, current2) {
1993
- const parse3 = (v) => {
2001
+ const parse4 = (v) => {
1994
2002
  const [core = "", ...rest] = v.trim().split("-");
1995
2003
  return {
1996
2004
  nums: core.split(".").map((n) => Number.parseInt(n, 10)),
1997
2005
  pre: rest.length > 0
1998
2006
  };
1999
2007
  };
2000
- const a = parse3(candidate);
2001
- const b = parse3(current2);
2008
+ const a = parse4(candidate);
2009
+ const b = parse4(current2);
2002
2010
  if (a.nums.length !== 3 || b.nums.length !== 3) return false;
2003
2011
  if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
2004
2012
  for (let i = 0; i < 3; i++) {
@@ -2075,7 +2083,7 @@ function spawnNpm(spawnImpl, bin, args, opts) {
2075
2083
  return process.platform === "win32" ? spawnImpl([bin, ...args].join(" "), { ...opts, shell: true }) : spawnImpl(bin, args, opts);
2076
2084
  }
2077
2085
  async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
2078
- return new Promise((resolve3) => {
2086
+ return new Promise((resolve4) => {
2079
2087
  let out = "";
2080
2088
  let settled = false;
2081
2089
  let deadline;
@@ -2084,7 +2092,7 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
2084
2092
  settled = true;
2085
2093
  if (deadline) clearTimeout(deadline);
2086
2094
  if (reason) log.info("auto-update", `version check failed: ${reason}`);
2087
- resolve3(v);
2095
+ resolve4(v);
2088
2096
  };
2089
2097
  try {
2090
2098
  const child = spawnNpm(spawnImpl, "npm", ["view", pkg, "version", "--json"], {
@@ -2101,7 +2109,8 @@ async function npmViewVersion(pkg, spawnImpl = realSpawn2) {
2101
2109
  child.on("close", (code, signal) => {
2102
2110
  if (code !== 0) return done("", `npm view exited ${code ?? signal}`);
2103
2111
  try {
2104
- const v = JSON.parse(out.trim());
2112
+ const parsed = JSON.parse(out.trim());
2113
+ const v = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
2105
2114
  if (typeof v !== "string")
2106
2115
  return done("", `unparsable npm output: ${out.trim().slice(0, 80)}`);
2107
2116
  if (!RELEASE_RE.test(v)) return done("", `not a release: ${v.slice(0, 40)}`);
@@ -2281,8 +2290,8 @@ async function waitBounded(p, ms) {
2281
2290
  try {
2282
2291
  await Promise.race([
2283
2292
  p,
2284
- new Promise((resolve3) => {
2285
- timer = setTimeout(resolve3, Math.max(ms, 0));
2293
+ new Promise((resolve4) => {
2294
+ timer = setTimeout(resolve4, Math.max(ms, 0));
2286
2295
  })
2287
2296
  ]);
2288
2297
  } finally {
@@ -16927,7 +16936,7 @@ import { execFileSync as execFileSync4 } from "child_process";
16927
16936
 
16928
16937
  // src/core/git.ts
16929
16938
  import { execFileSync as execFileSync2 } from "child_process";
16930
- import { resolve as resolve2 } from "path";
16939
+ import { resolve as resolve3 } from "path";
16931
16940
 
16932
16941
  // src/core/uuid.ts
16933
16942
  import { createHash as createHash2 } from "crypto";
@@ -16955,18 +16964,25 @@ var US = "";
16955
16964
  var RS = "";
16956
16965
  var GITLOG_HEAD = "gitlog-head:";
16957
16966
  var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
16958
- function git(repo, ...args) {
16967
+ function runGit(repo, args, env) {
16959
16968
  return execFileSync2("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
16960
16969
  encoding: "utf8",
16961
16970
  maxBuffer: 1 << 28,
16962
16971
  windowsHide: true,
16972
+ env,
16963
16973
  // execFileSync otherwise forwards failed git stderr into the host's TUI,
16964
16974
  // even when callers catch the error. Keep diagnostics on the error instead.
16965
16975
  stdio: ["ignore", "pipe", "pipe"]
16966
16976
  });
16967
16977
  }
16978
+ function git(repo, ...args) {
16979
+ return runGit(repo, args);
16980
+ }
16981
+ function gitLocal(repo, ...args) {
16982
+ return runGit(repo, args, { ...process.env, GIT_NO_LAZY_FETCH: "1" });
16983
+ }
16968
16984
  function repoNameOf(repo) {
16969
- return projectNameOf(resolve2(repo));
16985
+ return projectNameOf(resolve3(repo));
16970
16986
  }
16971
16987
  function gitHeadSha(dir) {
16972
16988
  try {
@@ -16978,7 +16994,7 @@ function gitHeadSha(dir) {
16978
16994
  function commitsSince(dir, sinceSha) {
16979
16995
  if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
16980
16996
  try {
16981
- const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16997
+ const n = Number.parseInt(gitLocal(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
16982
16998
  return Number.isFinite(n) ? n : null;
16983
16999
  } catch {
16984
17000
  return null;
@@ -17004,11 +17020,197 @@ async function gitLogIsCurrent(client, repo, head) {
17004
17020
  // src/core/survey.ts
17005
17021
  import { execFileSync as execFileSync3, spawn as realSpawn5 } from "child_process";
17006
17022
  import { createHash as createHash3 } from "crypto";
17007
- import { existsSync as existsSync3 } from "fs";
17023
+ import { existsSync as existsSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
17008
17024
  import { homedir as homedir5, tmpdir as tmpdir2 } from "os";
17009
17025
  import { dirname as dirname7, join as join11 } from "path";
17010
17026
  import { fileURLToPath as fileURLToPath4 } from "url";
17011
17027
 
17028
+ // node_modules/smol-toml/dist/stringify.js
17029
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
17030
+ var HAS_WELLFORMED = !!"".isWellFormed;
17031
+ function extendedTypeOf(obj) {
17032
+ let type = typeof obj;
17033
+ if (type === "object") {
17034
+ if (Array.isArray(obj))
17035
+ return "array";
17036
+ if (typeof obj.getUTCDate === "function" && obj instanceof Date)
17037
+ return "date";
17038
+ if (globalThis.Temporal) {
17039
+ if (obj.until) {
17040
+ if (obj instanceof Temporal.ZonedDateTime)
17041
+ return "temporal/tz+uc";
17042
+ if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)
17043
+ return "temporal/uc";
17044
+ if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)
17045
+ return "temporal";
17046
+ if (obj instanceof Temporal.PlainYearMonth)
17047
+ return "temporal/x";
17048
+ } else if (obj.toPlainDate && obj instanceof Temporal.PlainMonthDay || obj.negated && obj instanceof Temporal.Duration) {
17049
+ return "temporal/x";
17050
+ }
17051
+ }
17052
+ }
17053
+ return type;
17054
+ }
17055
+ function isArrayOfTables(obj) {
17056
+ for (let i = 0; i < obj.length; i++) {
17057
+ if (extendedTypeOf(obj[i]) !== "object")
17058
+ return false;
17059
+ }
17060
+ return obj.length != 0;
17061
+ }
17062
+ function formatWellFormedStringUnchecked(s) {
17063
+ return JSON.stringify(s).replaceAll("\x7F", "\\u007f");
17064
+ }
17065
+ function formatString(s) {
17066
+ return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);
17067
+ }
17068
+ function formatKey(s) {
17069
+ if (BARE_KEY.test(s))
17070
+ return s;
17071
+ if (HAS_WELLFORMED && !s.isWellFormed())
17072
+ throw new RangeError("key contains illegal lone surrogates");
17073
+ return formatWellFormedStringUnchecked(s);
17074
+ }
17075
+ function stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {
17076
+ if (depth === 0) {
17077
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17078
+ }
17079
+ switch (type) {
17080
+ // @ts-expect-error -- intentional fallthrough case
17081
+ case "number":
17082
+ if (isNaN(val))
17083
+ return "nan";
17084
+ if (val === Infinity)
17085
+ return "inf";
17086
+ if (val === -Infinity)
17087
+ return "-inf";
17088
+ if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))
17089
+ return val.toFixed(1);
17090
+ case "bigint":
17091
+ case "boolean":
17092
+ case "temporal":
17093
+ return val.toString();
17094
+ case "string":
17095
+ return formatString(val);
17096
+ case "date":
17097
+ if (isNaN(val.getTime()))
17098
+ throw new TypeError("cannot serialize invalid date");
17099
+ return val.toISOString();
17100
+ case "object":
17101
+ return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);
17102
+ case "array":
17103
+ return stringifyArray(val, depth, numberAsFloat, strictTemporal);
17104
+ // @ts-expect-error -- intentional fallthrough case
17105
+ case "temporal/tz+uc":
17106
+ if (strictTemporal) {
17107
+ let tz = val.timeZoneId;
17108
+ let tzc = tz.charCodeAt(0);
17109
+ if (
17110
+ // Classic offset
17111
+ tzc !== 43 && tzc !== 45 && // Fast pre-check pass; see below for the actually accepted values
17112
+ (tzc !== 85 && tzc !== 71 && tzc !== 90 && tzc !== 69 || // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately
17113
+ tz !== "UTC" && tz !== "UCT" && tz !== "Universal" && tz !== "Zulu" && // GMT is a TZ but it's for all intents and purposes equivalent to UTC. Safe to downgrade.
17114
+ !tz.startsWith("GMT") && tz !== "Greenwich" && // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)
17115
+ !tz.startsWith("Etc/"))
17116
+ ) {
17117
+ throw new TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode");
17118
+ }
17119
+ }
17120
+ case "temporal/uc":
17121
+ if (strictTemporal && val.calendarId !== "iso8601")
17122
+ throw new TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");
17123
+ return val.toString({
17124
+ calendarName: "never",
17125
+ timeZoneName: "never"
17126
+ });
17127
+ case "temporal/x":
17128
+ throw new TypeError("Unsupported " + val[Symbol.toStringTag]);
17129
+ }
17130
+ }
17131
+ function stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {
17132
+ let keys = Object.keys(obj);
17133
+ if (keys.length === 0)
17134
+ return "{}";
17135
+ let res = "{ ";
17136
+ for (let i = 0; i < keys.length; i++) {
17137
+ let k = keys[i];
17138
+ if (i)
17139
+ res += ", ";
17140
+ res += formatKey(k) + " = " + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);
17141
+ }
17142
+ return res + " }";
17143
+ }
17144
+ function stringifyArray(array2, depth, numberAsFloat, strictTemporal) {
17145
+ if (array2.length === 0)
17146
+ return "[]";
17147
+ let res = "[ ";
17148
+ for (let i = 0; i < array2.length; i++) {
17149
+ if (i)
17150
+ res += ", ";
17151
+ if (array2[i] === null || array2[i] === void 0) {
17152
+ throw new TypeError("arrays cannot contain null or undefined values");
17153
+ }
17154
+ res += stringifyValue(array2[i], extendedTypeOf(array2[i]), depth - 1, numberAsFloat, strictTemporal);
17155
+ }
17156
+ return res + " ]";
17157
+ }
17158
+ function stringifyArrayTable(array2, key, depth, numberAsFloat, strictTemporal) {
17159
+ if (depth === 0) {
17160
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17161
+ }
17162
+ let res = "";
17163
+ for (let i = 0; i < array2.length; i++) {
17164
+ res += `${res && "\n"}[[${key}]]
17165
+ `;
17166
+ res += stringifyTable(0, array2[i], key, depth, numberAsFloat, strictTemporal);
17167
+ }
17168
+ return res;
17169
+ }
17170
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {
17171
+ if (depth === 0) {
17172
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
17173
+ }
17174
+ let preamble = "";
17175
+ let tables = "";
17176
+ let keys = Object.keys(obj);
17177
+ for (let i = 0; i < keys.length; i++) {
17178
+ let k = keys[i];
17179
+ if (obj[k] !== null && obj[k] !== void 0) {
17180
+ let type = extendedTypeOf(obj[k]);
17181
+ if (type === "symbol" || type === "function") {
17182
+ throw new TypeError(`cannot serialize values of type '${type}'`);
17183
+ }
17184
+ let key = formatKey(k);
17185
+ if (type === "array" && isArrayOfTables(obj[k])) {
17186
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);
17187
+ } else if (type === "object") {
17188
+ let tblKey = prefix ? `${prefix}.${key}` : key;
17189
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);
17190
+ } else {
17191
+ preamble += key;
17192
+ preamble += " = ";
17193
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);
17194
+ preamble += "\n";
17195
+ }
17196
+ }
17197
+ }
17198
+ if (tableKey && (preamble || !tables))
17199
+ preamble = preamble ? `[${tableKey}]
17200
+ ${preamble}` : `[${tableKey}]`;
17201
+ return preamble && tables ? `${preamble}
17202
+ ${tables}` : preamble || tables;
17203
+ }
17204
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false, strictTemporal = false } = {}) {
17205
+ if (extendedTypeOf(obj) !== "object") {
17206
+ throw new TypeError("stringify can only be called with an object");
17207
+ }
17208
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat, strictTemporal);
17209
+ if (str[str.length - 1] !== "\n")
17210
+ return str + "\n";
17211
+ return str;
17212
+ }
17213
+
17012
17214
  // src/core/survey-lease.ts
17013
17215
  import { spawn as realSpawn4 } from "child_process";
17014
17216
  import { randomUUID } from "crypto";
@@ -17019,7 +17221,7 @@ import {
17019
17221
  renameSync as renameSync2,
17020
17222
  rmdirSync,
17021
17223
  rmSync,
17022
- statSync as statSync2,
17224
+ statSync as statSync3,
17023
17225
  unlinkSync as unlinkSync2,
17024
17226
  utimesSync,
17025
17227
  writeFileSync as writeFileSync2
@@ -17056,7 +17258,7 @@ function reclaimIfStale(directory, staleMs) {
17056
17258
  return true;
17057
17259
  }
17058
17260
  if (owners.length !== 1) return false;
17059
- const age = Date.now() - statSync2(join10(directory, owners[0])).mtimeMs;
17261
+ const age = Date.now() - statSync3(join10(directory, owners[0])).mtimeMs;
17060
17262
  if (Math.abs(age) <= staleMs) return false;
17061
17263
  releaseLease({ directory, owner: owners[0] });
17062
17264
  return true;
@@ -17119,7 +17321,7 @@ function opencodeCanDefineSurveyAgent(bin) {
17119
17321
  windowsHide: true,
17120
17322
  stdio: ["ignore", "pipe", "ignore"]
17121
17323
  });
17122
- return Number(/(\d+)\./.exec(out)?.[1] ?? 0) >= 1;
17324
+ return Number(/(\d+)\./.exec(out)?.[1] ?? 0) === 1;
17123
17325
  } catch {
17124
17326
  return false;
17125
17327
  }
@@ -17134,6 +17336,7 @@ var SURVEY_DISALLOWED_TOOLS = [
17134
17336
  "WebSearch",
17135
17337
  "Task"
17136
17338
  ];
17339
+ var tomlValue = (value) => stringify({ v: value }).slice("v = ".length).trim();
17137
17340
  function buildSurveyPlan(harness, bin, repoDir, opts) {
17138
17341
  const env = {
17139
17342
  ...process.env,
@@ -17192,9 +17395,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17192
17395
  "-c",
17193
17396
  `mcp_servers.hindsight.command="node"`,
17194
17397
  "-c",
17195
- `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
17398
+ `mcp_servers.hindsight.args=${tomlValue([opts.mcpServerPath])}`,
17196
17399
  "-c",
17197
- `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
17400
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD=${tomlValue(repoDir)}`,
17198
17401
  "-c",
17199
17402
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
17200
17403
  SURVEY_PROMPT
@@ -17218,10 +17421,19 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
17218
17421
  }
17219
17422
  }
17220
17423
  }
17424
+ var SURVEY_MAX_ATTEMPTS = 3;
17425
+ function surveyAttempts(file2, sha) {
17426
+ try {
17427
+ const state = JSON.parse(readFileSync5(file2, "utf8"));
17428
+ return state.sha === sha && typeof state.attempts === "number" ? state.attempts : 0;
17429
+ } catch {
17430
+ return 0;
17431
+ }
17432
+ }
17221
17433
  async function startCodebaseSurvey(repoDir, opts = {}) {
17222
17434
  try {
17223
17435
  const spawnFn = opts.spawn ?? realSpawn5;
17224
- const exists = opts.exists ?? binOnPath;
17436
+ const resolveBin = opts.resolveBin ?? ((bin) => binOnPath(bin, { exts: [".exe"] }));
17225
17437
  const mcpServerPath = opts.mcpServerPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
17226
17438
  const preferred = opts.harness ?? "claude-code";
17227
17439
  const order = [
@@ -17235,10 +17447,16 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17235
17447
  for (const harness of order) {
17236
17448
  if (seen.has(harness)) continue;
17237
17449
  seen.add(harness);
17238
- const bin = resolveAgentBin(harness, opts.claudeBin);
17239
- if (!exists(bin)) continue;
17240
- if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin))
17450
+ const name2 = resolveAgentBin(harness, opts.claudeBin);
17451
+ const bin = resolveBin(name2);
17452
+ if (!bin) {
17453
+ log.info("survey", `${harness}: ${name2} not found, trying the next agent`);
17454
+ continue;
17455
+ }
17456
+ if (harness === "opencode" && !(opts.opencodeDefinesAgent ?? opencodeCanDefineSurveyAgent)(bin)) {
17457
+ log.info("survey", `${harness}: ${bin} cannot define the survey agent, trying the next`);
17241
17458
  continue;
17459
+ }
17242
17460
  const plan = buildSurveyPlan(harness, bin, repoDir, {
17243
17461
  model: opts.model,
17244
17462
  budgetUsd: opts.budgetUsd,
@@ -17247,12 +17465,19 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17247
17465
  const { cfg, bankId } = resolveHostConfig(harness, repoDir);
17248
17466
  if (cfg.disabled) return false;
17249
17467
  const key = createHash3("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
17250
- const lease = acquireLease(
17251
- opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys"),
17252
- key,
17253
- opts.lease?.staleMs ?? LEASE_STALE_MS
17254
- );
17468
+ const leaseDir = opts.lease?.dir ?? join11(tmpdir2(), "hindsight-coding-agent", "surveys");
17469
+ const lease = acquireLease(leaseDir, key, opts.lease?.staleMs ?? LEASE_STALE_MS);
17255
17470
  if (!lease) return false;
17471
+ const attemptsFile = join11(
17472
+ leaseDir,
17473
+ `attempts-${createHash3("sha256").update(JSON.stringify([key, repoDir])).digest("hex")}.json`
17474
+ );
17475
+ const attempts = opts.sha ? surveyAttempts(attemptsFile, opts.sha) : 0;
17476
+ if (attempts >= SURVEY_MAX_ATTEMPTS) {
17477
+ log.info("survey", `${attempts} surveys already launched at ${opts.sha}, skipping`);
17478
+ releaseLease(lease);
17479
+ return false;
17480
+ }
17256
17481
  const spec = {
17257
17482
  lease,
17258
17483
  bin: plan.bin,
@@ -17260,7 +17485,7 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17260
17485
  ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
17261
17486
  };
17262
17487
  const supervisorPath = opts.supervisorPath ?? join11(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
17263
- return await new Promise((resolve3) => {
17488
+ return await new Promise((resolve4) => {
17264
17489
  try {
17265
17490
  const child = spawnFn("node", [supervisorPath], {
17266
17491
  cwd: repoDir,
@@ -17270,19 +17495,31 @@ async function startCodebaseSurvey(repoDir, opts = {}) {
17270
17495
  env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
17271
17496
  });
17272
17497
  let spawned = false;
17273
- child.on("error", () => {
17498
+ child.on("error", (e) => {
17274
17499
  if (spawned) return;
17500
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17275
17501
  releaseLease(lease);
17276
- resolve3(false);
17502
+ resolve4(false);
17277
17503
  });
17278
17504
  child.once("spawn", () => {
17279
17505
  spawned = true;
17280
17506
  child.unref();
17281
- resolve3(true);
17507
+ if (opts.sha) {
17508
+ try {
17509
+ writeFileSync3(
17510
+ attemptsFile,
17511
+ JSON.stringify({ sha: opts.sha, attempts: attempts + 1 }),
17512
+ { mode: 384 }
17513
+ );
17514
+ } catch {
17515
+ }
17516
+ }
17517
+ resolve4(true);
17282
17518
  });
17283
- } catch {
17519
+ } catch (e) {
17520
+ log.warn("survey", `survey supervisor failed to launch: ${describeError(e)}`);
17284
17521
  releaseLease(lease);
17285
- resolve3(false);
17522
+ resolve4(false);
17286
17523
  }
17287
17524
  });
17288
17525
  }
@@ -17560,6 +17797,18 @@ function pendingReplayable(cursor, now) {
17560
17797
  if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
17561
17798
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
17562
17799
  }
17800
+ function advanceSegments(cursor, bank) {
17801
+ if (!cursor || cursor.bank === bank) return cursor?.segments;
17802
+ return [...cursor.segments ?? [{ bank: cursor.bank, from: 0 }], { bank, from: cursor.turns }];
17803
+ }
17804
+ function bankTurns(turns, segments, bank) {
17805
+ if (!segments) return turns;
17806
+ return turns.filter((_, i) => {
17807
+ let owner;
17808
+ for (const s of segments) if (s.from <= i) owner = s.bank;
17809
+ return owner === bank;
17810
+ });
17811
+ }
17563
17812
  var MAX_CURSOR_OPS = 8;
17564
17813
  function fingerprintTurns(turns, count) {
17565
17814
  const h = createHash5("sha1").update(String(count));
@@ -17570,7 +17819,8 @@ function planRetain(turns, cursor, opts) {
17570
17819
  if (!turns.length) return { mode: "skip" };
17571
17820
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
17572
17821
  if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
17573
- if (cursor.bank !== opts.bank) return { mode: "replace" };
17822
+ if (cursor.bank !== opts.bank && !cursor.segments?.some((s) => s.bank === opts.bank))
17823
+ return { mode: "replace" };
17574
17824
  const seen = cursor.paths ?? [];
17575
17825
  const newFile = Boolean(opts.path && seen.length && !seen.includes(opts.path));
17576
17826
  const continues = cursor.turns <= turns.length && fingerprintTurns(turns, cursor.turns) === cursor.fingerprint;
@@ -17691,8 +17941,17 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17691
17941
  let cursor = cursors?.read(sessionId);
17692
17942
  const probed = Boolean(cursors) && cursor?.appendSupported !== true;
17693
17943
  const appendSupported = Boolean(cursors) && (cursor?.appendSupported === true || await supportsAppend(client));
17944
+ const moved = Boolean(cursor && cursor.bank !== client.bank);
17945
+ if (moved)
17946
+ log.warn(harness ?? "", "session moved to another bank mid-session", {
17947
+ session: sessionId,
17948
+ from: cursor?.bank,
17949
+ to: client.bank,
17950
+ atTurn: cursor?.turns
17951
+ });
17952
+ const segments = advanceSegments(cursor, client.bank);
17694
17953
  let ops = [];
17695
- if (appendSupported && cursor?.ops?.length && !cursor.dirty)
17954
+ if (appendSupported && cursor?.ops?.length && !cursor.dirty && !moved)
17696
17955
  ({ cursor, ops } = await settleOps(client, cursor));
17697
17956
  const plan = planRetain(turns, cursor, {
17698
17957
  appendSupported,
@@ -17701,7 +17960,7 @@ async function writeSession(client, sessionId, turns, startTs, harness, stamp, c
17701
17960
  });
17702
17961
  if (probed) diag(harness ?? "", "retain_mode", { mode: plan.mode, appendSupported });
17703
17962
  const paths = plan.mode === "replace" ? transcriptPath ? [transcriptPath] : void 0 : advancePaths(cursor?.paths, transcriptPath);
17704
- const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
17963
+ const outbox = plan.mode === "replace" || moved ? [] : cursor?.pending ?? [];
17705
17964
  if (plan.mode === "skip" && !outbox.length) return;
17706
17965
  const opId = (mode, content) => uuidV5(`${client.bank}
17707
17966
  ${refId}
@@ -17743,6 +18002,7 @@ ${content}`);
17743
18002
  fingerprint: fingerprintTurns(turns, turns.length),
17744
18003
  bank: client.bank,
17745
18004
  ...paths ? { paths } : {},
18005
+ ...segments ? { segments } : {},
17746
18006
  ...appendSupported ? { appendSupported: true } : {}
17747
18007
  };
17748
18008
  const accepted = (id) => {
@@ -17755,9 +18015,14 @@ ${content}`);
17755
18015
  return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
17756
18016
  };
17757
18017
  if (plan.mode === "replace") {
17758
- const content = renderSessionJsonl(refId, turns, startTs);
18018
+ const share = bankTurns(turns, segments, client.bank);
18019
+ if (!share.length) return;
18020
+ const content = renderSessionJsonl(refId, share, startTs);
18021
+ const base = cursor ? `${cursor.turns}
18022
+ ${cursor.fingerprint}` : "";
17759
18023
  cursors?.write(sessionId, { ...next, dirty: true });
17760
- const operationId = opId("replace", content);
18024
+ const operationId = opId("replace", `${base}
18025
+ ${content}`);
17761
18026
  await submitWithRetry(() => submit(content, operationId, false), stillOurs, retryUntil);
17762
18027
  ops = [];
17763
18028
  cursors?.write(sessionId, accepted(operationId));
@@ -17784,7 +18049,7 @@ ${content}`);
17784
18049
  }
17785
18050
 
17786
18051
  // src/core/usage.ts
17787
- import { readFileSync as readFileSync5 } from "fs";
18052
+ import { readFileSync as readFileSync6 } from "fs";
17788
18053
  import { join as join13 } from "path";
17789
18054
  function usageFilePath() {
17790
18055
  return process.env.HINDSIGHT_USAGE_FILE || join13(logsDir(), "usage.jsonl");
@@ -17867,12 +18132,12 @@ function buildRetainStamp(cfg, ctx) {
17867
18132
  const base = resolversFor(ctx);
17868
18133
  const cache = /* @__PURE__ */ new Map();
17869
18134
  const resolvers = Object.fromEntries(
17870
- Object.entries(base).map(([name2, resolve3]) => [
18135
+ Object.entries(base).map(([name2, resolve4]) => [
17871
18136
  name2,
17872
18137
  () => {
17873
18138
  const hit = cache.get(name2);
17874
18139
  if (hit !== void 0) return hit;
17875
- const value = resolve3();
18140
+ const value = resolve4();
17876
18141
  cache.set(name2, value);
17877
18142
  return value;
17878
18143
  }
@@ -17892,7 +18157,7 @@ function buildRetainStamp(cfg, ctx) {
17892
18157
  }
17893
18158
 
17894
18159
  // src/core/skill-sync.ts
17895
- import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
18160
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
17896
18161
  import { homedir as homedir7 } from "os";
17897
18162
  import { dirname as dirname8, join as join15 } from "path";
17898
18163
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -17967,7 +18232,7 @@ function syncCompanionSkill(harness, opts = {}) {
17967
18232
  const dstMd = join15(dst, "SKILL.md");
17968
18233
  const installed = existsSync6(dstMd);
17969
18234
  if (!installed && !opts.install) return;
17970
- if (!installed || readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
18235
+ if (!installed || readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
17971
18236
  cpSync(src, dst, { recursive: true });
17972
18237
  }
17973
18238
  } catch {
@@ -17989,9 +18254,9 @@ function brandWord() {
17989
18254
  }
17990
18255
 
17991
18256
  // src/core/legacy.ts
17992
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
18257
+ import { existsSync as existsSync7, readFileSync as readFileSync8 } from "fs";
17993
18258
  import { homedir as homedir8 } from "os";
17994
- import { join as join16, relative, isAbsolute as isAbsolute2 } from "path";
18259
+ import { join as join16, relative, isAbsolute as isAbsolute3 } from "path";
17995
18260
  var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17996
18261
  function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")) {
17997
18262
  const registry2 = readJson(join16(claudeDir, "plugins", "installed_plugins.json"));
@@ -18006,7 +18271,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18006
18271
  if (!i || typeof i !== "object") return false;
18007
18272
  if (typeof i.projectPath !== "string") return true;
18008
18273
  const rel = relative(i.projectPath, cwd);
18009
- return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
18274
+ return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
18010
18275
  });
18011
18276
  if (active) return key;
18012
18277
  }
@@ -18014,7 +18279,7 @@ function detectLegacyClaudePlugin(cwd, claudeDir = join16(homedir8(), ".claude")
18014
18279
  }
18015
18280
  function readJson(path) {
18016
18281
  try {
18017
- const parsed = JSON.parse(readFileSync7(path, "utf8"));
18282
+ const parsed = JSON.parse(readFileSync8(path, "utf8"));
18018
18283
  return parsed && typeof parsed === "object" ? parsed : void 0;
18019
18284
  } catch {
18020
18285
  return void 0;
@@ -18026,7 +18291,7 @@ function legacyClaudePluginWarning(key) {
18026
18291
  }
18027
18292
 
18028
18293
  // src/core/session-cache.ts
18029
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
18294
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
18030
18295
  import { tmpdir as tmpdir3 } from "os";
18031
18296
  import { dirname as dirname9, join as join17 } from "path";
18032
18297
  function sessionCacheFile(harness, sessionId) {
@@ -18034,7 +18299,7 @@ function sessionCacheFile(harness, sessionId) {
18034
18299
  }
18035
18300
  function readSessionCache(cacheFile) {
18036
18301
  try {
18037
- return JSON.parse(readFileSync8(cacheFile, "utf8"));
18302
+ return JSON.parse(readFileSync9(cacheFile, "utf8"));
18038
18303
  } catch {
18039
18304
  return {};
18040
18305
  }
@@ -18043,7 +18308,7 @@ function writeFileAtomic(path, body) {
18043
18308
  mkdirSync4(dirname9(path), { recursive: true });
18044
18309
  const tmp = `${path}.${process.pid}.tmp`;
18045
18310
  try {
18046
- writeFileSync3(tmp, body);
18311
+ writeFileSync4(tmp, body);
18047
18312
  renameSync3(tmp, path);
18048
18313
  } catch (e) {
18049
18314
  try {
@@ -18153,12 +18418,13 @@ async function buildSessionStartContext(args) {
18153
18418
  startSeed(cwd, { limit: cfg.seedLimit, harness });
18154
18419
  if (cold) {
18155
18420
  if (cfg.codebaseSurvey !== false) {
18421
+ const sha = resolveHeadSha(cwd);
18156
18422
  const started = await startSurvey(cwd, {
18157
18423
  harness,
18158
18424
  model: cfg.surveyModel,
18159
- budgetUsd: cfg.surveyBudgetUsd
18425
+ budgetUsd: cfg.surveyBudgetUsd,
18426
+ sha: sha ?? void 0
18160
18427
  });
18161
- const sha = resolveHeadSha(cwd);
18162
18428
  if (started && sha) recordSurveyBaseline(sha);
18163
18429
  }
18164
18430
  diag(harness, "seed_started", { bank: bankId });
@@ -18179,7 +18445,8 @@ async function buildSessionStartContext(args) {
18179
18445
  const started = await startSurvey(cwd, {
18180
18446
  harness,
18181
18447
  model: cfg.surveyModel,
18182
- budgetUsd: cfg.surveyBudgetUsd
18448
+ budgetUsd: cfg.surveyBudgetUsd,
18449
+ sha
18183
18450
  });
18184
18451
  if (started) {
18185
18452
  recordSurveyBaseline(sha);
@@ -18281,7 +18548,7 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
18281
18548
  }
18282
18549
 
18283
18550
  // src/core/turn-journal.ts
18284
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, statSync as statSync3 } from "fs";
18551
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
18285
18552
  import { tmpdir as tmpdir4 } from "os";
18286
18553
  import { dirname as dirname10, join as join18 } from "path";
18287
18554
 
@@ -18532,8 +18799,6 @@ var RuntimeCore = class {
18532
18799
  fetchTranscript;
18533
18800
  /** Write-backs started and not yet settled — what `flush` waits for. */
18534
18801
  inFlight = /* @__PURE__ */ new Set();
18535
- lastInjection = "";
18536
- // most recent turn's injection block, keyed by nothing (see getInjection)
18537
18802
  deferInitialReflect = false;
18538
18803
  /** Host-notice channel (opencode/Kilo: client.tui.showToast via the adapter). Optional, fail-open. */
18539
18804
  notify;
@@ -18605,7 +18870,11 @@ var RuntimeCore = class {
18605
18870
  */
18606
18871
  async onPrompt(sessionId, prompt) {
18607
18872
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
18608
- if (!sessionId || !prompt.trim()) return;
18873
+ if (!sessionId) return;
18874
+ if (!prompt.trim()) {
18875
+ this.injection.delete(sessionId);
18876
+ return;
18877
+ }
18609
18878
  const turns = (this.turnCount.get(sessionId) ?? 0) + 1;
18610
18879
  this.turnCount.set(sessionId, turns);
18611
18880
  const cacheFile = sessionCacheFile(this.harness, sessionId);
@@ -18637,18 +18906,21 @@ var RuntimeCore = class {
18637
18906
  }
18638
18907
  const block = blocks.filter(Boolean).join("\n\n");
18639
18908
  this.injection.set(sessionId, block);
18640
- this.lastInjection = block;
18641
18909
  }
18642
18910
  /**
18643
- * The system-prompt text to inject this turn (built by the preceding onPrompt), or undefined.
18644
- * opencode's `experimental.chat.system.transform` hook fires with NO sessionId (input is just
18645
- * `{model}`), so a session-keyed lookup returns nothing there — fall back to the most recent
18646
- * turn's block (`lastInjection`). The completion's system.transform fires right after that
18647
- * session's `chat.message`/onPrompt, so `lastInjection` is this turn's block.
18911
+ * The text to inject into this turn's user message (built by the preceding onPrompt), or
18912
+ * undefined.
18913
+ *
18914
+ * It goes into the USER turn on every host, never the system prompt (#5914). The block changes
18915
+ * from turn to turn — the recall runs once, the roster refresh on a cadence — so a system prompt
18916
+ * carrying it differed between requests and broke the provider's prefix cache from that point
18917
+ * on. Persisted in the turn it belongs to, it leaves the system prompt and the earlier history
18918
+ * byte-identical. That used to need a fallback to the most recent block for opencode's
18919
+ * `experimental.chat.system.transform`, which fired with no session id; nothing reads it that
18920
+ * way any more.
18648
18921
  */
18649
18922
  getInjection(sessionId) {
18650
- const keyed = sessionId ? this.injection.get(sessionId) : void 0;
18651
- return keyed ?? this.lastInjection ?? void 0;
18923
+ return this.injection.get(sessionId) || void 0;
18652
18924
  }
18653
18925
  /**
18654
18926
  * Full normalized transcript (rich: user/assistant text + tool calls/outputs): upsert every turn
@@ -18828,6 +19100,9 @@ var liveAgents = /* @__PURE__ */ new Map();
18828
19100
  function dshSessionEvents(session) {
18829
19101
  return session.snapshotEvents?.() ?? session.events ?? [];
18830
19102
  }
19103
+ function ownEvents(session) {
19104
+ return dshSessionEvents(session).slice(session.inheritedEventCount ?? 0);
19105
+ }
18831
19106
  function workspaceRoot(agent) {
18832
19107
  return agent.session.header.cwd || process.cwd();
18833
19108
  }
@@ -18842,7 +19117,7 @@ function workspaceFor(root) {
18842
19117
  const core = new RuntimeCore(client, bankId, cfg, HARNESS2, root);
18843
19118
  core.setTranscriptSource(async (sessionId) => {
18844
19119
  const agent = liveAgents.get(sessionId);
18845
- return agent ? readDshEvents(dshSessionEvents(agent.session)) : [];
19120
+ return agent ? readDshEvents(ownEvents(agent.session)) : [];
18846
19121
  });
18847
19122
  const workspace = { core, root };
18848
19123
  workspaces.set(root, workspace);
@@ -18866,11 +19141,20 @@ function injectionMessage(text) {
18866
19141
  source: { kind: `plugin:${HINDSIGHT_PLUGIN}`, form: "recall" }
18867
19142
  };
18868
19143
  }
18869
- function createDshHooks(resolve3) {
18870
- const lastInjected = /* @__PURE__ */ new Map();
19144
+ function lastInjectedText(events) {
19145
+ for (let i = events.length - 1; i >= 0; i--) {
19146
+ const event = events[i];
19147
+ if (event?.type !== "user/message") continue;
19148
+ const message = event.data;
19149
+ if (message?.source?.kind !== `plugin:${HINDSIGHT_PLUGIN}`) continue;
19150
+ return (message.content ?? []).map((block) => block.text ?? "").join("\n");
19151
+ }
19152
+ return void 0;
19153
+ }
19154
+ function createDshHooks(resolve4) {
18871
19155
  return {
18872
19156
  sessionStart({ agent }) {
18873
- const workspace = resolve3(agent);
19157
+ const workspace = resolve4(agent);
18874
19158
  if (!workspace) return;
18875
19159
  liveAgents.set(agent.session.header.id, agent);
18876
19160
  ensureSeeded(workspace);
@@ -18878,7 +19162,7 @@ function createDshHooks(resolve3) {
18878
19162
  async preStep({ agent, signal }, next) {
18879
19163
  const decision = await next();
18880
19164
  if (decision.kind !== "enter" || signal.aborted) return decision;
18881
- const workspace = resolve3(agent);
19165
+ const workspace = resolve4(agent);
18882
19166
  if (!workspace) return decision;
18883
19167
  const sessionId = agent.session.header.id;
18884
19168
  liveAgents.set(sessionId, agent);
@@ -18891,16 +19175,15 @@ function createDshHooks(resolve3) {
18891
19175
  diag(HARNESS2, "inject_empty", { session: sessionId });
18892
19176
  return decision;
18893
19177
  }
18894
- if (injection === lastInjected.get(sessionId)) {
19178
+ if (injection === lastInjectedText(dshSessionEvents(agent.session))) {
18895
19179
  diag(HARNESS2, "inject_unchanged", { session: sessionId });
18896
19180
  return decision;
18897
19181
  }
18898
- lastInjected.set(sessionId, injection);
18899
19182
  diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
18900
19183
  return { kind: "enter", messages: [...decision.messages, injectionMessage(injection)] };
18901
19184
  },
18902
19185
  async turnStopping({ agent }) {
18903
- const workspace = resolve3(agent);
19186
+ const workspace = resolve4(agent);
18904
19187
  if (!workspace) return;
18905
19188
  const sessionId = agent.session.header.id;
18906
19189
  liveAgents.set(sessionId, agent);
@@ -18908,7 +19191,6 @@ function createDshHooks(resolve3) {
18908
19191
  },
18909
19192
  disposed({ agent }) {
18910
19193
  liveAgents.delete(agent.session.header.id);
18911
- lastInjected.delete(agent.session.header.id);
18912
19194
  }
18913
19195
  };
18914
19196
  }
@@ -18986,6 +19268,47 @@ export {
18986
19268
  dsh_default as default,
18987
19269
  dshSessionEvents,
18988
19270
  inject,
19271
+ lastInjectedText,
18989
19272
  name,
19273
+ ownEvents,
18990
19274
  toDshParameters
18991
19275
  };
19276
+ /*! Bundled license information:
19277
+
19278
+ smol-toml/dist/error.js:
19279
+ smol-toml/dist/primitive.js:
19280
+ smol-toml/dist/date.js:
19281
+ smol-toml/dist/extract.js:
19282
+ smol-toml/dist/util.js:
19283
+ smol-toml/dist/struct.js:
19284
+ smol-toml/dist/parse.js:
19285
+ smol-toml/dist/stringify.js:
19286
+ smol-toml/dist/index.js:
19287
+ (*!
19288
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
19289
+ * SPDX-License-Identifier: BSD-3-Clause
19290
+ *
19291
+ * Redistribution and use in source and binary forms, with or without
19292
+ * modification, are permitted provided that the following conditions are met:
19293
+ *
19294
+ * 1. Redistributions of source code must retain the above copyright notice, this
19295
+ * list of conditions and the following disclaimer.
19296
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
19297
+ * this list of conditions and the following disclaimer in the
19298
+ * documentation and/or other materials provided with the distribution.
19299
+ * 3. Neither the name of the copyright holder nor the names of its contributors
19300
+ * may be used to endorse or promote products derived from this software without
19301
+ * specific prior written permission.
19302
+ *
19303
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19304
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19305
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19306
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19307
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19308
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19309
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
19310
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
19311
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
19312
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
19313
+ *)
19314
+ */