@vectorize-io/hindsight-coding-agents 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +201 -16
- package/dist/antigravity-hook.js +1132 -115
- package/dist/antigravity-statusline.js +77 -11
- package/dist/antigravity-stop-hook.js +1193 -133
- package/dist/claude-hook.js +1132 -115
- package/dist/claude-sessionstart-hook.js +1241 -140
- package/dist/claude-stop-hook.js +1193 -133
- package/dist/cline.js +578 -163
- package/dist/codebuddy-hook.js +4270 -0
- package/dist/codebuddy-sessionstart-hook.js +5030 -0
- package/dist/codebuddy-stop-hook.js +4564 -0
- package/dist/codex-hook.js +1132 -115
- package/dist/codex-sessionstart-hook.js +1241 -140
- package/dist/codex-stop-hook.js +1193 -133
- package/dist/copilot-hook.js +1132 -115
- package/dist/copilot-sessionstart-hook.js +1241 -140
- package/dist/copilot-stop-hook.js +1193 -133
- package/dist/cursor-hook.js +1132 -115
- package/dist/cursor-sessionstart-hook.js +1241 -140
- package/dist/cursor-stop-hook.js +1193 -133
- package/dist/daemon-start.js +54 -9
- package/dist/dcode-hook.js +1132 -115
- package/dist/dcode-sessionstart-hook.js +1241 -140
- package/dist/dcode-stop-hook.js +1193 -133
- package/dist/deepen.js +370 -104
- package/dist/devin-hook.js +1132 -115
- package/dist/devin-sessionstart-hook.js +1241 -140
- package/dist/devin-stop-hook.js +1193 -133
- package/dist/droid-hook.js +1132 -115
- package/dist/droid-sessionstart-hook.js +1241 -140
- package/dist/droid-stop-hook.js +1193 -133
- package/dist/dsh.js +586 -164
- package/dist/grok-hook.js +1132 -115
- package/dist/grok-sessionstart-hook.js +1241 -140
- package/dist/grok-stop-hook.js +1193 -133
- package/dist/hindsight-seed.js +50 -8
- package/dist/index.js +587 -172
- package/dist/installer.js +2010 -769
- package/dist/kilo.js +587 -172
- package/dist/kimi-hook.js +4270 -0
- package/dist/kimi-sessionstart-hook.js +5030 -0
- package/dist/kimi-stop-hook.js +4564 -0
- package/dist/mcp-server.js +419 -115
- package/dist/opencode2.js +586 -169
- package/dist/pi.js +644 -175
- package/dist/prime-agent.js +644 -175
- package/dist/qwen-hook.js +1132 -115
- package/dist/qwen-sessionstart-hook.js +1241 -140
- package/dist/qwen-stop-hook.js +1193 -133
- package/dist/status.js +243 -52
- package/dist/traecode-hook.js +4270 -0
- package/dist/traecode-sessionstart-hook.js +5030 -0
- package/dist/traecode-stop-hook.js +4564 -0
- package/dist/workbuddy-hook.js +4270 -0
- package/dist/workbuddy-sessionstart-hook.js +5030 -0
- package/dist/workbuddy-stop-hook.js +4564 -0
- package/dist/zcode-hook.js +1132 -115
- package/dist/zcode-sessionstart-hook.js +1241 -140
- package/dist/zcode-stop-hook.js +1193 -133
- package/package.json +22 -12
- package/plugin.json +1 -1
- package/skill/SKILL.md +73 -14
package/dist/mcp-server.js
CHANGED
|
@@ -8059,11 +8059,11 @@ function datetimeRegex(args) {
|
|
|
8059
8059
|
regex = `${regex}(${opts.join("|")})`;
|
|
8060
8060
|
return new RegExp(`^${regex}$`);
|
|
8061
8061
|
}
|
|
8062
|
-
function isValidIP(ip,
|
|
8063
|
-
if ((
|
|
8062
|
+
function isValidIP(ip, version3) {
|
|
8063
|
+
if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
|
|
8064
8064
|
return true;
|
|
8065
8065
|
}
|
|
8066
|
-
if ((
|
|
8066
|
+
if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
|
|
8067
8067
|
return true;
|
|
8068
8068
|
}
|
|
8069
8069
|
return false;
|
|
@@ -8090,11 +8090,11 @@ function isValidJWT(jwt2, alg) {
|
|
|
8090
8090
|
return false;
|
|
8091
8091
|
}
|
|
8092
8092
|
}
|
|
8093
|
-
function isValidCidr(ip,
|
|
8094
|
-
if ((
|
|
8093
|
+
function isValidCidr(ip, version3) {
|
|
8094
|
+
if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
|
|
8095
8095
|
return true;
|
|
8096
8096
|
}
|
|
8097
|
-
if ((
|
|
8097
|
+
if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
|
|
8098
8098
|
return true;
|
|
8099
8099
|
}
|
|
8100
8100
|
return false;
|
|
@@ -12428,10 +12428,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
|
12428
12428
|
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
12429
12429
|
var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
|
12430
12430
|
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
12431
|
-
var uuid = (
|
|
12432
|
-
if (!
|
|
12431
|
+
var uuid = (version3) => {
|
|
12432
|
+
if (!version3)
|
|
12433
12433
|
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
|
|
12434
|
-
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${
|
|
12434
|
+
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
12435
12435
|
};
|
|
12436
12436
|
var uuid4 = /* @__PURE__ */ uuid(4);
|
|
12437
12437
|
var uuid6 = /* @__PURE__ */ uuid(6);
|
|
@@ -23354,17 +23354,33 @@ function normalizeObjectSchema(schema) {
|
|
|
23354
23354
|
}
|
|
23355
23355
|
return void 0;
|
|
23356
23356
|
}
|
|
23357
|
+
function getDotPath(path) {
|
|
23358
|
+
if (path.length === 0) {
|
|
23359
|
+
return "object root";
|
|
23360
|
+
}
|
|
23361
|
+
return path.reduce((acc, seg, index) => {
|
|
23362
|
+
if (index === 0) {
|
|
23363
|
+
return String(seg);
|
|
23364
|
+
}
|
|
23365
|
+
if (typeof seg === "number") {
|
|
23366
|
+
return `${acc}[${seg}]`;
|
|
23367
|
+
}
|
|
23368
|
+
return `${acc}.${seg}`;
|
|
23369
|
+
}, "");
|
|
23370
|
+
}
|
|
23357
23371
|
function getParseErrorMessage(error51) {
|
|
23358
23372
|
if (error51 && typeof error51 === "object") {
|
|
23373
|
+
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23374
|
+
return error51.issues.map((i) => {
|
|
23375
|
+
if (!i.path?.length) {
|
|
23376
|
+
return i.message;
|
|
23377
|
+
}
|
|
23378
|
+
return `${i.message} at ${getDotPath(i.path)}`;
|
|
23379
|
+
}).join("\n");
|
|
23380
|
+
}
|
|
23359
23381
|
if ("message" in error51 && typeof error51.message === "string") {
|
|
23360
23382
|
return error51.message;
|
|
23361
23383
|
}
|
|
23362
|
-
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23363
|
-
const firstIssue = error51.issues[0];
|
|
23364
|
-
if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
|
|
23365
|
-
return String(firstIssue.message);
|
|
23366
|
-
}
|
|
23367
|
-
}
|
|
23368
23384
|
try {
|
|
23369
23385
|
return JSON.stringify(error51);
|
|
23370
23386
|
} catch {
|
|
@@ -25740,10 +25756,10 @@ function fromJSONSchema(schema, params) {
|
|
|
25740
25756
|
} catch {
|
|
25741
25757
|
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
|
|
25742
25758
|
}
|
|
25743
|
-
const
|
|
25759
|
+
const version3 = detectVersion(normalized, params?.defaultTarget);
|
|
25744
25760
|
const defs = normalized.$defs || normalized.definitions || {};
|
|
25745
25761
|
const ctx = {
|
|
25746
|
-
version:
|
|
25762
|
+
version: version3,
|
|
25747
25763
|
defs,
|
|
25748
25764
|
refs: /* @__PURE__ */ new Map(),
|
|
25749
25765
|
processing: /* @__PURE__ */ new Set(),
|
|
@@ -28684,6 +28700,9 @@ var Protocol = class {
|
|
|
28684
28700
|
this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
|
|
28685
28701
|
const handleTaskResult = async () => {
|
|
28686
28702
|
const taskId = request.params.taskId;
|
|
28703
|
+
if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
|
|
28704
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
28705
|
+
}
|
|
28687
28706
|
if (this._taskMessageQueue) {
|
|
28688
28707
|
let queuedMessage;
|
|
28689
28708
|
while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
|
|
@@ -28714,12 +28733,12 @@ var Protocol = class {
|
|
|
28714
28733
|
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
28715
28734
|
}
|
|
28716
28735
|
if (!isTerminal(task.status)) {
|
|
28717
|
-
await this._waitForTaskUpdate(taskId, extra.signal);
|
|
28736
|
+
await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
|
|
28718
28737
|
return await handleTaskResult();
|
|
28719
28738
|
}
|
|
28720
28739
|
if (isTerminal(task.status)) {
|
|
28721
28740
|
const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
|
|
28722
|
-
this._clearTaskQueue(taskId);
|
|
28741
|
+
this._clearTaskQueue(taskId, extra.sessionId);
|
|
28723
28742
|
return {
|
|
28724
28743
|
...result,
|
|
28725
28744
|
_meta: {
|
|
@@ -28756,7 +28775,7 @@ var Protocol = class {
|
|
|
28756
28775
|
throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
|
|
28757
28776
|
}
|
|
28758
28777
|
await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
|
|
28759
|
-
this._clearTaskQueue(request.params.taskId);
|
|
28778
|
+
this._clearTaskQueue(request.params.taskId, extra.sessionId);
|
|
28760
28779
|
const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
28761
28780
|
if (!cancelledTask) {
|
|
28762
28781
|
throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
|
|
@@ -28884,6 +28903,19 @@ var Protocol = class {
|
|
|
28884
28903
|
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
|
|
28885
28904
|
const capturedTransport = this._transport;
|
|
28886
28905
|
const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
|
|
28906
|
+
const sessionId = capturedTransport?.sessionId;
|
|
28907
|
+
const store = this._taskStore;
|
|
28908
|
+
let relatedTaskFound = true;
|
|
28909
|
+
let relatedTaskLookup;
|
|
28910
|
+
if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
|
|
28911
|
+
relatedTaskFound = false;
|
|
28912
|
+
relatedTaskLookup = (async () => {
|
|
28913
|
+
if (!await store.getTask(relatedTaskId, sessionId)) {
|
|
28914
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
|
|
28915
|
+
}
|
|
28916
|
+
relatedTaskFound = true;
|
|
28917
|
+
})();
|
|
28918
|
+
}
|
|
28887
28919
|
if (handler === void 0) {
|
|
28888
28920
|
const errorResponse = {
|
|
28889
28921
|
jsonrpc: "2.0",
|
|
@@ -28893,7 +28925,10 @@ var Protocol = class {
|
|
|
28893
28925
|
message: "Method not found"
|
|
28894
28926
|
}
|
|
28895
28927
|
};
|
|
28896
|
-
if (relatedTaskId &&
|
|
28928
|
+
if (relatedTaskId && relatedTaskLookup) {
|
|
28929
|
+
const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
|
|
28930
|
+
relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error51) => this._onerror(new Error(`Failed to send an error response: ${error51}`)));
|
|
28931
|
+
} else if (relatedTaskId && this._taskMessageQueue) {
|
|
28897
28932
|
this._enqueueTaskMessage(relatedTaskId, {
|
|
28898
28933
|
type: "error",
|
|
28899
28934
|
message: errorResponse,
|
|
@@ -28944,7 +28979,10 @@ var Protocol = class {
|
|
|
28944
28979
|
closeSSEStream: extra?.closeSSEStream,
|
|
28945
28980
|
closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
|
|
28946
28981
|
};
|
|
28947
|
-
Promise.resolve().then(() => {
|
|
28982
|
+
(relatedTaskLookup ?? Promise.resolve()).then(() => {
|
|
28983
|
+
if (relatedTaskLookup && abortController.signal.aborted) {
|
|
28984
|
+
throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
|
|
28985
|
+
}
|
|
28948
28986
|
if (taskCreationParams) {
|
|
28949
28987
|
this.assertTaskHandlerCapability(request.method);
|
|
28950
28988
|
}
|
|
@@ -28979,7 +29017,7 @@ var Protocol = class {
|
|
|
28979
29017
|
...error51["data"] !== void 0 && { data: error51["data"] }
|
|
28980
29018
|
}
|
|
28981
29019
|
};
|
|
28982
|
-
if (relatedTaskId && this._taskMessageQueue) {
|
|
29020
|
+
if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
|
|
28983
29021
|
await this._enqueueTaskMessage(relatedTaskId, {
|
|
28984
29022
|
type: "error",
|
|
28985
29023
|
message: errorResponse,
|
|
@@ -29459,7 +29497,7 @@ var Protocol = class {
|
|
|
29459
29497
|
throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
|
|
29460
29498
|
}
|
|
29461
29499
|
const maxQueueSize = this._options?.maxTaskQueueSize;
|
|
29462
|
-
await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
|
|
29500
|
+
await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
|
|
29463
29501
|
}
|
|
29464
29502
|
/**
|
|
29465
29503
|
* Clears the message queue for a task and rejects any pending request resolvers.
|
|
@@ -29488,12 +29526,13 @@ var Protocol = class {
|
|
|
29488
29526
|
* Uses polling to check for updates at the task's configured poll interval.
|
|
29489
29527
|
* @param taskId The task ID to wait for
|
|
29490
29528
|
* @param signal Abort signal to cancel the wait
|
|
29529
|
+
* @param sessionId Session of the request that waits, passed to the task store
|
|
29491
29530
|
* @returns Promise that resolves when an update occurs or rejects if aborted
|
|
29492
29531
|
*/
|
|
29493
|
-
async _waitForTaskUpdate(taskId, signal) {
|
|
29532
|
+
async _waitForTaskUpdate(taskId, signal, sessionId) {
|
|
29494
29533
|
let interval = this._options?.defaultTaskPollInterval ?? 1e3;
|
|
29495
29534
|
try {
|
|
29496
|
-
const task = await this._taskStore?.getTask(taskId);
|
|
29535
|
+
const task = await this._taskStore?.getTask(taskId, sessionId);
|
|
29497
29536
|
if (task?.pollInterval) {
|
|
29498
29537
|
interval = task.pollInterval;
|
|
29499
29538
|
}
|
|
@@ -29979,16 +30018,7 @@ var Server = class extends Protocol {
|
|
|
29979
30018
|
if (!methodSchema) {
|
|
29980
30019
|
throw new Error("Schema is missing a method literal");
|
|
29981
30020
|
}
|
|
29982
|
-
|
|
29983
|
-
if (isZ4Schema(methodSchema)) {
|
|
29984
|
-
const v4Schema = methodSchema;
|
|
29985
|
-
const v4Def = v4Schema._zod?.def;
|
|
29986
|
-
methodValue = v4Def?.value ?? v4Schema.value;
|
|
29987
|
-
} else {
|
|
29988
|
-
const v3Schema = methodSchema;
|
|
29989
|
-
const legacyDef = v3Schema._def;
|
|
29990
|
-
methodValue = legacyDef?.value ?? v3Schema.value;
|
|
29991
|
-
}
|
|
30021
|
+
const methodValue = getLiteralValue(methodSchema);
|
|
29992
30022
|
if (typeof methodValue !== "string") {
|
|
29993
30023
|
throw new Error("Schema method literal must be a string");
|
|
29994
30024
|
}
|
|
@@ -30381,6 +30411,42 @@ var ExperimentalMcpServerTasks = class {
|
|
|
30381
30411
|
};
|
|
30382
30412
|
|
|
30383
30413
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
|
|
30414
|
+
function toolInputElementCount(value, max) {
|
|
30415
|
+
let count = 0;
|
|
30416
|
+
const stack = [value];
|
|
30417
|
+
while (stack.length > 0) {
|
|
30418
|
+
const node = stack.pop();
|
|
30419
|
+
if (node === null || typeof node !== "object")
|
|
30420
|
+
continue;
|
|
30421
|
+
if (Array.isArray(node)) {
|
|
30422
|
+
for (const child of node) {
|
|
30423
|
+
if (++count > max)
|
|
30424
|
+
return count;
|
|
30425
|
+
if (child !== null && typeof child === "object")
|
|
30426
|
+
stack.push(child);
|
|
30427
|
+
}
|
|
30428
|
+
} else {
|
|
30429
|
+
for (const key in node) {
|
|
30430
|
+
if (!Object.prototype.hasOwnProperty.call(node, key))
|
|
30431
|
+
continue;
|
|
30432
|
+
if (++count > max)
|
|
30433
|
+
return count;
|
|
30434
|
+
const child = node[key];
|
|
30435
|
+
if (child !== null && typeof child === "object")
|
|
30436
|
+
stack.push(child);
|
|
30437
|
+
}
|
|
30438
|
+
}
|
|
30439
|
+
}
|
|
30440
|
+
return count;
|
|
30441
|
+
}
|
|
30442
|
+
function resolveMaxToolInputElements(value) {
|
|
30443
|
+
if (value === void 0 || value === Infinity)
|
|
30444
|
+
return void 0;
|
|
30445
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
|
|
30446
|
+
throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
|
|
30447
|
+
}
|
|
30448
|
+
return value;
|
|
30449
|
+
}
|
|
30384
30450
|
var McpServer = class {
|
|
30385
30451
|
constructor(serverInfo, options) {
|
|
30386
30452
|
this._registeredResources = {};
|
|
@@ -30392,6 +30458,7 @@ var McpServer = class {
|
|
|
30392
30458
|
this._resourceHandlersInitialized = false;
|
|
30393
30459
|
this._promptHandlersInitialized = false;
|
|
30394
30460
|
this.server = new Server(serverInfo, options);
|
|
30461
|
+
this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
|
|
30395
30462
|
}
|
|
30396
30463
|
/**
|
|
30397
30464
|
* Access experimental features.
|
|
@@ -30522,12 +30589,15 @@ var McpServer = class {
|
|
|
30522
30589
|
* Validates tool input arguments against the tool's input schema.
|
|
30523
30590
|
*/
|
|
30524
30591
|
async validateToolInput(tool, args, toolName) {
|
|
30592
|
+
if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) {
|
|
30593
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
|
|
30594
|
+
}
|
|
30525
30595
|
if (!tool.inputSchema) {
|
|
30526
30596
|
return void 0;
|
|
30527
30597
|
}
|
|
30528
30598
|
const inputObj = normalizeObjectSchema(tool.inputSchema);
|
|
30529
30599
|
const schemaToParse = inputObj ?? tool.inputSchema;
|
|
30530
|
-
const parseResult = await safeParseAsync2(schemaToParse, args);
|
|
30600
|
+
const parseResult = await safeParseAsync2(schemaToParse, args ?? {});
|
|
30531
30601
|
if (!parseResult.success) {
|
|
30532
30602
|
const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
30533
30603
|
const errorMessage = getParseErrorMessage(error51);
|
|
@@ -30765,7 +30835,7 @@ var McpServer = class {
|
|
|
30765
30835
|
}
|
|
30766
30836
|
if (prompt.argsSchema) {
|
|
30767
30837
|
const argsObj = normalizeObjectSchema(prompt.argsSchema);
|
|
30768
|
-
const parseResult = await safeParseAsync2(argsObj, request.params.arguments);
|
|
30838
|
+
const parseResult = await safeParseAsync2(argsObj, request.params.arguments ?? {});
|
|
30769
30839
|
if (!parseResult.success) {
|
|
30770
30840
|
const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
30771
30841
|
const errorMessage = getParseErrorMessage(error51);
|
|
@@ -31176,8 +31246,17 @@ var EMPTY_COMPLETION_RESULT = {
|
|
|
31176
31246
|
import process3 from "process";
|
|
31177
31247
|
|
|
31178
31248
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
31249
|
+
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
31179
31250
|
var ReadBuffer = class {
|
|
31251
|
+
constructor(options) {
|
|
31252
|
+
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
31253
|
+
}
|
|
31180
31254
|
append(chunk) {
|
|
31255
|
+
const newSize = (this._buffer?.length ?? 0) + chunk.length;
|
|
31256
|
+
if (newSize > this._maxBufferSize) {
|
|
31257
|
+
this.clear();
|
|
31258
|
+
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
31259
|
+
}
|
|
31181
31260
|
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
31182
31261
|
}
|
|
31183
31262
|
readMessage() {
|
|
@@ -31205,18 +31284,24 @@ function serializeMessage(message) {
|
|
|
31205
31284
|
|
|
31206
31285
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
31207
31286
|
var StdioServerTransport = class {
|
|
31208
|
-
constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
|
|
31287
|
+
constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
|
|
31209
31288
|
this._stdin = _stdin;
|
|
31210
31289
|
this._stdout = _stdout;
|
|
31211
|
-
this._readBuffer = new ReadBuffer();
|
|
31212
31290
|
this._started = false;
|
|
31213
31291
|
this._ondata = (chunk) => {
|
|
31214
|
-
|
|
31215
|
-
|
|
31292
|
+
try {
|
|
31293
|
+
this._readBuffer.append(chunk);
|
|
31294
|
+
this.processReadBuffer();
|
|
31295
|
+
} catch (error51) {
|
|
31296
|
+
this.onerror?.(error51);
|
|
31297
|
+
this.close().catch(() => {
|
|
31298
|
+
});
|
|
31299
|
+
}
|
|
31216
31300
|
};
|
|
31217
31301
|
this._onerror = (error51) => {
|
|
31218
31302
|
this.onerror?.(error51);
|
|
31219
31303
|
};
|
|
31304
|
+
this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
|
|
31220
31305
|
}
|
|
31221
31306
|
/**
|
|
31222
31307
|
* Starts listening for messages on stdin.
|
|
@@ -31265,7 +31350,7 @@ var StdioServerTransport = class {
|
|
|
31265
31350
|
};
|
|
31266
31351
|
|
|
31267
31352
|
// src/core/config.ts
|
|
31268
|
-
import { readFileSync as
|
|
31353
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
31269
31354
|
import { homedir as homedir3 } from "os";
|
|
31270
31355
|
import { join as join7 } from "path";
|
|
31271
31356
|
|
|
@@ -31281,6 +31366,7 @@ import { homedir as homedir2 } from "os";
|
|
|
31281
31366
|
import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
|
|
31282
31367
|
|
|
31283
31368
|
// src/core/diag.ts
|
|
31369
|
+
import { readFileSync } from "fs";
|
|
31284
31370
|
import { join as join3 } from "path";
|
|
31285
31371
|
|
|
31286
31372
|
// src/core/log.ts
|
|
@@ -31353,7 +31439,7 @@ function diag(harness, event, extra = {}) {
|
|
|
31353
31439
|
}
|
|
31354
31440
|
|
|
31355
31441
|
// src/core/git-layout.ts
|
|
31356
|
-
import { lstatSync, readFileSync, realpathSync } from "fs";
|
|
31442
|
+
import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
|
|
31357
31443
|
import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
|
|
31358
31444
|
var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
|
|
31359
31445
|
var ATTEMPTS = 3;
|
|
@@ -31377,7 +31463,7 @@ function entryKind(path) {
|
|
|
31377
31463
|
}
|
|
31378
31464
|
function readTextOrNull(path) {
|
|
31379
31465
|
try {
|
|
31380
|
-
return
|
|
31466
|
+
return readFileSync2(path, "utf8");
|
|
31381
31467
|
} catch (error51) {
|
|
31382
31468
|
if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
|
|
31383
31469
|
return null;
|
|
@@ -31539,13 +31625,13 @@ function isWithin(directory, configured) {
|
|
|
31539
31625
|
function mapLookup(map2, directory) {
|
|
31540
31626
|
const cwd = normalize(directory);
|
|
31541
31627
|
let best;
|
|
31542
|
-
for (const [dir,
|
|
31628
|
+
for (const [dir, value] of Object.entries(map2)) {
|
|
31543
31629
|
const p = configuredDir(dir);
|
|
31544
31630
|
if (isWithin(cwd, p)) {
|
|
31545
|
-
if (!best || p.length > best.len) best = { len: p.length,
|
|
31631
|
+
if (!best || p.length > best.len) best = { len: p.length, value };
|
|
31546
31632
|
}
|
|
31547
31633
|
}
|
|
31548
|
-
return best?.
|
|
31634
|
+
return best?.value;
|
|
31549
31635
|
}
|
|
31550
31636
|
function lookupDirectories(config2, directory, sessionRoot = "") {
|
|
31551
31637
|
const directories = [normalize(directory)];
|
|
@@ -31569,6 +31655,10 @@ function isOptedIn(config2, directory) {
|
|
|
31569
31655
|
const pathMap = config2.mapPathToBank;
|
|
31570
31656
|
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
31571
31657
|
}
|
|
31658
|
+
function pathSection(config2, paths, directory) {
|
|
31659
|
+
if (!directory || !paths) return void 0;
|
|
31660
|
+
return lookupDirectories(config2, directory).map((candidate) => mapLookup(paths, candidate)).find((section) => section !== void 0);
|
|
31661
|
+
}
|
|
31572
31662
|
function mappedBank(config2, directory, sessionRoot) {
|
|
31573
31663
|
const pathMap = config2.mapPathToBank;
|
|
31574
31664
|
if (!directory || !pathMap) return void 0;
|
|
@@ -31588,6 +31678,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
|
|
|
31588
31678
|
};
|
|
31589
31679
|
return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
31590
31680
|
}
|
|
31681
|
+
function bankProjectName(config2, directory, sessionRoot) {
|
|
31682
|
+
if (mappedBank(config2, directory, sessionRoot)) return void 0;
|
|
31683
|
+
const dynamic = config2.dynamicBankId ?? !config2.bankId;
|
|
31684
|
+
if (!dynamic) return void 0;
|
|
31685
|
+
const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
|
|
31686
|
+
if (!template.includes("{gitProject}")) return void 0;
|
|
31687
|
+
try {
|
|
31688
|
+
return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
|
|
31689
|
+
} catch (error51) {
|
|
31690
|
+
if (error51 instanceof BankResolutionError) return void 0;
|
|
31691
|
+
throw error51;
|
|
31692
|
+
}
|
|
31693
|
+
}
|
|
31591
31694
|
function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
|
|
31592
31695
|
try {
|
|
31593
31696
|
return deriveBankId(config2, directory, harness, sessionRoot);
|
|
@@ -31605,7 +31708,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
|
|
|
31605
31708
|
// src/core/missions.ts
|
|
31606
31709
|
import { createHash } from "crypto";
|
|
31607
31710
|
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.";
|
|
31608
|
-
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history,
|
|
31711
|
+
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
|
|
31609
31712
|
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.`;
|
|
31610
31713
|
var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
|
|
31611
31714
|
var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
|
|
@@ -31681,6 +31784,8 @@ var KNOWLEDGE_LABELS = {
|
|
|
31681
31784
|
]
|
|
31682
31785
|
};
|
|
31683
31786
|
function pageScopeRule(project) {
|
|
31787
|
+
if (project === void 0)
|
|
31788
|
+
return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
|
|
31684
31789
|
return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
|
|
31685
31790
|
}
|
|
31686
31791
|
var PAGE_TAXONOMY = [
|
|
@@ -31816,12 +31921,17 @@ var CODING_BANK_TEMPLATE = {
|
|
|
31816
31921
|
}
|
|
31817
31922
|
};
|
|
31818
31923
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
31924
|
+
var PLUGIN_GOVERNED_BANK_FIELDS = [
|
|
31925
|
+
"retain_strategies",
|
|
31926
|
+
"entity_labels",
|
|
31927
|
+
"retain_extraction_mode"
|
|
31928
|
+
];
|
|
31819
31929
|
function isSet(v) {
|
|
31820
31930
|
if (v === null || v === void 0) return false;
|
|
31821
31931
|
if (typeof v === "string") return v.trim() !== "";
|
|
31822
31932
|
return true;
|
|
31823
31933
|
}
|
|
31824
|
-
function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
|
|
31934
|
+
function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, defaults = {}) {
|
|
31825
31935
|
const current2 = overrides ?? {};
|
|
31826
31936
|
const template = CODING_BANK_TEMPLATE.bank;
|
|
31827
31937
|
const bank = {};
|
|
@@ -31850,19 +31960,26 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE) {
|
|
|
31850
31960
|
const [knowledgeGroup] = template.entity_labels;
|
|
31851
31961
|
if (!labels.some((g) => g?.key === knowledgeGroup.key))
|
|
31852
31962
|
bank.entity_labels = [...labels, knowledgeGroup];
|
|
31963
|
+
for (const [key, value] of Object.entries(defaults)) {
|
|
31964
|
+
if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key) || !isSet(value) || isSet(current2[key])) continue;
|
|
31965
|
+
bank[key] = value;
|
|
31966
|
+
}
|
|
31853
31967
|
return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
|
|
31854
31968
|
}
|
|
31855
31969
|
|
|
31970
|
+
// package.json
|
|
31971
|
+
var version2 = "0.8.1";
|
|
31972
|
+
|
|
31856
31973
|
// src/core/util.ts
|
|
31857
31974
|
import { accessSync, constants } from "fs";
|
|
31858
31975
|
import { delimiter, join as join6 } from "path";
|
|
31859
31976
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
31860
|
-
function semverGte(
|
|
31977
|
+
function semverGte(version3, min) {
|
|
31861
31978
|
const parts = (v) => {
|
|
31862
31979
|
const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
31863
31980
|
return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
|
|
31864
31981
|
};
|
|
31865
|
-
const a =
|
|
31982
|
+
const a = version3 ? parts(version3) : void 0;
|
|
31866
31983
|
const b = parts(min);
|
|
31867
31984
|
if (!a || !b) return false;
|
|
31868
31985
|
for (let i = 0; i < 3; i++) {
|
|
@@ -31887,6 +32004,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
31887
32004
|
}
|
|
31888
32005
|
|
|
31889
32006
|
// src/core/hindsight.ts
|
|
32007
|
+
var USER_AGENT = `hindsight-coding-agents/${version2}`;
|
|
31890
32008
|
function resolveRetainScopes(tags, configured) {
|
|
31891
32009
|
if (configured !== "per_source") return configured;
|
|
31892
32010
|
const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
|
|
@@ -31922,7 +32040,7 @@ async function isEndpointMissing(r) {
|
|
|
31922
32040
|
const j = await r.json();
|
|
31923
32041
|
return String(j?.detail ?? "").trim().toLowerCase() === "not found";
|
|
31924
32042
|
} catch {
|
|
31925
|
-
return
|
|
32043
|
+
return false;
|
|
31926
32044
|
}
|
|
31927
32045
|
}
|
|
31928
32046
|
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
@@ -31941,6 +32059,12 @@ var ReflectError = class extends Error {
|
|
|
31941
32059
|
get fallbackEligible() {
|
|
31942
32060
|
return this.timedOut || this.status !== void 0 && this.status >= 500;
|
|
31943
32061
|
}
|
|
32062
|
+
/** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
|
|
32063
|
+
* only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
|
|
32064
|
+
get permanent() {
|
|
32065
|
+
const s = this.status;
|
|
32066
|
+
return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
|
|
32067
|
+
}
|
|
31944
32068
|
};
|
|
31945
32069
|
var DEFAULT_MAX_PARALLEL_RETAINS = 10;
|
|
31946
32070
|
var DEFAULT_PAGE_SEARCH_LIMIT = 10;
|
|
@@ -31951,8 +32075,31 @@ var DEFAULT_RECALL_OPTIONS = {
|
|
|
31951
32075
|
include: { entities: null }
|
|
31952
32076
|
};
|
|
31953
32077
|
var POLL_CYCLE_MS = 5e3;
|
|
32078
|
+
var POLL_MAX_SERVER_ERRORS = 12;
|
|
31954
32079
|
var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
|
|
31955
32080
|
var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
32081
|
+
var RATE_LIMIT_BACKOFF_MS = 1e3;
|
|
32082
|
+
function shapePage(page) {
|
|
32083
|
+
const p = page ?? {};
|
|
32084
|
+
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
32085
|
+
return {
|
|
32086
|
+
id: p.id,
|
|
32087
|
+
name: p.name,
|
|
32088
|
+
...p.description ? { description: p.description } : {},
|
|
32089
|
+
...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
|
|
32090
|
+
...p.timestamp ? { last_updated_at: p.timestamp } : {},
|
|
32091
|
+
body
|
|
32092
|
+
};
|
|
32093
|
+
}
|
|
32094
|
+
var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
|
|
32095
|
+
function signalOnlyDispatcher() {
|
|
32096
|
+
void globalThis.Headers;
|
|
32097
|
+
const d = globalThis[GLOBAL_DISPATCHER];
|
|
32098
|
+
if (typeof d?.compose !== "function") return void 0;
|
|
32099
|
+
return d.compose(
|
|
32100
|
+
(dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
|
|
32101
|
+
);
|
|
32102
|
+
}
|
|
31956
32103
|
var HindsightClient = class {
|
|
31957
32104
|
apiUrl;
|
|
31958
32105
|
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
@@ -31972,6 +32119,7 @@ var HindsightClient = class {
|
|
|
31972
32119
|
observationScopes;
|
|
31973
32120
|
pageSearchLimit;
|
|
31974
32121
|
recallOptions;
|
|
32122
|
+
rateLimitPatienceMs;
|
|
31975
32123
|
constructor(o) {
|
|
31976
32124
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
31977
32125
|
this.token = o.apiToken;
|
|
@@ -31984,13 +32132,18 @@ var HindsightClient = class {
|
|
|
31984
32132
|
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
31985
32133
|
this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
|
|
31986
32134
|
this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
|
|
32135
|
+
this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
|
|
31987
32136
|
}
|
|
31988
32137
|
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
31989
32138
|
get apiToken() {
|
|
31990
32139
|
return this.token;
|
|
31991
32140
|
}
|
|
31992
32141
|
headers() {
|
|
31993
|
-
const h = {
|
|
32142
|
+
const h = {
|
|
32143
|
+
"Content-Type": "application/json",
|
|
32144
|
+
"Accept-Encoding": "identity",
|
|
32145
|
+
"User-Agent": USER_AGENT
|
|
32146
|
+
};
|
|
31994
32147
|
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
31995
32148
|
return h;
|
|
31996
32149
|
}
|
|
@@ -32021,7 +32174,8 @@ var HindsightClient = class {
|
|
|
32021
32174
|
* bounds the whole call.
|
|
32022
32175
|
*/
|
|
32023
32176
|
async fetchWithAuth(url2, init) {
|
|
32024
|
-
const
|
|
32177
|
+
const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
|
|
32178
|
+
const send = () => fetch(url2, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
|
|
32025
32179
|
const r = await send();
|
|
32026
32180
|
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
32027
32181
|
return send();
|
|
@@ -32037,13 +32191,22 @@ var HindsightClient = class {
|
|
|
32037
32191
|
}
|
|
32038
32192
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
32039
32193
|
async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
|
|
32040
|
-
const
|
|
32041
|
-
|
|
32042
|
-
|
|
32043
|
-
|
|
32044
|
-
|
|
32045
|
-
|
|
32046
|
-
|
|
32194
|
+
const payload = body ? JSON.stringify(body) : void 0;
|
|
32195
|
+
let r;
|
|
32196
|
+
for (let attempt = 0, waited = 0; ; attempt++) {
|
|
32197
|
+
r = await this.fetchWithAuth(url2, {
|
|
32198
|
+
method,
|
|
32199
|
+
body: payload,
|
|
32200
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
32201
|
+
});
|
|
32202
|
+
if (r.status !== 429 || tolerate.includes(429)) break;
|
|
32203
|
+
const asked = retryAfterMs(r.headers.get("retry-after"));
|
|
32204
|
+
const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
|
|
32205
|
+
const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
|
|
32206
|
+
if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
|
|
32207
|
+
await sleep(wait);
|
|
32208
|
+
waited += wait;
|
|
32209
|
+
}
|
|
32047
32210
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
32048
32211
|
throw new Error(
|
|
32049
32212
|
`${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
@@ -32078,7 +32241,7 @@ var HindsightClient = class {
|
|
|
32078
32241
|
}
|
|
32079
32242
|
/**
|
|
32080
32243
|
* Whether this server honours `operation_id` on an async retain, and can therefore be appended to
|
|
32081
|
-
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via
|
|
32244
|
+
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
|
|
32082
32245
|
* unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
|
|
32083
32246
|
*/
|
|
32084
32247
|
async supportsIdempotentRetain() {
|
|
@@ -32088,14 +32251,37 @@ var HindsightClient = class {
|
|
|
32088
32251
|
}
|
|
32089
32252
|
return this.idempotentRetain;
|
|
32090
32253
|
}
|
|
32254
|
+
/** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
|
|
32255
|
+
* hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
|
|
32256
|
+
* so append silently never turned on (#5286). Servers that predate the alias still answer
|
|
32257
|
+
* `/version`, so that stays as the fallback. */
|
|
32091
32258
|
async probeIdempotentRetain() {
|
|
32259
|
+
for (const path of ["/v1/version", "/version"]) {
|
|
32260
|
+
try {
|
|
32261
|
+
const r = await this.req("GET", `${this.apiUrl}${path}`);
|
|
32262
|
+
if (!r.ok) continue;
|
|
32263
|
+
const j = await r.json();
|
|
32264
|
+
return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
|
|
32265
|
+
} catch {
|
|
32266
|
+
}
|
|
32267
|
+
}
|
|
32268
|
+
return false;
|
|
32269
|
+
}
|
|
32270
|
+
/**
|
|
32271
|
+
* Whether a session write-back may use `update_mode="append"`: the server must dedupe by
|
|
32272
|
+
* `operation_id` AND the bank must keep document text, or the server rejects the append in the
|
|
32273
|
+
* background (#4613). Only an explicit `store_document_text: false` answers "no" — an unreachable
|
|
32274
|
+
* or unparseable config assumes the default (stored), so a flaky probe never downgrades appends.
|
|
32275
|
+
*/
|
|
32276
|
+
async supportsAppendRetain() {
|
|
32277
|
+
if (!await this.supportsIdempotentRetain()) return false;
|
|
32092
32278
|
try {
|
|
32093
|
-
const r = await this.req("GET",
|
|
32094
|
-
if (!r.ok) return
|
|
32279
|
+
const r = await this.req("GET", this.bankUrl("/config"));
|
|
32280
|
+
if (!r.ok) return true;
|
|
32095
32281
|
const j = await r.json();
|
|
32096
|
-
return
|
|
32282
|
+
return j.config?.store_document_text !== false;
|
|
32097
32283
|
} catch {
|
|
32098
|
-
return
|
|
32284
|
+
return true;
|
|
32099
32285
|
}
|
|
32100
32286
|
}
|
|
32101
32287
|
/**
|
|
@@ -32123,6 +32309,32 @@ var HindsightClient = class {
|
|
|
32123
32309
|
}
|
|
32124
32310
|
return ids;
|
|
32125
32311
|
}
|
|
32312
|
+
/**
|
|
32313
|
+
* The tags on one document, or undefined when the bank holds none with that id. Read from the
|
|
32314
|
+
* document LISTING narrowed by `q` (a substring match on the id, so the exact id is picked out of
|
|
32315
|
+
* the page) rather than GET /documents/{id}, which also sends the document's full text: the
|
|
32316
|
+
* caller, the git-log freshness check on SessionStart, reads a ~100k-character document for one tag.
|
|
32317
|
+
*/
|
|
32318
|
+
async documentTags(documentId) {
|
|
32319
|
+
const limit = 100;
|
|
32320
|
+
for (let offset = 0; ; offset += limit) {
|
|
32321
|
+
const q = `?q=${encodeURIComponent(documentId)}&limit=${limit}&offset=${offset}`;
|
|
32322
|
+
const r = await this.req("GET", this.bankUrl(`/documents${q}`));
|
|
32323
|
+
const j = await r.json();
|
|
32324
|
+
const items = j.items ?? [];
|
|
32325
|
+
const hit = items.find((it) => it.id === documentId);
|
|
32326
|
+
if (hit) return hit.tags ?? [];
|
|
32327
|
+
if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
|
|
32328
|
+
}
|
|
32329
|
+
}
|
|
32330
|
+
/** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
|
|
32331
|
+
* yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
|
|
32332
|
+
async hasDocuments() {
|
|
32333
|
+
const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
|
|
32334
|
+
if (r.status === 404) return false;
|
|
32335
|
+
const j = await r.json();
|
|
32336
|
+
return (j.total ?? j.items?.length ?? 0) > 0;
|
|
32337
|
+
}
|
|
32126
32338
|
/** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
|
|
32127
32339
|
* entity labels), then seed knowledge pages when the server supports them. Both halves are
|
|
32128
32340
|
* idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
|
|
@@ -32144,7 +32356,8 @@ var HindsightClient = class {
|
|
|
32144
32356
|
} else {
|
|
32145
32357
|
const manifest = codingBankManifest(
|
|
32146
32358
|
opts.reset ? void 0 : await this.readBankOverrides(),
|
|
32147
|
-
opts.extractionMode
|
|
32359
|
+
opts.extractionMode,
|
|
32360
|
+
opts.defaults
|
|
32148
32361
|
);
|
|
32149
32362
|
if (!manifest) {
|
|
32150
32363
|
this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
|
|
@@ -32203,7 +32416,13 @@ var HindsightClient = class {
|
|
|
32203
32416
|
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
32204
32417
|
const start = Date.now();
|
|
32205
32418
|
const pending = new Set(ids);
|
|
32419
|
+
const serverErrors = /* @__PURE__ */ new Map();
|
|
32206
32420
|
let failed = 0;
|
|
32421
|
+
const giveUp = (id, status) => {
|
|
32422
|
+
pending.delete(id);
|
|
32423
|
+
failed++;
|
|
32424
|
+
this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
|
|
32425
|
+
};
|
|
32207
32426
|
while (pending.size && Date.now() - start < maxMs) {
|
|
32208
32427
|
let backoffMs = POLL_CYCLE_MS;
|
|
32209
32428
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
@@ -32216,7 +32435,14 @@ var HindsightClient = class {
|
|
|
32216
32435
|
);
|
|
32217
32436
|
return;
|
|
32218
32437
|
}
|
|
32219
|
-
if (
|
|
32438
|
+
if (r.status >= 500) {
|
|
32439
|
+
const n = (serverErrors.get(id) ?? 0) + 1;
|
|
32440
|
+
serverErrors.set(id, n);
|
|
32441
|
+
if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
|
|
32442
|
+
return;
|
|
32443
|
+
}
|
|
32444
|
+
if (!r.ok) return giveUp(id, r.status);
|
|
32445
|
+
serverErrors.delete(id);
|
|
32220
32446
|
const st = ((await r.json()).status || "").toLowerCase();
|
|
32221
32447
|
if (TERMINAL.has(st)) {
|
|
32222
32448
|
pending.delete(id);
|
|
@@ -32350,8 +32576,8 @@ var HindsightClient = class {
|
|
|
32350
32576
|
return { items };
|
|
32351
32577
|
}
|
|
32352
32578
|
/**
|
|
32353
|
-
* Read one knowledge page's synthesized content by knowledge-base id,
|
|
32354
|
-
*
|
|
32579
|
+
* Read one knowledge page's synthesized content by knowledge-base id, shaped by `shapePage` so
|
|
32580
|
+
* the body arrives once. The endpoint omits the internal reflect trace that built
|
|
32355
32581
|
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
32356
32582
|
* token cap.
|
|
32357
32583
|
*/
|
|
@@ -32362,7 +32588,7 @@ var HindsightClient = class {
|
|
|
32362
32588
|
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
32363
32589
|
);
|
|
32364
32590
|
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
32365
|
-
return await r.json();
|
|
32591
|
+
return shapePage(await r.json());
|
|
32366
32592
|
}
|
|
32367
32593
|
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
32368
32594
|
* Returns page-level hits with a relevance snippet — the real search behind
|
|
@@ -32383,6 +32609,7 @@ var HindsightClient = class {
|
|
|
32383
32609
|
return (j.results ?? []).map((x) => ({
|
|
32384
32610
|
id: x.id,
|
|
32385
32611
|
name: x.name,
|
|
32612
|
+
...x.source_query ? { source_query: x.source_query } : {},
|
|
32386
32613
|
snippet: x.snippet ?? "",
|
|
32387
32614
|
score: x.score ?? 0
|
|
32388
32615
|
}));
|
|
@@ -32399,7 +32626,7 @@ var HindsightClient = class {
|
|
|
32399
32626
|
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
32400
32627
|
*/
|
|
32401
32628
|
async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
|
|
32402
|
-
const pages = pagesFor(this.project
|
|
32629
|
+
const pages = pagesFor(this.project, pagesConfig, customPages);
|
|
32403
32630
|
const existing = /* @__PURE__ */ new Map();
|
|
32404
32631
|
let roots;
|
|
32405
32632
|
try {
|
|
@@ -32474,7 +32701,7 @@ var HindsightClient = class {
|
|
|
32474
32701
|
}
|
|
32475
32702
|
const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
|
|
32476
32703
|
this.log(
|
|
32477
|
-
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ??
|
|
32704
|
+
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
|
|
32478
32705
|
);
|
|
32479
32706
|
}
|
|
32480
32707
|
/**
|
|
@@ -32485,23 +32712,33 @@ var HindsightClient = class {
|
|
|
32485
32712
|
* it: five taxonomy pages against one page per initiative, each an LLM synthesis per
|
|
32486
32713
|
* consolidation under the auto-refresh that used to be the default (#3506).
|
|
32487
32714
|
*
|
|
32488
|
-
*
|
|
32489
|
-
*
|
|
32490
|
-
*
|
|
32715
|
+
* Their `name` and `source_query` are written once, from the initiative's own title, and
|
|
32716
|
+
* re-stating either would rebuild a page whose question never changed. The one exception is
|
|
32717
|
+
* the scope clause: a page captured while the clause named the BANK is scoped to a project no
|
|
32718
|
+
* memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
|
|
32719
|
+
* one — the rest of the query, the user's wording included, is kept. The tree read above is
|
|
32720
|
+
* reused rather than re-fetched.
|
|
32491
32721
|
*/
|
|
32492
32722
|
async resyncInitiativeTriggers(roots, pageTrigger) {
|
|
32493
32723
|
const folder = roots.find(
|
|
32494
32724
|
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
|
|
32495
32725
|
);
|
|
32726
|
+
const bankScope = pageScopeRule(this.bank);
|
|
32496
32727
|
let updated = 0;
|
|
32497
32728
|
for (const page of folder?.children ?? []) {
|
|
32498
|
-
if (page.kind !== "page"
|
|
32499
|
-
const
|
|
32500
|
-
|
|
32729
|
+
if (page.kind !== "page") continue;
|
|
32730
|
+
const patch = {};
|
|
32731
|
+
const query = page.description?.replace(bankScope, pageScopeRule(this.project));
|
|
32732
|
+
if (query !== page.description) patch.source_query = query;
|
|
32733
|
+
if (page.trigger != null) {
|
|
32734
|
+
const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
|
|
32735
|
+
if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
|
|
32736
|
+
}
|
|
32737
|
+
if (!patch.trigger && !patch.source_query) continue;
|
|
32501
32738
|
const r = await this.req(
|
|
32502
32739
|
"PATCH",
|
|
32503
32740
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
|
|
32504
|
-
|
|
32741
|
+
patch
|
|
32505
32742
|
);
|
|
32506
32743
|
if (r.status === 404) continue;
|
|
32507
32744
|
updated++;
|
|
@@ -32529,10 +32766,9 @@ var HindsightClient = class {
|
|
|
32529
32766
|
let pageId = args.relatesToPageId;
|
|
32530
32767
|
if (!pageId) {
|
|
32531
32768
|
const folderId = await this.ensureFolder("Initiatives");
|
|
32532
|
-
const subject = this.project ?? this.bank;
|
|
32533
32769
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
32534
32770
|
name: args.title,
|
|
32535
|
-
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(
|
|
32771
|
+
source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.` + pageScopeRule(this.project),
|
|
32536
32772
|
parent_id: folderId,
|
|
32537
32773
|
tags: ["knowledge:feature-work"],
|
|
32538
32774
|
max_tokens: PAGE_MAX_TOKENS,
|
|
@@ -32547,7 +32783,7 @@ var HindsightClient = class {
|
|
|
32547
32783
|
}
|
|
32548
32784
|
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
32549
32785
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
32550
|
-
const markerId = `initiative-marker-${this.slugify(
|
|
32786
|
+
const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
|
|
32551
32787
|
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
32552
32788
|
const context = `initiative marker for [[page:${pageId}]]`;
|
|
32553
32789
|
await this.retain(content, context, markerId, tags, "document", {
|
|
@@ -32653,6 +32889,7 @@ function resolveCustomPages(raw) {
|
|
|
32653
32889
|
}
|
|
32654
32890
|
var DEFAULT_REFLECT_TIMEOUT_MS = 2e4;
|
|
32655
32891
|
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
32892
|
+
var DEFAULT_INJECT_TIMEOUT_MS = 7e3;
|
|
32656
32893
|
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
32657
32894
|
function resolveReflectBudget(raw) {
|
|
32658
32895
|
const value = raw.reflectBudget;
|
|
@@ -32679,6 +32916,22 @@ function resolveObservationScopes(raw) {
|
|
|
32679
32916
|
}
|
|
32680
32917
|
return DEFAULT_OBSERVATION_SCOPES;
|
|
32681
32918
|
}
|
|
32919
|
+
function resolveDefaultBankConfig(raw) {
|
|
32920
|
+
const value = raw;
|
|
32921
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
32922
|
+
const out = {};
|
|
32923
|
+
for (const [key, v] of Object.entries(value)) {
|
|
32924
|
+
if (PLUGIN_GOVERNED_BANK_FIELDS.includes(key)) {
|
|
32925
|
+
log.warn(
|
|
32926
|
+
"config",
|
|
32927
|
+
`ignoring defaultBankConfig.${key} \u2014 the plugin manages this field itself` + (key === "retain_extraction_mode" ? " (set retainExtractionMode instead)" : "")
|
|
32928
|
+
);
|
|
32929
|
+
continue;
|
|
32930
|
+
}
|
|
32931
|
+
out[key] = v;
|
|
32932
|
+
}
|
|
32933
|
+
return out;
|
|
32934
|
+
}
|
|
32682
32935
|
var AUTO_INJECT_MODES = ["reflect", "pages", "recall", "none"];
|
|
32683
32936
|
function resolveAutoInject(raw) {
|
|
32684
32937
|
if (raw.autoReflect !== void 0) {
|
|
@@ -32718,18 +32971,21 @@ function resolveConfig(raw = {}) {
|
|
|
32718
32971
|
// write sessions back by default, every harness
|
|
32719
32972
|
manageBankConfig: raw.manageBankConfig ?? true,
|
|
32720
32973
|
retainExtractionMode: RETAIN_EXTRACTION_MODES.includes(raw.retainExtractionMode) ? raw.retainExtractionMode : DEFAULT_RETAIN_EXTRACTION_MODE,
|
|
32974
|
+
defaultBankConfig: resolveDefaultBankConfig(raw.defaultBankConfig),
|
|
32721
32975
|
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
32722
32976
|
reflectTimeoutMs: raw.reflectTimeoutMs || DEFAULT_REFLECT_TIMEOUT_MS,
|
|
32723
32977
|
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
32724
32978
|
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
32725
32979
|
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
32726
32980
|
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
32981
|
+
injectTimeoutMs: raw.injectTimeoutMs || DEFAULT_INJECT_TIMEOUT_MS,
|
|
32727
32982
|
reflectBudget: resolveReflectBudget(raw),
|
|
32728
32983
|
autoInject: resolveAutoInject(raw),
|
|
32729
32984
|
pageSearchLimit: raw.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT,
|
|
32730
32985
|
// Same shape as retainMetadata: an object, or nothing. An array would spread into numeric
|
|
32731
32986
|
// keys and reach the API as garbage, so it is rejected like any other non-object.
|
|
32732
32987
|
recallOptions: raw.recallOptions && typeof raw.recallOptions === "object" && !Array.isArray(raw.recallOptions) ? { ...raw.recallOptions } : {},
|
|
32988
|
+
toolGuideExtra: typeof raw.toolGuideExtra === "string" && raw.toolGuideExtra.trim() ? raw.toolGuideExtra : void 0,
|
|
32733
32989
|
// Every turn, not every tenth. The guide is what tells the agent WHEN to reach for memory, and
|
|
32734
32990
|
// at a cadence of 10 a normal session is told once, on turn 1, and never again. Measured over
|
|
32735
32991
|
// 40 real Claude Code turns, moving this from 10 to 1 took searches from 15% of turns to 32.5%
|
|
@@ -32749,18 +33005,22 @@ function resolveConfig(raw = {}) {
|
|
|
32749
33005
|
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
32750
33006
|
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
32751
33007
|
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
33008
|
+
// Undefined, not "", when unset or blank: the retain call distinguishes "not configured" (use
|
|
33009
|
+
// the built-in default) from a configured value, and an empty context would strip the default.
|
|
33010
|
+
retainContext: typeof raw.retainContext === "string" && raw.retainContext.trim() !== "" ? raw.retainContext : void 0,
|
|
32752
33011
|
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
32753
33012
|
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
32754
33013
|
) : {},
|
|
32755
33014
|
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
32756
33015
|
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
33016
|
+
paths: raw.paths && typeof raw.paths === "object" ? raw.paths : {},
|
|
32757
33017
|
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
|
|
32758
33018
|
autoUpdate: raw.autoUpdate ?? true
|
|
32759
33019
|
};
|
|
32760
33020
|
}
|
|
32761
33021
|
function readRaw(path) {
|
|
32762
33022
|
try {
|
|
32763
|
-
return JSON.parse(
|
|
33023
|
+
return JSON.parse(readFileSync3(path, "utf8"));
|
|
32764
33024
|
} catch (e) {
|
|
32765
33025
|
if (e?.code !== "ENOENT") {
|
|
32766
33026
|
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
@@ -32770,7 +33030,12 @@ function readRaw(path) {
|
|
|
32770
33030
|
}
|
|
32771
33031
|
function mergeRaw(a, b) {
|
|
32772
33032
|
const { harnesses: _drop, ...flat } = b;
|
|
32773
|
-
return {
|
|
33033
|
+
return {
|
|
33034
|
+
...a,
|
|
33035
|
+
...flat,
|
|
33036
|
+
banks: { ...a.banks ?? {}, ...b.banks ?? {} },
|
|
33037
|
+
paths: { ...a.paths ?? {}, ...b.paths ?? {} }
|
|
33038
|
+
};
|
|
32774
33039
|
}
|
|
32775
33040
|
function applyLayer(raw, layer, harness) {
|
|
32776
33041
|
let out = mergeRaw(raw, layer);
|
|
@@ -32801,9 +33066,11 @@ var ENV_KEYS = {
|
|
|
32801
33066
|
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
32802
33067
|
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
32803
33068
|
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
33069
|
+
injectTimeoutMs: "HINDSIGHT_INJECT_TIMEOUT_MS",
|
|
32804
33070
|
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
32805
33071
|
autoInject: "HINDSIGHT_AUTO_INJECT",
|
|
32806
33072
|
pageSearchLimit: "HINDSIGHT_PAGE_SEARCH_LIMIT",
|
|
33073
|
+
toolGuideExtra: "HINDSIGHT_TOOL_GUIDE_EXTRA",
|
|
32807
33074
|
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
32808
33075
|
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
32809
33076
|
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
@@ -32845,6 +33112,7 @@ var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
|
32845
33112
|
"maxParallelRetains",
|
|
32846
33113
|
"reflectTimeoutMs",
|
|
32847
33114
|
"reflectToolTimeoutMs",
|
|
33115
|
+
"injectTimeoutMs",
|
|
32848
33116
|
"pageSearchLimit",
|
|
32849
33117
|
"pageRefreshEveryTurns",
|
|
32850
33118
|
"seedLimit",
|
|
@@ -32893,15 +33161,25 @@ var BANK_OVERRIDE_EXCLUDED = [
|
|
|
32893
33161
|
function applyBankConfig(cfg, resolvedId, directory) {
|
|
32894
33162
|
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
32895
33163
|
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
33164
|
+
const byPath = directory === void 0 ? void 0 : pathSection(cfg, cfg.paths, directory);
|
|
33165
|
+
if (byPath) {
|
|
33166
|
+
const { bank: _rename, ...rest } = overrideFields(byPath);
|
|
33167
|
+
cfg = { ...cfg, ...resolvePartial(cfg, rest) };
|
|
33168
|
+
}
|
|
32896
33169
|
const section = cfg.banks[resolvedId];
|
|
32897
33170
|
if (!section) return { cfg, bankId: resolvedId };
|
|
32898
|
-
const safe =
|
|
32899
|
-
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
32900
|
-
delete safe.banks;
|
|
33171
|
+
const safe = overrideFields(section);
|
|
32901
33172
|
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
32902
33173
|
delete safe.bank;
|
|
32903
33174
|
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
32904
33175
|
}
|
|
33176
|
+
function overrideFields(section) {
|
|
33177
|
+
const safe = { ...section };
|
|
33178
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
33179
|
+
delete safe.banks;
|
|
33180
|
+
delete safe.paths;
|
|
33181
|
+
return safe;
|
|
33182
|
+
}
|
|
32905
33183
|
function resolvePartial(cfg, patch) {
|
|
32906
33184
|
const full = resolveConfig(patch);
|
|
32907
33185
|
const out = {};
|
|
@@ -32910,6 +33188,16 @@ function resolvePartial(cfg, patch) {
|
|
|
32910
33188
|
out[key] = full[key];
|
|
32911
33189
|
}
|
|
32912
33190
|
if ("autoReflect" in patch && !("autoInject" in patch)) out.autoInject = full.autoInject;
|
|
33191
|
+
if ("serverMode" in patch || "apiUrl" in patch || "apiPort" in patch) {
|
|
33192
|
+
const conn = resolveConfig({
|
|
33193
|
+
serverMode: patch.serverMode ?? cfg.serverMode,
|
|
33194
|
+
apiPort: patch.apiPort ?? cfg.apiPort,
|
|
33195
|
+
apiUrl: patch.apiUrl ?? (cfg.serverMode === "daemon" ? void 0 : cfg.apiUrl)
|
|
33196
|
+
});
|
|
33197
|
+
out.serverMode = conn.serverMode;
|
|
33198
|
+
out.apiUrl = conn.apiUrl;
|
|
33199
|
+
out.apiPort = conn.apiPort;
|
|
33200
|
+
}
|
|
32913
33201
|
return out;
|
|
32914
33202
|
}
|
|
32915
33203
|
|
|
@@ -32919,10 +33207,12 @@ function resolveHostConfig(harness, directory) {
|
|
|
32919
33207
|
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
32920
33208
|
const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
|
|
32921
33209
|
if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
|
|
32922
|
-
|
|
33210
|
+
const resolved2 = applyBankConfig(cfg0, bankId, directory);
|
|
33211
|
+
const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
|
|
33212
|
+
return { ...resolved2, project };
|
|
32923
33213
|
}
|
|
32924
33214
|
function resolveHostMemory(harness, directory) {
|
|
32925
|
-
const { cfg, bankId } = resolveHostConfig(harness, directory);
|
|
33215
|
+
const { cfg, bankId, project } = resolveHostConfig(harness, directory);
|
|
32926
33216
|
return {
|
|
32927
33217
|
cfg,
|
|
32928
33218
|
bankId,
|
|
@@ -32930,6 +33220,8 @@ function resolveHostMemory(harness, directory) {
|
|
|
32930
33220
|
apiUrl: cfg.apiUrl,
|
|
32931
33221
|
apiToken: cfg.apiToken,
|
|
32932
33222
|
bank: bankId,
|
|
33223
|
+
// Names the repo in the initiative pages this host captures, as the seeded pages do.
|
|
33224
|
+
project,
|
|
32933
33225
|
maxParallelRetains: cfg.maxParallelRetains,
|
|
32934
33226
|
observationScopes: cfg.observationScopes,
|
|
32935
33227
|
pageSearchLimit: cfg.pageSearchLimit,
|
|
@@ -32938,7 +33230,12 @@ function resolveHostMemory(harness, directory) {
|
|
|
32938
33230
|
// rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
|
|
32939
33231
|
// through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
|
|
32940
33232
|
// honoured on re-resolution exactly as it was on the first one.
|
|
32941
|
-
|
|
33233
|
+
// The URL stays the one this client was built with, so a token re-read after the config
|
|
33234
|
+
// moved this directory to ANOTHER server is that server's credential: never send it here.
|
|
33235
|
+
tokenProvider: () => {
|
|
33236
|
+
const live = resolveHostConfig(harness, directory).cfg;
|
|
33237
|
+
return live.apiUrl === cfg.apiUrl ? live.apiToken : cfg.apiToken;
|
|
33238
|
+
}
|
|
32942
33239
|
})
|
|
32943
33240
|
};
|
|
32944
33241
|
}
|
|
@@ -32950,13 +33247,13 @@ import { homedir as homedir5 } from "os";
|
|
|
32950
33247
|
import { join as join10 } from "path";
|
|
32951
33248
|
|
|
32952
33249
|
// src/core/status.ts
|
|
32953
|
-
import { execFileSync as
|
|
33250
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
32954
33251
|
|
|
32955
33252
|
// src/core/git.ts
|
|
32956
33253
|
import { execFileSync } from "child_process";
|
|
32957
33254
|
import { resolve as resolve2 } from "path";
|
|
32958
33255
|
function git(repo, ...args) {
|
|
32959
|
-
return execFileSync("git", ["-C", repo, ...args], {
|
|
33256
|
+
return execFileSync("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
|
|
32960
33257
|
encoding: "utf8",
|
|
32961
33258
|
maxBuffer: 1 << 28,
|
|
32962
33259
|
windowsHide: true,
|
|
@@ -32969,6 +33266,7 @@ function repoNameOf(repo) {
|
|
|
32969
33266
|
return projectNameOf(resolve2(repo));
|
|
32970
33267
|
}
|
|
32971
33268
|
function commitsSince(dir, sinceSha) {
|
|
33269
|
+
if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(sinceSha)) return null;
|
|
32972
33270
|
try {
|
|
32973
33271
|
const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
|
|
32974
33272
|
return Number.isFinite(n) ? n : null;
|
|
@@ -32991,7 +33289,7 @@ function parsePageList(raw) {
|
|
|
32991
33289
|
}
|
|
32992
33290
|
|
|
32993
33291
|
// src/core/survey.ts
|
|
32994
|
-
import { spawn as realSpawn3 } from "child_process";
|
|
33292
|
+
import { execFileSync as execFileSync2, spawn as realSpawn3 } from "child_process";
|
|
32995
33293
|
import { createHash as createHash2 } from "crypto";
|
|
32996
33294
|
import { existsSync as existsSync2 } from "fs";
|
|
32997
33295
|
import { homedir as homedir4, tmpdir } from "os";
|
|
@@ -33027,7 +33325,7 @@ var SURVEY_DOC_IDS = [
|
|
|
33027
33325
|
var DEEPEN_DIFF_TARGET = 300;
|
|
33028
33326
|
function commitCount(repoDir) {
|
|
33029
33327
|
try {
|
|
33030
|
-
const out =
|
|
33328
|
+
const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
33031
33329
|
encoding: "utf8",
|
|
33032
33330
|
windowsHide: true,
|
|
33033
33331
|
stdio: ["ignore", "pipe", "pipe"]
|
|
@@ -33098,19 +33396,7 @@ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
|
|
|
33098
33396
|
idempotentHint: false,
|
|
33099
33397
|
openWorldHint: false
|
|
33100
33398
|
};
|
|
33101
|
-
var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention.';
|
|
33102
|
-
function shapePage(page) {
|
|
33103
|
-
const p = page ?? {};
|
|
33104
|
-
const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
|
|
33105
|
-
return {
|
|
33106
|
-
id: p.id,
|
|
33107
|
-
name: p.name,
|
|
33108
|
-
...p.description ? { description: p.description } : {},
|
|
33109
|
-
...Array.isArray(p.tags) && p.tags.length ? { tags: p.tags } : {},
|
|
33110
|
-
...p.timestamp ? { last_updated_at: p.timestamp } : {},
|
|
33111
|
-
body
|
|
33112
|
-
};
|
|
33113
|
-
}
|
|
33399
|
+
var CREDIT_REMINDER = 'Crediting is mandatory, not a judgement call: if anything these results contribute reaches your reply \u2014 quoted, paraphrased, or merely confirming what you were going to say \u2014 open that part with "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>". Rewriting a snippet in your own words does not make it yours. If none of them bear on the turn, ignore them silently \u2014 an unhelpful search needs no mention. These are past records: check a claim that something was fixed or works against the code before relying on it.';
|
|
33114
33400
|
function ok(value) {
|
|
33115
33401
|
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
|
33116
33402
|
}
|
|
@@ -33128,6 +33414,8 @@ function guarded(fn) {
|
|
|
33128
33414
|
};
|
|
33129
33415
|
}
|
|
33130
33416
|
function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
33417
|
+
const extra = opts.toolGuideExtra?.trim();
|
|
33418
|
+
const crediting = extra ? `${CREDIT_REMINDER} ${extra}` : CREDIT_REMINDER;
|
|
33131
33419
|
return [
|
|
33132
33420
|
{
|
|
33133
33421
|
name: "hindsight_sync_status",
|
|
@@ -33187,7 +33475,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
33187
33475
|
},
|
|
33188
33476
|
{
|
|
33189
33477
|
name: "hindsight_search_knowledge_pages",
|
|
33190
|
-
description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " +
|
|
33478
|
+
description: "Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. " + crediting,
|
|
33191
33479
|
inputSchema: { query: external_exports.string().describe("what to look for") },
|
|
33192
33480
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
33193
33481
|
handler: async (args) => {
|
|
@@ -33197,9 +33485,12 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
33197
33485
|
pages: hits.map((h) => ({
|
|
33198
33486
|
page: h.name,
|
|
33199
33487
|
page_id: h.id,
|
|
33488
|
+
// The question the page answers — the same `description` the list and read tools
|
|
33489
|
+
// carry, so a hit says what the page is FOR, not just how it opens.
|
|
33490
|
+
...h.source_query ? { description: h.source_query } : {},
|
|
33200
33491
|
snippet: h.snippet
|
|
33201
33492
|
})),
|
|
33202
|
-
crediting
|
|
33493
|
+
crediting
|
|
33203
33494
|
});
|
|
33204
33495
|
} catch (e) {
|
|
33205
33496
|
return err(e);
|
|
@@ -33218,7 +33509,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
33218
33509
|
description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
|
|
33219
33510
|
inputSchema: { page_id: external_exports.string() },
|
|
33220
33511
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
33221
|
-
handler: guarded(async ({ page_id }) =>
|
|
33512
|
+
handler: guarded(async ({ page_id }) => client.getPage(page_id))
|
|
33222
33513
|
},
|
|
33223
33514
|
{
|
|
33224
33515
|
name: "hindsight_reflect",
|
|
@@ -33304,7 +33595,8 @@ function resolversFor(ctx) {
|
|
|
33304
33595
|
function buildRetainStamp(cfg, ctx) {
|
|
33305
33596
|
const hasTags = Boolean(cfg.retainTags?.length);
|
|
33306
33597
|
const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
|
|
33307
|
-
|
|
33598
|
+
const hasContext = Boolean(cfg.retainContext?.trim());
|
|
33599
|
+
if (!hasTags && !hasMetadata && !hasContext) return { tags: [], metadata: {} };
|
|
33308
33600
|
const base = resolversFor(ctx);
|
|
33309
33601
|
const cache = /* @__PURE__ */ new Map();
|
|
33310
33602
|
const resolvers = Object.fromEntries(
|
|
@@ -33328,7 +33620,8 @@ function buildRetainStamp(cfg, ctx) {
|
|
|
33328
33620
|
for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
|
|
33329
33621
|
metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
|
|
33330
33622
|
}
|
|
33331
|
-
|
|
33623
|
+
const context = hasContext ? applyTemplate(cfg.retainContext, resolvers, "retainContext").trim() || void 0 : void 0;
|
|
33624
|
+
return { tags, metadata, context };
|
|
33332
33625
|
}
|
|
33333
33626
|
|
|
33334
33627
|
// src/mcp-server.ts
|
|
@@ -33341,6 +33634,7 @@ function selectTools(cfg, client, bankId, opts = {}) {
|
|
|
33341
33634
|
pageTrigger: buildPageTrigger(cfg),
|
|
33342
33635
|
reflectTimeoutMs: cfg.reflectToolTimeoutMs,
|
|
33343
33636
|
reflectBudget: cfg.reflectBudget,
|
|
33637
|
+
toolGuideExtra: cfg.toolGuideExtra,
|
|
33344
33638
|
stampFor: () => buildRetainStamp(cfg, { directory: cwd, harness, bankId })
|
|
33345
33639
|
});
|
|
33346
33640
|
}
|
|
@@ -33353,6 +33647,15 @@ function resolveHarness(env = process.env) {
|
|
|
33353
33647
|
}
|
|
33354
33648
|
return harness;
|
|
33355
33649
|
}
|
|
33650
|
+
function resolveProjectCwd(env = process.env, argv = process.argv, fallbackCwd = process.cwd()) {
|
|
33651
|
+
const override = env.HINDSIGHT_MCP_PROJECT_CWD?.trim();
|
|
33652
|
+
if (override && !override.includes("${")) return override;
|
|
33653
|
+
if (env.HINDSIGHT_MCP_HARNESS === "cursor-cli") {
|
|
33654
|
+
const folder = argv[2]?.trim();
|
|
33655
|
+
if (folder && !folder.includes("${")) return folder;
|
|
33656
|
+
}
|
|
33657
|
+
return fallbackCwd;
|
|
33658
|
+
}
|
|
33356
33659
|
function buildMcpServer(tools) {
|
|
33357
33660
|
const server = new McpServer({ name: "hindsight", version: "0.1.0" });
|
|
33358
33661
|
if (tools.length === 0) {
|
|
@@ -33374,7 +33677,7 @@ function buildMcpServer(tools) {
|
|
|
33374
33677
|
return server;
|
|
33375
33678
|
}
|
|
33376
33679
|
async function main() {
|
|
33377
|
-
const cwd =
|
|
33680
|
+
const cwd = resolveProjectCwd();
|
|
33378
33681
|
const harness = resolveHarness();
|
|
33379
33682
|
const { cfg, bankId, client } = resolveHostMemory(harness, cwd);
|
|
33380
33683
|
const server = buildMcpServer(selectTools(cfg, client, bankId, { cwd, harness }));
|
|
@@ -33389,5 +33692,6 @@ if (process.argv[1] && process.argv[1] === fileURLToPath3(import.meta.url)) {
|
|
|
33389
33692
|
export {
|
|
33390
33693
|
buildMcpServer,
|
|
33391
33694
|
resolveHarness,
|
|
33695
|
+
resolveProjectCwd,
|
|
33392
33696
|
selectTools
|
|
33393
33697
|
};
|