@vectorize-io/hindsight-coding-agents 0.5.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -9
- package/dist/antigravity-hook.js +424 -81
- package/dist/antigravity-statusline.js +56 -11
- package/dist/antigravity-stop-hook.js +515 -134
- package/dist/claude-hook.js +424 -81
- package/dist/claude-sessionstart-hook.js +392 -98
- package/dist/claude-stop-hook.js +515 -134
- package/dist/cline.js +218 -73
- package/dist/codex-hook.js +424 -81
- package/dist/codex-sessionstart-hook.js +392 -98
- package/dist/codex-stop-hook.js +515 -134
- package/dist/copilot-hook.js +424 -81
- package/dist/copilot-sessionstart-hook.js +392 -98
- package/dist/copilot-stop-hook.js +515 -134
- package/dist/cursor-hook.js +424 -81
- package/dist/cursor-sessionstart-hook.js +392 -98
- package/dist/cursor-stop-hook.js +515 -134
- package/dist/daemon-start.js +50 -9
- package/dist/dcode-hook.js +424 -81
- package/dist/dcode-sessionstart-hook.js +392 -98
- package/dist/dcode-stop-hook.js +515 -134
- package/dist/deepen.js +164 -27
- package/dist/devin-hook.js +424 -81
- package/dist/devin-sessionstart-hook.js +392 -98
- package/dist/devin-stop-hook.js +515 -134
- package/dist/droid-hook.js +2920 -0
- package/dist/droid-sessionstart-hook.js +3487 -0
- package/dist/droid-stop-hook.js +3188 -0
- package/dist/dsh.js +260 -109
- package/dist/grok-hook.js +424 -81
- package/dist/grok-sessionstart-hook.js +392 -98
- package/dist/grok-stop-hook.js +515 -134
- package/dist/hindsight-seed.js +56 -11
- package/dist/index.js +257 -110
- package/dist/installer.js +530 -223
- package/dist/kilo.js +257 -110
- package/dist/mcp-server.js +537 -146
- package/dist/opencode2.js +257 -110
- package/dist/pi.js +256 -109
- package/dist/prime-agent.js +256 -109
- package/dist/qwen-hook.js +424 -81
- package/dist/qwen-sessionstart-hook.js +392 -98
- package/dist/qwen-stop-hook.js +515 -134
- package/dist/status.js +128 -20
- package/dist/zcode-hook.js +2920 -0
- package/dist/zcode-sessionstart-hook.js +3487 -0
- package/dist/zcode-stop-hook.js +3188 -0
- package/package.json +11 -5
- package/plugin.json +1 -1
- package/skill/SKILL.md +42 -8
package/dist/qwen-stop-hook.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/core/hook.ts
|
|
4
|
-
import { existsSync as existsSync2, readFileSync as
|
|
4
|
+
import { existsSync as existsSync2, readFileSync as readFileSync5 } from "fs";
|
|
5
5
|
|
|
6
6
|
// src/core/bank.ts
|
|
7
7
|
import { existsSync } from "fs";
|
|
@@ -290,9 +290,13 @@ function isOptedIn(config, directory) {
|
|
|
290
290
|
const pathMap = config.mapPathToBank;
|
|
291
291
|
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
292
292
|
}
|
|
293
|
-
function
|
|
293
|
+
function mappedBank(config, directory, sessionRoot) {
|
|
294
294
|
const pathMap = config.mapPathToBank;
|
|
295
|
-
|
|
295
|
+
if (!directory || !pathMap) return void 0;
|
|
296
|
+
return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
|
|
297
|
+
}
|
|
298
|
+
function deriveBankId(config, directory, harness = "coding", sessionRoot) {
|
|
299
|
+
const mapped = mappedBank(config, directory, sessionRoot);
|
|
296
300
|
if (mapped) return mapped;
|
|
297
301
|
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
298
302
|
if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
|
|
@@ -331,6 +335,7 @@ import { fileURLToPath } from "url";
|
|
|
331
335
|
var DEFAULT_SEED_LIMIT = 300;
|
|
332
336
|
|
|
333
337
|
// src/core/missions.ts
|
|
338
|
+
import { createHash } from "crypto";
|
|
334
339
|
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.";
|
|
335
340
|
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.";
|
|
336
341
|
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.`;
|
|
@@ -442,17 +447,77 @@ function pagesFor(project) {
|
|
|
442
447
|
var PAGE_MAX_TOKENS = 4096;
|
|
443
448
|
var PAGE_TAGS_MATCH = "all";
|
|
444
449
|
var PAGE_FACT_TYPES = ["world", "experience", "observation"];
|
|
450
|
+
var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
|
|
451
|
+
var CRON_FIELD_RANGES = [
|
|
452
|
+
[0, 59],
|
|
453
|
+
// minute
|
|
454
|
+
[0, 23],
|
|
455
|
+
// hour
|
|
456
|
+
[1, 31],
|
|
457
|
+
// day of month
|
|
458
|
+
[1, 12],
|
|
459
|
+
// month
|
|
460
|
+
[0, 6]
|
|
461
|
+
// day of week
|
|
462
|
+
];
|
|
463
|
+
var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
|
|
464
|
+
function isHashedCron(cron) {
|
|
465
|
+
return /(^|\s)H/.test(cron);
|
|
466
|
+
}
|
|
467
|
+
function parseHashedCron(cron) {
|
|
468
|
+
const fields = cron.trim().split(/\s+/);
|
|
469
|
+
if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
|
|
470
|
+
for (const [i, field] of fields.entries()) {
|
|
471
|
+
if (!field.startsWith("H")) continue;
|
|
472
|
+
const m = HASHED_FIELD.exec(field);
|
|
473
|
+
if (!m) return void 0;
|
|
474
|
+
if (m[1] === void 0) continue;
|
|
475
|
+
const [lo, hi] = [Number(m[1]), Number(m[2])];
|
|
476
|
+
const [min, max] = CRON_FIELD_RANGES[i];
|
|
477
|
+
if (lo > hi || lo < min || hi > max) return void 0;
|
|
478
|
+
}
|
|
479
|
+
return fields;
|
|
480
|
+
}
|
|
481
|
+
function hashedValue(seed, field, lo, hi) {
|
|
482
|
+
const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
|
|
483
|
+
return lo + digest.readUInt32BE(0) % (hi - lo + 1);
|
|
484
|
+
}
|
|
485
|
+
function expandCronHash(cron, seed) {
|
|
486
|
+
if (!isHashedCron(cron)) return cron;
|
|
487
|
+
const fields = parseHashedCron(cron);
|
|
488
|
+
if (!fields) return cron;
|
|
489
|
+
return fields.map((field, i) => {
|
|
490
|
+
const m = HASHED_FIELD.exec(field);
|
|
491
|
+
if (!m) return field;
|
|
492
|
+
const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
|
|
493
|
+
return String(hashedValue(seed, i, lo, hi));
|
|
494
|
+
}).join(" ");
|
|
495
|
+
}
|
|
496
|
+
function pageTriggerFor(trigger, bank, page) {
|
|
497
|
+
const cron = trigger.refresh_cron;
|
|
498
|
+
if (!cron || !isHashedCron(cron)) return trigger;
|
|
499
|
+
return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
|
|
500
|
+
}
|
|
445
501
|
function buildPageTrigger(cfg = {}) {
|
|
446
502
|
const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
|
|
447
503
|
switch (cfg.pageTriggerType) {
|
|
448
|
-
case "
|
|
449
|
-
return { ...base,
|
|
504
|
+
case "auto-refresh":
|
|
505
|
+
return { ...base, refresh_after_consolidation: true };
|
|
450
506
|
case "manual":
|
|
451
507
|
return { ...base, refresh_after_consolidation: false };
|
|
508
|
+
// "cron" and an unset type alike: the default schedule stands in for a missing expression, so
|
|
509
|
+
// a trigger built from a partial config is never a cron trigger with nothing to fire on.
|
|
452
510
|
default:
|
|
453
|
-
return { ...base,
|
|
511
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
|
|
454
512
|
}
|
|
455
513
|
}
|
|
514
|
+
function pageTriggerDrifted(current2, desired) {
|
|
515
|
+
return current2.tags_match !== desired.tags_match || (current2.refresh_cron ?? null) !== (desired.refresh_cron ?? null) || Boolean(current2.refresh_after_consolidation) !== Boolean(desired.refresh_after_consolidation);
|
|
516
|
+
}
|
|
517
|
+
function pageTriggerPatch(desired) {
|
|
518
|
+
if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
|
|
519
|
+
return desired;
|
|
520
|
+
}
|
|
456
521
|
var CODING_BANK_TEMPLATE = {
|
|
457
522
|
version: "1",
|
|
458
523
|
bank: {
|
|
@@ -976,7 +1041,9 @@ var HindsightClient = class {
|
|
|
976
1041
|
source_query: page.source_query,
|
|
977
1042
|
tags: page.tags,
|
|
978
1043
|
max_tokens: PAGE_MAX_TOKENS,
|
|
979
|
-
|
|
1044
|
+
// Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
|
|
1045
|
+
// and one trigger is built per session for all of them.
|
|
1046
|
+
trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
|
|
980
1047
|
};
|
|
981
1048
|
if (!hit) {
|
|
982
1049
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
@@ -990,14 +1057,14 @@ var HindsightClient = class {
|
|
|
990
1057
|
if (r.status !== 409) created++;
|
|
991
1058
|
} else {
|
|
992
1059
|
const sourceDrift = hit.description !== page.source_query;
|
|
993
|
-
const triggerDrift = hit.trigger != null && hit.trigger
|
|
1060
|
+
const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
|
|
994
1061
|
if (!sourceDrift && !triggerDrift) continue;
|
|
995
1062
|
const patch = {};
|
|
996
1063
|
if (sourceDrift) {
|
|
997
1064
|
patch.source_query = page.source_query;
|
|
998
1065
|
patch.tags = page.tags;
|
|
999
1066
|
}
|
|
1000
|
-
if (triggerDrift) patch.trigger =
|
|
1067
|
+
if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
|
|
1001
1068
|
const r = await this.req(
|
|
1002
1069
|
"PATCH",
|
|
1003
1070
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
@@ -1013,10 +1080,42 @@ var HindsightClient = class {
|
|
|
1013
1080
|
updated++;
|
|
1014
1081
|
}
|
|
1015
1082
|
}
|
|
1083
|
+
const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
|
|
1016
1084
|
this.log(
|
|
1017
|
-
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
1085
|
+
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged` + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
|
|
1018
1086
|
);
|
|
1019
1087
|
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
|
|
1090
|
+
*
|
|
1091
|
+
* `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
|
|
1092
|
+
* an older default they are the same drift as the taxonomy — and on a real repo they are most of
|
|
1093
|
+
* it: five taxonomy pages against one page per initiative, each an LLM synthesis per
|
|
1094
|
+
* consolidation under the auto-refresh that used to be the default (#3506).
|
|
1095
|
+
*
|
|
1096
|
+
* Only the trigger is touched. Their `name` and `source_query` are written once, from the
|
|
1097
|
+
* initiative's own title, and re-stating either would rebuild a page whose question never
|
|
1098
|
+
* changed. The tree read above is reused rather than re-fetched.
|
|
1099
|
+
*/
|
|
1100
|
+
async resyncInitiativeTriggers(roots, pageTrigger) {
|
|
1101
|
+
const folder = roots.find(
|
|
1102
|
+
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
|
|
1103
|
+
);
|
|
1104
|
+
let updated = 0;
|
|
1105
|
+
for (const page of folder?.children ?? []) {
|
|
1106
|
+
if (page.kind !== "page" || page.trigger == null) continue;
|
|
1107
|
+
const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
|
|
1108
|
+
if (!pageTriggerDrifted(page.trigger, desired)) continue;
|
|
1109
|
+
const r = await this.req(
|
|
1110
|
+
"PATCH",
|
|
1111
|
+
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
|
|
1112
|
+
{ trigger: pageTriggerPatch(desired) }
|
|
1113
|
+
);
|
|
1114
|
+
if ([404, 405, 501].includes(r.status)) break;
|
|
1115
|
+
updated++;
|
|
1116
|
+
}
|
|
1117
|
+
return updated;
|
|
1118
|
+
}
|
|
1020
1119
|
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
1021
1120
|
slugify(s) {
|
|
1022
1121
|
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
@@ -1038,12 +1137,14 @@ var HindsightClient = class {
|
|
|
1038
1137
|
let pageId = args.relatesToPageId;
|
|
1039
1138
|
if (!pageId) {
|
|
1040
1139
|
const folderId = await this.ensureFolder("Initiatives");
|
|
1140
|
+
const subject = this.project ?? this.bank;
|
|
1041
1141
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
1042
1142
|
name: args.title,
|
|
1043
|
-
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
|
|
1143
|
+
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),
|
|
1044
1144
|
parent_id: folderId,
|
|
1045
1145
|
tags: ["knowledge:feature-work"],
|
|
1046
|
-
|
|
1146
|
+
max_tokens: PAGE_MAX_TOKENS,
|
|
1147
|
+
trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
|
|
1047
1148
|
});
|
|
1048
1149
|
try {
|
|
1049
1150
|
const j = await r.json();
|
|
@@ -1085,16 +1186,22 @@ var HindsightClient = class {
|
|
|
1085
1186
|
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
|
|
1086
1187
|
var DEFAULT_DAEMON_PORT = 9077;
|
|
1087
1188
|
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
1088
|
-
function
|
|
1089
|
-
if (raw.pageTriggerType === "manual") return "manual";
|
|
1090
|
-
if (raw.pageTriggerType === "
|
|
1091
|
-
|
|
1189
|
+
function resolvePageTrigger(raw) {
|
|
1190
|
+
if (raw.pageTriggerType === "manual") return { type: "manual" };
|
|
1191
|
+
if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
|
|
1192
|
+
if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
|
|
1092
1193
|
log.warn(
|
|
1093
1194
|
"config",
|
|
1094
|
-
|
|
1195
|
+
`ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
|
|
1095
1196
|
);
|
|
1096
|
-
|
|
1097
|
-
return "
|
|
1197
|
+
const cron = raw.pageTriggerCron?.trim();
|
|
1198
|
+
if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
|
|
1199
|
+
if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
|
|
1200
|
+
log.warn(
|
|
1201
|
+
"config",
|
|
1202
|
+
`pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to ${JSON.stringify(DEFAULT_PAGE_TRIGGER_CRON)}`
|
|
1203
|
+
);
|
|
1204
|
+
return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
|
|
1098
1205
|
}
|
|
1099
1206
|
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
1100
1207
|
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
@@ -1126,6 +1233,7 @@ function resolveObservationScopes(raw) {
|
|
|
1126
1233
|
function resolveConfig(raw = {}) {
|
|
1127
1234
|
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
1128
1235
|
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
1236
|
+
const pageTrigger = resolvePageTrigger(raw);
|
|
1129
1237
|
return {
|
|
1130
1238
|
serverMode,
|
|
1131
1239
|
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
@@ -1160,8 +1268,8 @@ function resolveConfig(raw = {}) {
|
|
|
1160
1268
|
reflectBudget: resolveReflectBudget(raw),
|
|
1161
1269
|
autoReflect: raw.autoReflect ?? true,
|
|
1162
1270
|
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
1163
|
-
pageTriggerType:
|
|
1164
|
-
pageTriggerCron:
|
|
1271
|
+
pageTriggerType: pageTrigger.type,
|
|
1272
|
+
pageTriggerCron: pageTrigger.cron,
|
|
1165
1273
|
autoSeed: raw.autoSeed ?? true,
|
|
1166
1274
|
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
1167
1275
|
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
@@ -1387,19 +1495,124 @@ function fileCursorStore(harness) {
|
|
|
1387
1495
|
};
|
|
1388
1496
|
}
|
|
1389
1497
|
|
|
1498
|
+
// src/core/turn-journal.ts
|
|
1499
|
+
import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, statSync } from "fs";
|
|
1500
|
+
import { tmpdir as tmpdir3 } from "os";
|
|
1501
|
+
import { dirname as dirname6, join as join8 } from "path";
|
|
1502
|
+
|
|
1503
|
+
// src/core/transcript-util.ts
|
|
1504
|
+
var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
|
|
1505
|
+
function stripInjectedMemory(s) {
|
|
1506
|
+
return s.replace(MEMORY_TAG_RE, "");
|
|
1507
|
+
}
|
|
1508
|
+
var TARGET_KEYS = [
|
|
1509
|
+
"file_path",
|
|
1510
|
+
"path",
|
|
1511
|
+
"notebook_path",
|
|
1512
|
+
"command",
|
|
1513
|
+
"pattern",
|
|
1514
|
+
"query",
|
|
1515
|
+
"url",
|
|
1516
|
+
"name",
|
|
1517
|
+
"id"
|
|
1518
|
+
];
|
|
1519
|
+
var ACTION_TARGET_CAP = 100;
|
|
1520
|
+
function actionLine(tool, input) {
|
|
1521
|
+
let target = "";
|
|
1522
|
+
if (input && typeof input === "object") {
|
|
1523
|
+
const rec = input;
|
|
1524
|
+
for (const k of TARGET_KEYS) {
|
|
1525
|
+
const v = rec[k];
|
|
1526
|
+
if (typeof v === "string" && v.trim()) {
|
|
1527
|
+
target = v.trim().split("\n")[0];
|
|
1528
|
+
break;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
} else if (typeof input === "string") {
|
|
1532
|
+
target = input.trim().split("\n")[0];
|
|
1533
|
+
}
|
|
1534
|
+
if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
|
|
1535
|
+
return target ? `${tool} ${target}` : tool;
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
// src/core/turn-journal.ts
|
|
1539
|
+
var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
|
|
1540
|
+
function journalPath(harness, sessionId) {
|
|
1541
|
+
return join8(tmpdir3(), `hindsight-${harness}`, `${sessionId || "no-session"}.journal.jsonl`);
|
|
1542
|
+
}
|
|
1543
|
+
function appendJournalTurn(path, turn) {
|
|
1544
|
+
const content = stripInjectedMemory(turn.content ?? "").trim();
|
|
1545
|
+
if (!content) return;
|
|
1546
|
+
try {
|
|
1547
|
+
if (statSync(path).size >= JOURNAL_MAX_BYTES) return;
|
|
1548
|
+
} catch {
|
|
1549
|
+
}
|
|
1550
|
+
const last = readJournalTranscript(path).at(-1);
|
|
1551
|
+
if (last && last.role === turn.role && last.content === content) return;
|
|
1552
|
+
try {
|
|
1553
|
+
mkdirSync3(dirname6(path), { recursive: true });
|
|
1554
|
+
appendFileSync3(
|
|
1555
|
+
path,
|
|
1556
|
+
JSON.stringify({
|
|
1557
|
+
role: turn.role,
|
|
1558
|
+
content,
|
|
1559
|
+
timestamp: turn.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1560
|
+
}) + "\n"
|
|
1561
|
+
);
|
|
1562
|
+
} catch {
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
function readJournalTranscript(path) {
|
|
1566
|
+
let body;
|
|
1567
|
+
try {
|
|
1568
|
+
body = readFileSync4(path, "utf8");
|
|
1569
|
+
} catch {
|
|
1570
|
+
return [];
|
|
1571
|
+
}
|
|
1572
|
+
const turns = [];
|
|
1573
|
+
for (const line of body.split("\n")) {
|
|
1574
|
+
const trimmed = line.trim();
|
|
1575
|
+
if (!trimmed) continue;
|
|
1576
|
+
let parsed;
|
|
1577
|
+
try {
|
|
1578
|
+
parsed = JSON.parse(trimmed);
|
|
1579
|
+
} catch {
|
|
1580
|
+
continue;
|
|
1581
|
+
}
|
|
1582
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
1583
|
+
const { role, content, timestamp } = parsed;
|
|
1584
|
+
if (typeof role !== "string" || typeof content !== "string" || !content) continue;
|
|
1585
|
+
turns.push({
|
|
1586
|
+
role,
|
|
1587
|
+
content,
|
|
1588
|
+
...typeof timestamp === "string" ? { timestamp } : {}
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
return turns;
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1390
1594
|
// src/core/retain-hook.ts
|
|
1391
|
-
import { readFileSync as
|
|
1595
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
1392
1596
|
|
|
1393
1597
|
// src/core/retain-cursor.ts
|
|
1394
|
-
import { createHash } from "crypto";
|
|
1598
|
+
import { createHash as createHash2 } from "crypto";
|
|
1599
|
+
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
1600
|
+
var PENDING_MAX_BYTES = 256 * 1024;
|
|
1601
|
+
function pendingReplayable(cursor, now) {
|
|
1602
|
+
const pending = cursor.pending ?? [];
|
|
1603
|
+
if (!pending.length) return true;
|
|
1604
|
+
if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
|
|
1605
|
+
return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
|
|
1606
|
+
}
|
|
1395
1607
|
function fingerprintTurns(turns, count) {
|
|
1396
|
-
const h =
|
|
1608
|
+
const h = createHash2("sha1").update(String(count));
|
|
1397
1609
|
for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
|
|
1398
1610
|
return h.digest("hex");
|
|
1399
1611
|
}
|
|
1400
1612
|
function planRetain(turns, cursor, opts) {
|
|
1401
1613
|
if (!turns.length) return { mode: "skip" };
|
|
1402
1614
|
if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
|
|
1615
|
+
if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
|
|
1403
1616
|
if (cursor.bank !== opts.bank) return { mode: "replace" };
|
|
1404
1617
|
if (cursor.turns > turns.length) return { mode: "replace" };
|
|
1405
1618
|
if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
|
|
@@ -1408,13 +1621,13 @@ function planRetain(turns, cursor, opts) {
|
|
|
1408
1621
|
}
|
|
1409
1622
|
|
|
1410
1623
|
// src/core/uuid.ts
|
|
1411
|
-
import { createHash as
|
|
1624
|
+
import { createHash as createHash3 } from "crypto";
|
|
1412
1625
|
var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
|
|
1413
1626
|
function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
|
|
1414
1627
|
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
1415
1628
|
if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
|
|
1416
1629
|
const bytes = Buffer.from(
|
|
1417
|
-
|
|
1630
|
+
createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
|
|
1418
1631
|
);
|
|
1419
1632
|
bytes[6] = bytes[6] & 15 | 80;
|
|
1420
1633
|
bytes[8] = bytes[8] & 63 | 128;
|
|
@@ -1491,66 +1704,88 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
|
|
|
1491
1704
|
);
|
|
1492
1705
|
}
|
|
1493
1706
|
async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
|
|
1707
|
+
if (!turns.length) return;
|
|
1494
1708
|
const refId = `conversation:${sessionId}`;
|
|
1495
1709
|
const appendSupported = Boolean(cursors) && await supportsAppend(client);
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1498
|
-
const
|
|
1710
|
+
const cursor = cursors?.read(sessionId);
|
|
1711
|
+
const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
|
|
1712
|
+
const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
|
|
1713
|
+
if (plan.mode === "skip" && !outbox.length) return;
|
|
1714
|
+
const opId = (mode, content) => uuidV5(`${client.bank}
|
|
1715
|
+
${refId}
|
|
1716
|
+
${mode}
|
|
1717
|
+
${content}`);
|
|
1718
|
+
const submit = (content, operationId, append) => client.retain(
|
|
1719
|
+
content,
|
|
1720
|
+
"coding agent session",
|
|
1721
|
+
refId,
|
|
1722
|
+
// Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
|
|
1723
|
+
// the documents list filters and draws its agent logo from, so a template cannot displace them.
|
|
1724
|
+
[
|
|
1725
|
+
.../* @__PURE__ */ new Set([
|
|
1726
|
+
...stamp?.tags ?? [],
|
|
1727
|
+
"source:chat",
|
|
1728
|
+
...harness ? [`harness:${harness}`] : []
|
|
1729
|
+
])
|
|
1730
|
+
],
|
|
1731
|
+
"conversation",
|
|
1732
|
+
{
|
|
1733
|
+
timestamp: startTs,
|
|
1734
|
+
updateMode: append ? "append" : void 0,
|
|
1735
|
+
operationId,
|
|
1736
|
+
metadata: {
|
|
1737
|
+
...stamp?.metadata,
|
|
1738
|
+
// configured first: the built-ins below win on any key collision
|
|
1739
|
+
source: "chat",
|
|
1740
|
+
session_id: sessionId,
|
|
1741
|
+
ref_id: refId,
|
|
1742
|
+
...harness ? { harness } : {}
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
);
|
|
1499
1746
|
const next = {
|
|
1500
1747
|
turns: turns.length,
|
|
1501
1748
|
fingerprint: fingerprintTurns(turns, turns.length),
|
|
1502
1749
|
bank: client.bank
|
|
1503
1750
|
};
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
}
|
|
1538
|
-
}
|
|
1539
|
-
),
|
|
1540
|
-
// Still ours to retry only while the cursor holds the claim we wrote above.
|
|
1541
|
-
() => {
|
|
1542
|
-
if (!cursors) return true;
|
|
1543
|
-
const now = cursors.read(sessionId);
|
|
1544
|
-
return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
|
|
1545
|
-
},
|
|
1546
|
-
retryUntil
|
|
1547
|
-
);
|
|
1548
|
-
cursors?.write(sessionId, next);
|
|
1751
|
+
const stillOurs = () => {
|
|
1752
|
+
if (!cursors) return true;
|
|
1753
|
+
const now = cursors.read(sessionId);
|
|
1754
|
+
return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
|
|
1755
|
+
};
|
|
1756
|
+
if (plan.mode === "replace") {
|
|
1757
|
+
const content = renderSessionJsonl(refId, turns, startTs);
|
|
1758
|
+
cursors?.write(sessionId, { ...next, dirty: true });
|
|
1759
|
+
await submitWithRetry(
|
|
1760
|
+
() => submit(content, opId("replace", content), false),
|
|
1761
|
+
stillOurs,
|
|
1762
|
+
retryUntil
|
|
1763
|
+
);
|
|
1764
|
+
cursors?.write(sessionId, next);
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1767
|
+
const queue = [...outbox];
|
|
1768
|
+
if (plan.mode === "append") {
|
|
1769
|
+
const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
|
|
1770
|
+
queue.push({ content, operationId: opId("append", content), at: Date.now() });
|
|
1771
|
+
}
|
|
1772
|
+
cursors?.write(sessionId, { ...next, pending: queue });
|
|
1773
|
+
for (let i = 0; i < queue.length; i++) {
|
|
1774
|
+
if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
|
|
1775
|
+
const entry = queue[i];
|
|
1776
|
+
await submitWithRetry(
|
|
1777
|
+
() => submit(entry.content, entry.operationId, true),
|
|
1778
|
+
stillOurs,
|
|
1779
|
+
retryUntil
|
|
1780
|
+
);
|
|
1781
|
+
const remaining = queue.slice(i + 1);
|
|
1782
|
+
cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
|
|
1783
|
+
}
|
|
1549
1784
|
}
|
|
1550
1785
|
|
|
1551
1786
|
// src/core/daemon.ts
|
|
1552
1787
|
import { execFileSync, spawn as realSpawn2 } from "child_process";
|
|
1553
|
-
import { dirname as
|
|
1788
|
+
import { dirname as dirname7, join as join9 } from "path";
|
|
1554
1789
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1555
1790
|
var DAEMON_WAIT_RETAIN_MS = 4e4;
|
|
1556
1791
|
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
@@ -1624,7 +1859,7 @@ function onPath(bin) {
|
|
|
1624
1859
|
}
|
|
1625
1860
|
function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
|
|
1626
1861
|
try {
|
|
1627
|
-
const starter =
|
|
1862
|
+
const starter = join9(dirname7(fileURLToPath2(import.meta.url)), "daemon-start.js");
|
|
1628
1863
|
const child = spawnFn("node", [starter, "--harness", harness], {
|
|
1629
1864
|
detached: true,
|
|
1630
1865
|
stdio: "ignore",
|
|
@@ -1725,7 +1960,7 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
1725
1960
|
}
|
|
1726
1961
|
|
|
1727
1962
|
// src/core/jsonl.ts
|
|
1728
|
-
import { closeSync, openSync, readSync, statSync } from "fs";
|
|
1963
|
+
import { closeSync, openSync, readSync, statSync as statSync2 } from "fs";
|
|
1729
1964
|
import { StringDecoder } from "string_decoder";
|
|
1730
1965
|
var CHUNK_BYTES = 64 * 1024;
|
|
1731
1966
|
var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
|
|
@@ -1733,7 +1968,7 @@ function readJsonlTail(path, opts) {
|
|
|
1733
1968
|
const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
|
|
1734
1969
|
let size;
|
|
1735
1970
|
try {
|
|
1736
|
-
size =
|
|
1971
|
+
size = statSync2(path).size;
|
|
1737
1972
|
} catch {
|
|
1738
1973
|
return { lines: emptyLines(), skippedBytes: 0 };
|
|
1739
1974
|
}
|
|
@@ -1785,41 +2020,6 @@ function* streamLines(path, start) {
|
|
|
1785
2020
|
}
|
|
1786
2021
|
}
|
|
1787
2022
|
|
|
1788
|
-
// src/core/transcript-util.ts
|
|
1789
|
-
var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
|
|
1790
|
-
function stripInjectedMemory(s) {
|
|
1791
|
-
return s.replace(MEMORY_TAG_RE, "");
|
|
1792
|
-
}
|
|
1793
|
-
var TARGET_KEYS = [
|
|
1794
|
-
"file_path",
|
|
1795
|
-
"path",
|
|
1796
|
-
"notebook_path",
|
|
1797
|
-
"command",
|
|
1798
|
-
"pattern",
|
|
1799
|
-
"query",
|
|
1800
|
-
"url",
|
|
1801
|
-
"name",
|
|
1802
|
-
"id"
|
|
1803
|
-
];
|
|
1804
|
-
var ACTION_TARGET_CAP = 100;
|
|
1805
|
-
function actionLine(tool, input) {
|
|
1806
|
-
let target = "";
|
|
1807
|
-
if (input && typeof input === "object") {
|
|
1808
|
-
const rec = input;
|
|
1809
|
-
for (const k of TARGET_KEYS) {
|
|
1810
|
-
const v = rec[k];
|
|
1811
|
-
if (typeof v === "string" && v.trim()) {
|
|
1812
|
-
target = v.trim().split("\n")[0];
|
|
1813
|
-
break;
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
} else if (typeof input === "string") {
|
|
1817
|
-
target = input.trim().split("\n")[0];
|
|
1818
|
-
}
|
|
1819
|
-
if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
|
|
1820
|
-
return target ? `${tool} ${target}` : tool;
|
|
1821
|
-
}
|
|
1822
|
-
|
|
1823
2023
|
// src/core/transcript.ts
|
|
1824
2024
|
function renderLine(content, type) {
|
|
1825
2025
|
if (typeof content === "string") {
|
|
@@ -1912,15 +2112,27 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1912
2112
|
const hostDeadline = Date.now() + spec.hostTimeoutSec * 1e3 - HOST_DEADLINE_MARGIN_MS;
|
|
1913
2113
|
let ev = {};
|
|
1914
2114
|
try {
|
|
1915
|
-
ev = JSON.parse(
|
|
2115
|
+
ev = JSON.parse(readFileSync6(0, "utf8"));
|
|
1916
2116
|
} catch {
|
|
1917
2117
|
return;
|
|
1918
2118
|
}
|
|
1919
|
-
|
|
2119
|
+
if (spec.accept && !spec.accept(ev)) return;
|
|
2120
|
+
const parsed = spec.parse(ev);
|
|
2121
|
+
const { sessionId, cwd: rawCwd, lastAssistantMessage } = parsed;
|
|
1920
2122
|
const cwd = rawCwd || process.cwd();
|
|
2123
|
+
let transcriptPath = parsed.transcriptPath;
|
|
2124
|
+
let readTranscript = spec.readTranscript;
|
|
1921
2125
|
let cfg = loadConfig({ harness: spec.harness });
|
|
1922
2126
|
setLogLevel(cfg.logLevel);
|
|
1923
2127
|
if (cfg.disabled) return;
|
|
2128
|
+
if (spec.journal) {
|
|
2129
|
+
transcriptPath = journalPath(spec.harness, sessionId);
|
|
2130
|
+
readTranscript = readJournalTranscript;
|
|
2131
|
+
appendJournalTurn(transcriptPath, {
|
|
2132
|
+
role: "assistant",
|
|
2133
|
+
content: spec.journal.assistantText(ev)
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
1924
2136
|
if (!transcriptPath) return;
|
|
1925
2137
|
const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
|
|
1926
2138
|
const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
|
|
@@ -1946,7 +2158,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1946
2158
|
sessionId: sessionId || "no-session",
|
|
1947
2159
|
transcriptPath,
|
|
1948
2160
|
client,
|
|
1949
|
-
readTranscript
|
|
2161
|
+
readTranscript,
|
|
1950
2162
|
lastAssistantMessage,
|
|
1951
2163
|
readLastMessage: spec.readLastMessage,
|
|
1952
2164
|
retryUntil: hostDeadline,
|
|
@@ -1961,7 +2173,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1961
2173
|
}
|
|
1962
2174
|
|
|
1963
2175
|
// src/core/session-start.ts
|
|
1964
|
-
import { readFileSync as
|
|
2176
|
+
import { readFileSync as readFileSync9 } from "fs";
|
|
1965
2177
|
|
|
1966
2178
|
// src/core/git.ts
|
|
1967
2179
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
@@ -1974,29 +2186,29 @@ import { execFileSync as execFileSync3 } from "child_process";
|
|
|
1974
2186
|
import { spawn as realSpawn3 } from "child_process";
|
|
1975
2187
|
import { existsSync as existsSync3 } from "fs";
|
|
1976
2188
|
import { homedir as homedir3 } from "os";
|
|
1977
|
-
import { dirname as
|
|
2189
|
+
import { dirname as dirname8, join as join10 } from "path";
|
|
1978
2190
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1979
2191
|
|
|
1980
2192
|
// src/core/auto-update.ts
|
|
1981
2193
|
import { spawn as realSpawn4 } from "child_process";
|
|
1982
2194
|
import {
|
|
1983
2195
|
existsSync as existsSync4,
|
|
1984
|
-
mkdirSync as
|
|
1985
|
-
readFileSync as
|
|
2196
|
+
mkdirSync as mkdirSync4,
|
|
2197
|
+
readFileSync as readFileSync7,
|
|
1986
2198
|
realpathSync as realpathSync2,
|
|
1987
2199
|
unlinkSync,
|
|
1988
2200
|
writeFileSync as writeFileSync2
|
|
1989
2201
|
} from "fs";
|
|
1990
|
-
import { homedir as homedir4, tmpdir as
|
|
1991
|
-
import { dirname as
|
|
2202
|
+
import { homedir as homedir4, tmpdir as tmpdir4 } from "os";
|
|
2203
|
+
import { dirname as dirname9, join as join11 } from "path";
|
|
1992
2204
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1993
2205
|
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
1994
2206
|
var LOCK_STALE_MS = 10 * 60 * 1e3;
|
|
1995
2207
|
|
|
1996
2208
|
// src/core/skill-sync.ts
|
|
1997
|
-
import { cpSync, existsSync as existsSync5, readFileSync as
|
|
2209
|
+
import { cpSync, existsSync as existsSync5, readFileSync as readFileSync8 } from "fs";
|
|
1998
2210
|
import { homedir as homedir5 } from "os";
|
|
1999
|
-
import { dirname as
|
|
2211
|
+
import { dirname as dirname10, join as join12 } from "path";
|
|
2000
2212
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
2001
2213
|
|
|
2002
2214
|
// src/core/transcript-codex.ts
|
|
@@ -2129,19 +2341,19 @@ function readCopilotTranscript(path) {
|
|
|
2129
2341
|
}
|
|
2130
2342
|
|
|
2131
2343
|
// src/core/transcript-grok.ts
|
|
2132
|
-
import { existsSync as existsSync6, readFileSync as
|
|
2344
|
+
import { existsSync as existsSync6, readFileSync as readFileSync10, readdirSync } from "fs";
|
|
2133
2345
|
import { homedir as homedir6 } from "os";
|
|
2134
|
-
import { join as
|
|
2346
|
+
import { join as join13 } from "path";
|
|
2135
2347
|
var CHAT_HISTORY = "chat_history.jsonl";
|
|
2136
|
-
function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
|
|
2137
|
-
const sessionsDir =
|
|
2138
|
-
const direct =
|
|
2348
|
+
function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join13(homedir6(), ".grok")) {
|
|
2349
|
+
const sessionsDir = join13(grokHome, "sessions");
|
|
2350
|
+
const direct = join13(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
|
|
2139
2351
|
if (existsSync6(direct)) return direct;
|
|
2140
2352
|
try {
|
|
2141
2353
|
for (const candidate of readdirSync(sessionsDir)) {
|
|
2142
|
-
const directory =
|
|
2143
|
-
if (
|
|
2144
|
-
return
|
|
2354
|
+
const directory = join13(sessionsDir, candidate);
|
|
2355
|
+
if (readFileSync10(join13(directory, ".cwd"), "utf8").trim() === cwd) {
|
|
2356
|
+
return join13(directory, sessionId, CHAT_HISTORY);
|
|
2145
2357
|
}
|
|
2146
2358
|
}
|
|
2147
2359
|
} catch {
|
|
@@ -2179,9 +2391,9 @@ function readGrokTranscript(path) {
|
|
|
2179
2391
|
import { existsSync as existsSync7 } from "fs";
|
|
2180
2392
|
import { createRequire } from "module";
|
|
2181
2393
|
import { homedir as homedir7 } from "os";
|
|
2182
|
-
import { join as
|
|
2394
|
+
import { join as join14 } from "path";
|
|
2183
2395
|
function devinSessionDb(home = homedir7()) {
|
|
2184
|
-
return
|
|
2396
|
+
return join14(home, ".local", "share", "devin", "cli", "sessions.db");
|
|
2185
2397
|
}
|
|
2186
2398
|
function parseDevinMessages(nodes) {
|
|
2187
2399
|
const messages = /* @__PURE__ */ new Map();
|
|
@@ -2446,6 +2658,95 @@ function collectQwenTurns(path, turns) {
|
|
|
2446
2658
|
}
|
|
2447
2659
|
}
|
|
2448
2660
|
|
|
2661
|
+
// src/core/transcript-droid.ts
|
|
2662
|
+
function renderContent(content, role) {
|
|
2663
|
+
if (!Array.isArray(content)) return [];
|
|
2664
|
+
const texts = [];
|
|
2665
|
+
const actions = [];
|
|
2666
|
+
for (const block of content) {
|
|
2667
|
+
if (!block || typeof block !== "object") continue;
|
|
2668
|
+
const b = block;
|
|
2669
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
2670
|
+
const text = stripInjectedMemory(b.text).trim();
|
|
2671
|
+
if (text) texts.push(text);
|
|
2672
|
+
} else if (b.type === "tool_use" && typeof b.name === "string") {
|
|
2673
|
+
actions.push({ role: "action", content: actionLine(b.name, b.input) });
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
const out = [];
|
|
2677
|
+
const joined = texts.join("\n").trim();
|
|
2678
|
+
if (joined) out.push({ role, content: joined });
|
|
2679
|
+
out.push(...actions);
|
|
2680
|
+
return out;
|
|
2681
|
+
}
|
|
2682
|
+
function readDroidTranscript(path) {
|
|
2683
|
+
const turns = [];
|
|
2684
|
+
for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
|
|
2685
|
+
if (!rawLine.trim()) continue;
|
|
2686
|
+
let parsed;
|
|
2687
|
+
try {
|
|
2688
|
+
parsed = JSON.parse(rawLine);
|
|
2689
|
+
} catch {
|
|
2690
|
+
continue;
|
|
2691
|
+
}
|
|
2692
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
2693
|
+
const line = parsed;
|
|
2694
|
+
if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
|
|
2695
|
+
const message = line.message;
|
|
2696
|
+
const role = message.role;
|
|
2697
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
2698
|
+
if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
|
|
2699
|
+
const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
|
|
2700
|
+
turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
|
|
2701
|
+
}
|
|
2702
|
+
return turns;
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
// src/core/transcript-zcode.ts
|
|
2706
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
2707
|
+
function messageText2(content) {
|
|
2708
|
+
if (typeof content === "string") return content.trim();
|
|
2709
|
+
if (!Array.isArray(content)) return "";
|
|
2710
|
+
return content.filter((block) => block && typeof block === "object" && typeof block.text === "string").map((block) => block.text.trim()).filter(Boolean).join("\n").trim();
|
|
2711
|
+
}
|
|
2712
|
+
function readZcodeTranscript(path) {
|
|
2713
|
+
if (!path) return [];
|
|
2714
|
+
let body;
|
|
2715
|
+
try {
|
|
2716
|
+
body = readFileSync11(path, "utf8");
|
|
2717
|
+
} catch {
|
|
2718
|
+
return [];
|
|
2719
|
+
}
|
|
2720
|
+
const turns = [];
|
|
2721
|
+
for (const line of body.split("\n")) {
|
|
2722
|
+
const trimmed = line.trim();
|
|
2723
|
+
if (!trimmed) continue;
|
|
2724
|
+
let parsed;
|
|
2725
|
+
try {
|
|
2726
|
+
parsed = JSON.parse(trimmed);
|
|
2727
|
+
} catch {
|
|
2728
|
+
continue;
|
|
2729
|
+
}
|
|
2730
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
2731
|
+
const record = parsed;
|
|
2732
|
+
const message = typeof record.message === "object" && record.message !== null ? record.message : void 0;
|
|
2733
|
+
const role = typeof message?.role === "string" ? message.role : record.type;
|
|
2734
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
2735
|
+
const content = stripInjectedMemory(messageText2(message?.content)).trim();
|
|
2736
|
+
if (!content) continue;
|
|
2737
|
+
turns.push({
|
|
2738
|
+
role,
|
|
2739
|
+
content,
|
|
2740
|
+
...typeof record.timestamp === "string" ? { timestamp: record.timestamp } : {}
|
|
2741
|
+
});
|
|
2742
|
+
}
|
|
2743
|
+
return turns;
|
|
2744
|
+
}
|
|
2745
|
+
function zcodeAssistantText(path) {
|
|
2746
|
+
if (!path) return "";
|
|
2747
|
+
return readZcodeTranscript(path).filter((turn) => turn.role === "assistant").at(-1)?.content ?? "";
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2449
2750
|
// src/harness/hook-lifecycle.ts
|
|
2450
2751
|
var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
|
|
2451
2752
|
var claudePrompt = {
|
|
@@ -2473,6 +2774,10 @@ var dcodePrompt = {
|
|
|
2473
2774
|
...claudePrompt,
|
|
2474
2775
|
harness: "dcode"
|
|
2475
2776
|
};
|
|
2777
|
+
var droidPrompt = {
|
|
2778
|
+
...claudePrompt,
|
|
2779
|
+
harness: "factory-droid"
|
|
2780
|
+
};
|
|
2476
2781
|
var qwenPrompt = {
|
|
2477
2782
|
...claudePrompt,
|
|
2478
2783
|
harness: "qwen-code",
|
|
@@ -2482,6 +2787,7 @@ var qwenPrompt = {
|
|
|
2482
2787
|
sessionId: ev.session_id
|
|
2483
2788
|
})
|
|
2484
2789
|
};
|
|
2790
|
+
var zcodeSessionId = (ev) => ev.session_id ?? ev.sessionId;
|
|
2485
2791
|
var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
|
|
2486
2792
|
var antigravityPrompt = {
|
|
2487
2793
|
harness: "antigravity-cli",
|
|
@@ -2799,6 +3105,81 @@ var HOOK_HARNESSES = {
|
|
|
2799
3105
|
}),
|
|
2800
3106
|
readTranscript: readQwenTranscript
|
|
2801
3107
|
}
|
|
3108
|
+
},
|
|
3109
|
+
"factory-droid": {
|
|
3110
|
+
configStyle: "nested",
|
|
3111
|
+
install: {
|
|
3112
|
+
sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
|
|
3113
|
+
prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
|
|
3114
|
+
stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
|
|
3115
|
+
},
|
|
3116
|
+
// Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
|
|
3117
|
+
// idempotent retain entry point captures that final partial turn; its event gate ignores every
|
|
3118
|
+
// other notification type before config or daemon work begins.
|
|
3119
|
+
additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
|
|
3120
|
+
sessionStart: standardSessionStart("factory-droid"),
|
|
3121
|
+
prompt: droidPrompt,
|
|
3122
|
+
retain: {
|
|
3123
|
+
hostTimeoutSec: 60,
|
|
3124
|
+
harness: "factory-droid",
|
|
3125
|
+
accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
|
|
3126
|
+
parse: (ev) => ({
|
|
3127
|
+
sessionId: ev.session_id,
|
|
3128
|
+
transcriptPath: ev.transcript_path,
|
|
3129
|
+
cwd: ev.cwd
|
|
3130
|
+
}),
|
|
3131
|
+
readTranscript: readDroidTranscript
|
|
3132
|
+
}
|
|
3133
|
+
},
|
|
3134
|
+
/**
|
|
3135
|
+
* ZCode (Z.ai's GLM coding agent) embeds the Claude Code agent runtime, so its hook PROTOCOL is
|
|
3136
|
+
* Claude's — `prompt`/`cwd` in, `hookSpecificOutput.additionalContext` + `systemMessage` out —
|
|
3137
|
+
* with `sessionId` accepted alongside `session_id`, which its Stop payload sends instead.
|
|
3138
|
+
*
|
|
3139
|
+
* What is not Claude's is the TRANSCRIPT, and that is the whole of the difference here. ZCode
|
|
3140
|
+
* keeps no durable session file: `Stop` carries the reply in `responseText` plus a temp,
|
|
3141
|
+
* assistant-only transcript it deletes as soon as the hook returns, and no user prompt at all.
|
|
3142
|
+
* So this is the one harness that retains from the plugin's own journal (core/turn-journal.ts) —
|
|
3143
|
+
* the prompt hook appends the user turn, `journal.assistantText` closes it with the reply — and
|
|
3144
|
+
* everything downstream (cursor, append, stamping) sees the same full conversation as any host
|
|
3145
|
+
* transcript.
|
|
3146
|
+
*/
|
|
3147
|
+
zcode: {
|
|
3148
|
+
configStyle: "process",
|
|
3149
|
+
// ZCode's `timeoutMs`, so MILLISECONDS — see the qwen-code note above for the same trap. The
|
|
3150
|
+
// prompt budget must stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
|
|
3151
|
+
timeoutUnit: "milliseconds",
|
|
3152
|
+
install: {
|
|
3153
|
+
sessionStart: { event: "SessionStart", entry: "zcode-sessionstart-hook.js", timeout: 3e4 },
|
|
3154
|
+
prompt: { event: "UserPromptSubmit", entry: "zcode-hook.js", timeout: 3e4 },
|
|
3155
|
+
stop: { event: "Stop", entry: "zcode-stop-hook.js", timeout: 6e4 }
|
|
3156
|
+
},
|
|
3157
|
+
sessionStart: {
|
|
3158
|
+
...standardSessionStart("zcode"),
|
|
3159
|
+
parse: (ev) => ({ cwd: ev.cwd, sessionId: zcodeSessionId(ev) })
|
|
3160
|
+
},
|
|
3161
|
+
prompt: {
|
|
3162
|
+
...claudePrompt,
|
|
3163
|
+
harness: "zcode",
|
|
3164
|
+
journalPrompt: true,
|
|
3165
|
+
parse: (ev) => ({
|
|
3166
|
+
prompt: ev.prompt ?? ev.user_prompt,
|
|
3167
|
+
cwd: ev.cwd,
|
|
3168
|
+
sessionId: zcodeSessionId(ev)
|
|
3169
|
+
})
|
|
3170
|
+
},
|
|
3171
|
+
retain: {
|
|
3172
|
+
hostTimeoutSec: 60,
|
|
3173
|
+
harness: "zcode",
|
|
3174
|
+
// No transcriptPath: the journal supplies it (see `journal` below).
|
|
3175
|
+
parse: (ev) => ({ sessionId: zcodeSessionId(ev), cwd: ev.cwd }),
|
|
3176
|
+
journal: {
|
|
3177
|
+
// `responseText` is the full reply and is what ZCode sends in practice. The ephemeral
|
|
3178
|
+
// transcript is the fallback when it is absent, and `responsePreview` — which is
|
|
3179
|
+
// TRUNCATED — is the last resort, preferred only over losing the turn entirely.
|
|
3180
|
+
assistantText: (ev) => (ev.responseText || zcodeAssistantText(ev.transcript_path) || ev.responsePreview || "").trim()
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
2802
3183
|
}
|
|
2803
3184
|
};
|
|
2804
3185
|
var runHarnessRetain = (harness) => runRetainHook(HOOK_HARNESSES[harness].retain);
|