notesoup 0.57.3 → 0.58.0
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 +15 -1
- package/dist/plugins/claude/src/helper.js +2 -11
- package/dist/plugins/claude/src/thresholds.js +5 -18
- package/dist/plugins/codex/src/mcp.js +3 -11
- package/dist/plugins/codex/src/state.d.ts +1 -1
- package/dist/plugins/codex/src/state.js +1 -1
- package/dist/plugins/dsh/tools.js +1 -1
- package/dist/plugins/pi/boot.d.ts +1 -1
- package/dist/plugins/pi/boot.js +2 -3
- package/dist/plugins/pi/budget.d.ts +1 -1
- package/dist/plugins/pi/budget.js +1 -1
- package/dist/plugins/pi/render.d.ts +1 -1
- package/dist/plugins/pi/render.js +20 -11
- package/dist/plugins/pi/runtime.js +6 -2
- package/dist/plugins/pi/tool-result.d.ts +2 -1
- package/dist/plugins/pi/window.js +24 -1
- package/dist/src/boot/render.d.ts +3 -4
- package/dist/src/boot/render.js +23 -21
- package/dist/src/boot/text.d.ts +2 -5
- package/dist/src/boot/text.js +12 -9
- package/dist/src/budget/text.d.ts +1 -1
- package/dist/src/budget/text.js +1 -1
- package/dist/src/history/corpus.d.ts +1 -1
- package/dist/src/history/corpus.js +1 -1
- package/dist/src/history/history.d.ts +2 -2
- package/dist/src/history/history.js +5 -8
- package/dist/src/history/query.d.ts +11 -3
- package/dist/src/history/query.js +7 -11
- package/dist/src/index.d.ts +4 -3
- package/dist/src/index.js +1 -1
- package/dist/src/notes/constants.d.ts +1 -1
- package/dist/src/notes/constants.js +1 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.d.ts +2 -1
- package/dist/src/notes/frontmatter.js +3 -1
- package/dist/src/notes/index.d.ts +1 -0
- package/dist/src/notes/index.js +1 -0
- package/dist/src/notes/policy.d.ts +16 -0
- package/dist/src/notes/policy.js +43 -0
- package/dist/src/notes/store.d.ts +8 -3
- package/dist/src/notes/store.js +64 -20
- package/dist/src/result.d.ts +21 -0
- package/dist/src/result.js +18 -0
- package/dist/src/text-match.d.ts +8 -0
- package/dist/src/text-match.js +34 -0
- package/dist/src/tools/dream.d.ts +9 -1
- package/dist/src/tools/dream.js +2 -1
- package/dist/src/tools/history.js +14 -5
- package/dist/src/tools/notes.d.ts +75 -13
- package/dist/src/tools/notes.js +58 -19
- package/dist/src/tools/output.d.ts +1 -3
- package/dist/src/tools/output.js +1 -19
- package/dist/src/tools/result.d.ts +2 -20
- package/dist/src/tools/result.js +4 -18
- package/dist/src/tools/schema.d.ts +3 -7
- package/dist/src/tools/schema.js +10 -16
- package/dist/test/agent-loop.test.js +78 -6
- package/dist/test/boot.integration.test.js +30 -3
- package/dist/test/claude-mod.test.js +7 -6
- package/dist/test/codex-history.test.js +2 -2
- package/dist/test/codex-plugin.test.js +2 -0
- package/dist/test/dependencies.test.js +38 -3
- package/dist/test/dsh.test.js +1 -1
- package/dist/test/helpers/dependency-graph.js +12 -6
- package/dist/test/helpers/extension.d.ts +2 -1
- package/dist/test/history.integration.test.js +47 -1
- package/dist/test/host-neutral.test.js +4 -3
- package/dist/test/model-facing-text.test.js +20 -16
- package/dist/test/note-policy.test.d.ts +1 -0
- package/dist/test/note-policy.test.js +227 -0
- package/dist/test/notes-query-namespaces.test.js +7 -3
- package/dist/test/notes.integration.test.js +10 -10
- package/dist/test/notes.test.js +4 -4
- package/dist/test/pi-render.test.js +28 -1
- package/dist/test/project-namespace.test.js +1 -1
- package/docs/architecture.md +10 -7
- package/docs/dsh.md +1 -1
- package/docs/notes-library.md +20 -7
- package/docs/reset-lifecycle.md +2 -2
- package/docs/tool-results.md +3 -1
- package/package.json +12 -12
- package/playbook.md +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +528 -422
- package/plugins/claude/hooks/register.ts +1 -10
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/memory/SKILL.md +1 -1
- package/plugins/claude/src/helper.ts +2 -11
- package/plugins/claude/src/thresholds.ts +5 -15
- package/plugins/codex/dist/codex/notesoup.js +520 -403
- package/plugins/codex/src/mcp.ts +5 -12
- package/plugins/codex/src/state.ts +1 -1
- package/plugins/dsh/tools.ts +2 -1
- package/plugins/pi/boot.ts +3 -4
- package/plugins/pi/budget.ts +1 -1
- package/plugins/pi/render.ts +20 -8
- package/plugins/pi/runtime.ts +6 -2
- package/plugins/pi/tool-result.ts +2 -1
- package/plugins/pi/window.ts +20 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +24 -21
- package/src/boot/text.ts +12 -9
- package/src/budget/text.ts +1 -1
- package/src/history/corpus.ts +1 -1
- package/src/history/history.ts +5 -6
- package/src/history/query.ts +11 -14
- package/src/index.ts +5 -2
- package/src/notes/constants.ts +1 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +4 -2
- package/src/notes/index.ts +1 -0
- package/src/notes/policy.ts +49 -0
- package/src/notes/store.ts +66 -26
- package/src/result.ts +26 -0
- package/src/text-match.ts +32 -0
- package/src/tools/dream.ts +2 -1
- package/src/tools/history.ts +15 -6
- package/src/tools/notes.ts +60 -20
- package/src/tools/output.ts +1 -17
- package/src/tools/result.ts +4 -26
- package/src/tools/schema.ts +11 -17
- package/dist/plugins/codex/src/history.d.ts +0 -3
- package/dist/plugins/codex/src/history.js +0 -2
- package/dist/plugins/codex/src/transcript.d.ts +0 -3
- package/dist/plugins/codex/src/transcript.js +0 -2
- package/plugins/codex/src/history.ts +0 -3
- package/plugins/codex/src/transcript.ts +0 -3
|
@@ -7849,146 +7849,181 @@ __export(typebox_exports, {
|
|
|
7849
7849
|
With: () => With2
|
|
7850
7850
|
});
|
|
7851
7851
|
|
|
7852
|
-
// src/
|
|
7853
|
-
var
|
|
7854
|
-
var
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
var pad2 = (value) => String(value).padStart(2, "0");
|
|
7858
|
-
function localIso(epochMs) {
|
|
7859
|
-
const date = new Date(epochMs);
|
|
7860
|
-
const offsetMinutes = -date.getTimezoneOffset();
|
|
7861
|
-
const absOffset = Math.abs(offsetMinutes);
|
|
7862
|
-
const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
|
|
7863
|
-
const wallClock = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
|
|
7864
|
-
return `${wallClock}${offset}`;
|
|
7852
|
+
// src/history/history.ts
|
|
7853
|
+
var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
|
|
7854
|
+
var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
|
|
7855
|
+
function isTextContent(part) {
|
|
7856
|
+
return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
|
|
7865
7857
|
}
|
|
7866
|
-
function
|
|
7867
|
-
|
|
7858
|
+
function contentText(content) {
|
|
7859
|
+
if (typeof content === "string") return content;
|
|
7860
|
+
return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
|
|
7868
7861
|
}
|
|
7869
|
-
function
|
|
7870
|
-
return
|
|
7862
|
+
function argumentText(execution) {
|
|
7863
|
+
return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
|
|
7871
7864
|
}
|
|
7872
|
-
function
|
|
7873
|
-
|
|
7874
|
-
if (
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
}
|
|
7878
|
-
return fallback;
|
|
7865
|
+
function nestedCallLine(call) {
|
|
7866
|
+
const parts = [`${call.id} ${call.name} [${call.status}]`];
|
|
7867
|
+
if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
|
|
7868
|
+
if (call.error !== void 0) parts.push(`error: ${call.error}`);
|
|
7869
|
+
parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
|
|
7870
|
+
return `- ${parts.join(" ")}`;
|
|
7879
7871
|
}
|
|
7880
|
-
function
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
|
|
7884
|
-
|
|
7885
|
-
|
|
7886
|
-
|
|
7887
|
-
|
|
7872
|
+
function historyDocument(event) {
|
|
7873
|
+
if (event.execution === void 0) return event.text;
|
|
7874
|
+
const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
|
|
7875
|
+
if (event.text !== "") sections.push(`--- output ---
|
|
7876
|
+
${event.text}`);
|
|
7877
|
+
const nested = event.execution.nestedCalls;
|
|
7878
|
+
if (nested !== void 0) {
|
|
7879
|
+
const header2 = nested.complete ? "complete" : "incomplete";
|
|
7880
|
+
sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
|
|
7881
|
+
${nested.calls.map(nestedCallLine).join("\n")}`);
|
|
7888
7882
|
}
|
|
7883
|
+
return sections.join("\n");
|
|
7889
7884
|
}
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
const
|
|
7893
|
-
if (
|
|
7894
|
-
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
7898
|
-
|
|
7885
|
+
var documents = /* @__PURE__ */ new WeakMap();
|
|
7886
|
+
function eventDocument(event) {
|
|
7887
|
+
const cached = documents.get(event);
|
|
7888
|
+
if (cached !== void 0) return cached;
|
|
7889
|
+
const text = historyDocument(event);
|
|
7890
|
+
documents.set(event, text);
|
|
7891
|
+
return text;
|
|
7892
|
+
}
|
|
7893
|
+
function toolEvent(item, result) {
|
|
7894
|
+
const run = result ?? item;
|
|
7895
|
+
const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
|
|
7896
|
+
const truncated = run.outputTruncated === true;
|
|
7897
|
+
return {
|
|
7898
|
+
seq: item.seq,
|
|
7899
|
+
windowId: item.windowId,
|
|
7900
|
+
role: "tool",
|
|
7901
|
+
text: result?.text ?? (item.role === "tool" ? item.text : ""),
|
|
7902
|
+
createdAt: item.createdAt,
|
|
7903
|
+
execution: {
|
|
7904
|
+
name: item.toolName ?? "unknown",
|
|
7905
|
+
status,
|
|
7906
|
+
// A call records its arguments; a bare result records none, and gets none invented.
|
|
7907
|
+
...item.arguments === void 0 ? {} : { arguments: item.arguments },
|
|
7908
|
+
...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
|
|
7909
|
+
...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
|
|
7899
7910
|
}
|
|
7911
|
+
};
|
|
7912
|
+
}
|
|
7913
|
+
function projectHistory(rawWindows, highestSeq, branchSeqs) {
|
|
7914
|
+
const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
|
|
7915
|
+
const resultsById = /* @__PURE__ */ new Map();
|
|
7916
|
+
for (const item of raw) {
|
|
7917
|
+
if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
|
|
7900
7918
|
}
|
|
7901
|
-
|
|
7902
|
-
const
|
|
7903
|
-
|
|
7904
|
-
|
|
7905
|
-
|
|
7906
|
-
if (!match) continue;
|
|
7907
|
-
const key = match[1];
|
|
7908
|
-
const rest2 = match[2];
|
|
7909
|
-
if (rest2.trim() === "") {
|
|
7910
|
-
const items = [];
|
|
7911
|
-
while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
|
|
7912
|
-
index++;
|
|
7913
|
-
items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
|
|
7914
|
-
}
|
|
7915
|
-
fields[key] = items;
|
|
7916
|
-
} else {
|
|
7917
|
-
fields[key] = parseScalar(rest2);
|
|
7919
|
+
const pairedResults = /* @__PURE__ */ new Map();
|
|
7920
|
+
for (const item of raw) {
|
|
7921
|
+
const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
|
|
7922
|
+
if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
|
|
7923
|
+
pairedResults.set(result.seq, item.seq);
|
|
7918
7924
|
}
|
|
7919
7925
|
}
|
|
7920
|
-
const
|
|
7921
|
-
|
|
7922
|
-
|
|
7926
|
+
const windows = rawWindows.map((current) => ({
|
|
7927
|
+
windowId: current.windowId,
|
|
7928
|
+
...current.createdAt ? { createdAt: current.createdAt } : {},
|
|
7929
|
+
items: current.items.flatMap((item) => {
|
|
7930
|
+
if (pairedResults.has(item.seq)) return [];
|
|
7931
|
+
if (item.role === "tool_call" || item.role === "tool") {
|
|
7932
|
+
const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
|
|
7933
|
+
const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
|
|
7934
|
+
return [toolEvent(item, paired)];
|
|
7935
|
+
}
|
|
7936
|
+
return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
|
|
7937
|
+
})
|
|
7938
|
+
}));
|
|
7939
|
+
return { windows, highestSeq, branchSeqs, pairedResults };
|
|
7923
7940
|
}
|
|
7924
|
-
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7941
|
+
var NestedCallSummarySchema = typebox_exports.Object({
|
|
7942
|
+
call_count: typebox_exports.Integer({ minimum: 0 }),
|
|
7943
|
+
complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
|
|
7944
|
+
}, { additionalProperties: false });
|
|
7945
|
+
var ToolSummarySchema = typebox_exports.Object({
|
|
7946
|
+
tool: typebox_exports.Optional(typebox_exports.String()),
|
|
7947
|
+
tool_status: typebox_exports.Optional(ToolCallStatusSchema),
|
|
7948
|
+
output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
|
|
7949
|
+
full_output_path: typebox_exports.Optional(typebox_exports.String())
|
|
7950
|
+
}, { additionalProperties: false });
|
|
7951
|
+
function toolSummary(event) {
|
|
7952
|
+
const execution = event.execution;
|
|
7953
|
+
if (!execution) return {};
|
|
7954
|
+
return {
|
|
7955
|
+
tool: execution.name,
|
|
7956
|
+
tool_status: execution.status,
|
|
7957
|
+
...execution.outputTruncated ? { output_truncated: true } : {},
|
|
7958
|
+
...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
|
|
7959
|
+
};
|
|
7932
7960
|
}
|
|
7933
|
-
function
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
|
|
7937
|
-
}
|
|
7938
|
-
return JSON.stringify(value);
|
|
7961
|
+
function nestedCallSummary(event) {
|
|
7962
|
+
const nested = event.execution?.nestedCalls;
|
|
7963
|
+
return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
|
|
7939
7964
|
}
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
}
|
|
7965
|
+
var HistoryFoldedRowSchema = typebox_exports.Object({
|
|
7966
|
+
session: typebox_exports.Optional(typebox_exports.String()),
|
|
7967
|
+
first_seq: typebox_exports.Integer({ minimum: 1 }),
|
|
7968
|
+
last_seq: typebox_exports.Integer({ minimum: 1 }),
|
|
7969
|
+
count: typebox_exports.Integer({ minimum: 1 }),
|
|
7970
|
+
tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
|
|
7971
|
+
}, { additionalProperties: false });
|
|
7972
|
+
var HistoryPageItemSchema = typebox_exports.Object({
|
|
7973
|
+
session: typebox_exports.Optional(typebox_exports.String()),
|
|
7974
|
+
folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
|
|
7975
|
+
seq: typebox_exports.Integer({ minimum: 1 }),
|
|
7976
|
+
role: HistoryRoleSchema,
|
|
7977
|
+
created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
|
|
7978
|
+
...ToolSummarySchema.properties,
|
|
7979
|
+
content: typebox_exports.String(),
|
|
7980
|
+
truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
|
|
7981
|
+
offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
|
|
7982
|
+
}, { additionalProperties: false });
|
|
7983
|
+
var MAX_FOLD_TOOL_NAMES = 20;
|
|
7984
|
+
var MAX_FOLD_TOOL_NAME_CHARS = 120;
|
|
7985
|
+
function visibleItem(event, maxChars, matchOffset) {
|
|
7986
|
+
const document = eventDocument(event);
|
|
7987
|
+
const chars = Array.from(document);
|
|
7988
|
+
const start = matchOffset ?? 0;
|
|
7989
|
+
const limit = Math.max(0, maxChars);
|
|
7990
|
+
const truncated = start > 0 || start + limit < chars.length;
|
|
7991
|
+
return {
|
|
7992
|
+
seq: event.seq,
|
|
7993
|
+
role: event.role,
|
|
7994
|
+
created_at: event.createdAt ?? null,
|
|
7995
|
+
...toolSummary(event),
|
|
7996
|
+
content: truncated ? chars.slice(start, start + limit).join("") : document,
|
|
7997
|
+
truncated,
|
|
7998
|
+
...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
|
|
7999
|
+
};
|
|
7946
8000
|
}
|
|
7947
|
-
function
|
|
7948
|
-
|
|
7949
|
-
for (const key of KNOWN_KEYS) {
|
|
7950
|
-
const value = meta[key];
|
|
7951
|
-
if (value === void 0) continue;
|
|
7952
|
-
if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
|
|
7953
|
-
else lines.push(`${key}: ${yamlScalar(value)}`);
|
|
7954
|
-
}
|
|
7955
|
-
for (const key of Object.keys(meta)) {
|
|
7956
|
-
if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
|
|
7957
|
-
if (meta[key] === void 0) continue;
|
|
7958
|
-
lines.push(`${key}: ${yamlScalar(meta[key])}`);
|
|
7959
|
-
}
|
|
7960
|
-
return `---
|
|
7961
|
-
${lines.join("\n")}
|
|
7962
|
-
---
|
|
7963
|
-
|
|
7964
|
-
${body}`;
|
|
8001
|
+
function allItems(projection) {
|
|
8002
|
+
return projection.windows.flatMap((current) => current.items);
|
|
7965
8003
|
}
|
|
7966
|
-
function
|
|
7967
|
-
|
|
8004
|
+
function inSelection(event, params) {
|
|
8005
|
+
if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
|
|
8006
|
+
if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
|
|
8007
|
+
if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
|
|
8008
|
+
if (event.createdAt === void 0) return false;
|
|
8009
|
+
const at = Date.parse(event.createdAt);
|
|
8010
|
+
return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
|
|
7968
8011
|
}
|
|
7969
|
-
|
|
7970
|
-
|
|
7971
|
-
function isFilesystemError(error) {
|
|
7972
|
-
const code = typeof error === "object" && error !== null ? error.code : void 0;
|
|
7973
|
-
return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
|
|
8012
|
+
function filteredItems(projection, params) {
|
|
8013
|
+
return allItems(projection).filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role))).sort((a, b) => a.seq - b.seq);
|
|
7974
8014
|
}
|
|
7975
8015
|
|
|
7976
|
-
// src/
|
|
7977
|
-
|
|
7978
|
-
|
|
7979
|
-
|
|
7980
|
-
|
|
7981
|
-
|
|
7982
|
-
|
|
7983
|
-
|
|
7984
|
-
|
|
7985
|
-
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7986
|
-
const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
|
|
7987
|
-
if (index < 0) continue;
|
|
7988
|
-
if (earliest < 0 || index < earliest) earliest = index;
|
|
7989
|
-
}
|
|
7990
|
-
return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
|
|
8016
|
+
// src/tools/schema.ts
|
|
8017
|
+
var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
|
|
8018
|
+
var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
|
|
8019
|
+
function paramProblem(schema, params) {
|
|
8020
|
+
const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
|
|
8021
|
+
if (!first) return "unrecognized shape";
|
|
8022
|
+
const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
|
|
8023
|
+
const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
|
|
8024
|
+
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
7991
8025
|
}
|
|
8026
|
+
var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
|
|
7992
8027
|
|
|
7993
8028
|
// src/notes/errors.ts
|
|
7994
8029
|
var NoteError = class extends Error {
|
|
@@ -8111,22 +8146,226 @@ function assertAddress(value) {
|
|
|
8111
8146
|
if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
8112
8147
|
if (path === "" && who === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
|
|
8113
8148
|
}
|
|
8114
|
-
assertVirtualPath(path);
|
|
8115
|
-
return { scope, path, who };
|
|
8116
|
-
}
|
|
8117
|
-
function canonicalAddressFor(identity2, scope, path, who) {
|
|
8118
|
-
if (scope === "session") return `@sessions/${who ?? identity2.sessionId}/${path}`;
|
|
8119
|
-
if (scope === "project") return `@projects/${who ?? identity2.projectKey}/${path}`;
|
|
8120
|
-
if (scope === "human") return `@human/${path}`;
|
|
8121
|
-
if (scope === "agent") return `@agents/${who ?? identity2.agent}/${path}`;
|
|
8122
|
-
return `@models/${who ?? identity2.model}/${path}`;
|
|
8149
|
+
assertVirtualPath(path);
|
|
8150
|
+
return { scope, path, who };
|
|
8151
|
+
}
|
|
8152
|
+
function canonicalAddressFor(identity2, scope, path, who) {
|
|
8153
|
+
if (scope === "session") return `@sessions/${who ?? identity2.sessionId}/${path}`;
|
|
8154
|
+
if (scope === "project") return `@projects/${who ?? identity2.projectKey}/${path}`;
|
|
8155
|
+
if (scope === "human") return `@human/${path}`;
|
|
8156
|
+
if (scope === "agent") return `@agents/${who ?? identity2.agent}/${path}`;
|
|
8157
|
+
return `@models/${who ?? identity2.model}/${path}`;
|
|
8158
|
+
}
|
|
8159
|
+
function addressFor(identity2, scope, path, who) {
|
|
8160
|
+
if (scope === "session" && who === void 0) return path;
|
|
8161
|
+
if (scope === "project" && who === void 0) return `@project/${path}`;
|
|
8162
|
+
if (scope === "agent" && (who === void 0 || who === identity2.agent)) return `@self/${path}`;
|
|
8163
|
+
if (scope === "model" && (who === void 0 || who === identity2.model)) return `@model/${path}`;
|
|
8164
|
+
return canonicalAddressFor(identity2, scope, path, who);
|
|
8165
|
+
}
|
|
8166
|
+
|
|
8167
|
+
// src/notes/policy.ts
|
|
8168
|
+
var DEFAULT_NOTE_BUDGET = 2048;
|
|
8169
|
+
var MAX_PINNED_NOTES = 5;
|
|
8170
|
+
var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
|
|
8171
|
+
function validateNotePolicy(fields) {
|
|
8172
|
+
for (const key of ["pinned", "readonly"]) {
|
|
8173
|
+
if (fields[key] !== void 0 && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
|
|
8174
|
+
}
|
|
8175
|
+
if (fields.budget !== void 0 && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
|
|
8176
|
+
throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
|
|
8177
|
+
}
|
|
8178
|
+
}
|
|
8179
|
+
function effectiveNotePolicy(fields, path) {
|
|
8180
|
+
validateNotePolicy(fields);
|
|
8181
|
+
return {
|
|
8182
|
+
pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some((page) => page === path),
|
|
8183
|
+
budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
|
|
8184
|
+
readonly: fields.readonly ?? false
|
|
8185
|
+
};
|
|
8186
|
+
}
|
|
8187
|
+
function pinnedPageOrder(path) {
|
|
8188
|
+
const index = DEFAULT_PINNED_PAGES.findIndex((page) => page === path);
|
|
8189
|
+
return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
|
|
8190
|
+
}
|
|
8191
|
+
function noteBudgetWarnings(body, policy) {
|
|
8192
|
+
const count = Array.from(body).length;
|
|
8193
|
+
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
|
|
8194
|
+
}
|
|
8195
|
+
function assertNoteUnlocked(fields, unlock) {
|
|
8196
|
+
if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
|
|
8197
|
+
}
|
|
8198
|
+
function applyNotePolicy(target, fields) {
|
|
8199
|
+
validateNotePolicy(fields);
|
|
8200
|
+
for (const key of ["pinned", "budget", "readonly"]) {
|
|
8201
|
+
if (fields[key] !== void 0) Object.assign(target, { [key]: fields[key] });
|
|
8202
|
+
}
|
|
8203
|
+
}
|
|
8204
|
+
|
|
8205
|
+
// src/notes/frontmatter.ts
|
|
8206
|
+
var SCOPES = ["session", "project", "human", "agent", "model"];
|
|
8207
|
+
var ORIGINS = ["user", "self", "external"];
|
|
8208
|
+
var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
|
|
8209
|
+
var KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
|
|
8210
|
+
var pad2 = (value) => String(value).padStart(2, "0");
|
|
8211
|
+
function localIso(epochMs) {
|
|
8212
|
+
const date = new Date(epochMs);
|
|
8213
|
+
const offsetMinutes = -date.getTimezoneOffset();
|
|
8214
|
+
const absOffset = Math.abs(offsetMinutes);
|
|
8215
|
+
const offset = `${offsetMinutes < 0 ? "-" : "+"}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`;
|
|
8216
|
+
const wallClock = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}T${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}.${String(date.getMilliseconds()).padStart(3, "0")}`;
|
|
8217
|
+
return `${wallClock}${offset}`;
|
|
8218
|
+
}
|
|
8219
|
+
function isScope(value) {
|
|
8220
|
+
return typeof value === "string" && SCOPES.includes(value);
|
|
8221
|
+
}
|
|
8222
|
+
function isOrigin(value) {
|
|
8223
|
+
return typeof value === "string" && ORIGINS.includes(value);
|
|
8224
|
+
}
|
|
8225
|
+
function toEpoch(value, fallback) {
|
|
8226
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
8227
|
+
if (typeof value === "string") {
|
|
8228
|
+
const parsed = Date.parse(value);
|
|
8229
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
8230
|
+
}
|
|
8231
|
+
return fallback;
|
|
8232
|
+
}
|
|
8233
|
+
function parseScalar(text) {
|
|
8234
|
+
const trimmed = text.trim();
|
|
8235
|
+
if (trimmed === "") return "";
|
|
8236
|
+
try {
|
|
8237
|
+
return JSON.parse(trimmed);
|
|
8238
|
+
} catch {
|
|
8239
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
|
|
8240
|
+
return trimmed;
|
|
8241
|
+
}
|
|
8242
|
+
}
|
|
8243
|
+
function parseFrontmatter(raw) {
|
|
8244
|
+
const stripped = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
|
|
8245
|
+
const lines = stripped.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
8246
|
+
if (lines[0]?.trim() !== "---") return { fields: {}, body: raw };
|
|
8247
|
+
let close = -1;
|
|
8248
|
+
for (let index = 1; index < lines.length; index++) {
|
|
8249
|
+
if (lines[index]?.trim() === "---") {
|
|
8250
|
+
close = index;
|
|
8251
|
+
break;
|
|
8252
|
+
}
|
|
8253
|
+
}
|
|
8254
|
+
if (close === -1) return { fields: {}, body: raw };
|
|
8255
|
+
const fields = /* @__PURE__ */ Object.create(null);
|
|
8256
|
+
for (let index = 1; index < close; index++) {
|
|
8257
|
+
const line = lines[index];
|
|
8258
|
+
const match = /^([A-Za-z_][A-Za-z0-9_-]*):(.*)$/.exec(line);
|
|
8259
|
+
if (!match) continue;
|
|
8260
|
+
const key = match[1];
|
|
8261
|
+
const rest2 = match[2];
|
|
8262
|
+
if (rest2.trim() === "") {
|
|
8263
|
+
const items = [];
|
|
8264
|
+
while (index + 1 < close && /^\s*-\s+/.test(lines[index + 1])) {
|
|
8265
|
+
index++;
|
|
8266
|
+
items.push(parseScalar(lines[index].replace(/^\s*-\s+/, "")));
|
|
8267
|
+
}
|
|
8268
|
+
fields[key] = items;
|
|
8269
|
+
} else {
|
|
8270
|
+
fields[key] = parseScalar(rest2);
|
|
8271
|
+
}
|
|
8272
|
+
}
|
|
8273
|
+
const rest = lines.slice(close + 1);
|
|
8274
|
+
if (rest[0] === "") rest.shift();
|
|
8275
|
+
return { fields, body: rest.join("\n") };
|
|
8276
|
+
}
|
|
8277
|
+
function parseNote(raw, now = Date.now()) {
|
|
8278
|
+
const { fields, body } = parseFrontmatter(raw);
|
|
8279
|
+
validateNotePolicy(fields);
|
|
8280
|
+
const meta = { ...fields };
|
|
8281
|
+
meta.scope = isScope(meta.scope) ? meta.scope : "session";
|
|
8282
|
+
meta.origin = isOrigin(meta.origin) ? meta.origin : "self";
|
|
8283
|
+
for (const key of TIMESTAMP_KEYS) meta[key] = toEpoch(meta[key], now);
|
|
8284
|
+
meta.accessCount = typeof meta.accessCount === "number" && Number.isFinite(meta.accessCount) ? meta.accessCount : 0;
|
|
8285
|
+
return { meta, body };
|
|
8286
|
+
}
|
|
8287
|
+
function yamlScalar(value) {
|
|
8288
|
+
if (typeof value === "string") {
|
|
8289
|
+
const reserved = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
|
|
8290
|
+
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
|
|
8291
|
+
}
|
|
8292
|
+
return JSON.stringify(value);
|
|
8293
|
+
}
|
|
8294
|
+
function parsesAsNonString(text) {
|
|
8295
|
+
try {
|
|
8296
|
+
return typeof JSON.parse(text) !== "string";
|
|
8297
|
+
} catch {
|
|
8298
|
+
return false;
|
|
8299
|
+
}
|
|
8300
|
+
}
|
|
8301
|
+
function serializeNote(meta, body) {
|
|
8302
|
+
const lines = [];
|
|
8303
|
+
for (const key of KNOWN_KEYS) {
|
|
8304
|
+
const value = meta[key];
|
|
8305
|
+
if (value === void 0) continue;
|
|
8306
|
+
if (TIMESTAMP_KEYS.includes(key)) lines.push(`${key}: ${yamlScalar(localIso(value))}`);
|
|
8307
|
+
else lines.push(`${key}: ${yamlScalar(value)}`);
|
|
8308
|
+
}
|
|
8309
|
+
for (const key of Object.keys(meta)) {
|
|
8310
|
+
if (key === "scope" || KNOWN_KEYS.includes(key)) continue;
|
|
8311
|
+
if (meta[key] === void 0) continue;
|
|
8312
|
+
lines.push(`${key}: ${yamlScalar(meta[key])}`);
|
|
8313
|
+
}
|
|
8314
|
+
return `---
|
|
8315
|
+
${lines.join("\n")}
|
|
8316
|
+
---
|
|
8317
|
+
|
|
8318
|
+
${body}`;
|
|
8319
|
+
}
|
|
8320
|
+
function stripLeadingFrontmatter(content) {
|
|
8321
|
+
return parseFrontmatter(content).body;
|
|
8322
|
+
}
|
|
8323
|
+
|
|
8324
|
+
// src/notes/fs-error.ts
|
|
8325
|
+
function isFilesystemError(error) {
|
|
8326
|
+
const code = typeof error === "object" && error !== null ? error.code : void 0;
|
|
8327
|
+
return typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) && !code.startsWith("ERR_");
|
|
8328
|
+
}
|
|
8329
|
+
|
|
8330
|
+
// src/notes/store.ts
|
|
8331
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8332
|
+
import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
8333
|
+
import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
|
|
8334
|
+
|
|
8335
|
+
// src/text-match.ts
|
|
8336
|
+
var InvalidQueryError = class extends Error {
|
|
8337
|
+
constructor(message) {
|
|
8338
|
+
super(message);
|
|
8339
|
+
this.name = "InvalidQueryError";
|
|
8340
|
+
}
|
|
8341
|
+
};
|
|
8342
|
+
function searchQueries(query) {
|
|
8343
|
+
const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
|
|
8344
|
+
if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
|
|
8345
|
+
if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
|
|
8346
|
+
return candidates.filter((candidate) => candidate !== "");
|
|
8347
|
+
}
|
|
8348
|
+
function prefixFit(text, fits) {
|
|
8349
|
+
if (fits(text)) return text;
|
|
8350
|
+
const chars = Array.from(text);
|
|
8351
|
+
let low = 0;
|
|
8352
|
+
let high = chars.length;
|
|
8353
|
+
while (low < high) {
|
|
8354
|
+
const mid = Math.ceil((low + high) / 2);
|
|
8355
|
+
if (fits(chars.slice(0, mid).join(""))) low = mid;
|
|
8356
|
+
else high = mid - 1;
|
|
8357
|
+
}
|
|
8358
|
+
return chars.slice(0, low).join("");
|
|
8123
8359
|
}
|
|
8124
|
-
function
|
|
8125
|
-
|
|
8126
|
-
|
|
8127
|
-
|
|
8128
|
-
|
|
8129
|
-
|
|
8360
|
+
function earliestMatchOffsetChars(text, queries) {
|
|
8361
|
+
let earliest = -1;
|
|
8362
|
+
for (const query of queries) {
|
|
8363
|
+
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
8364
|
+
const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
|
|
8365
|
+
if (index < 0) continue;
|
|
8366
|
+
if (earliest < 0 || index < earliest) earliest = index;
|
|
8367
|
+
}
|
|
8368
|
+
return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
|
|
8130
8369
|
}
|
|
8131
8370
|
|
|
8132
8371
|
// src/notes/identity.ts
|
|
@@ -8152,7 +8391,7 @@ function snapshotNotesIdentity(value) {
|
|
|
8152
8391
|
}
|
|
8153
8392
|
|
|
8154
8393
|
// src/notes/constants.ts
|
|
8155
|
-
var MAX_NOTE_BYTES =
|
|
8394
|
+
var MAX_NOTE_BYTES = 512e3;
|
|
8156
8395
|
var MAX_NOTE_PATH_BYTES = 512;
|
|
8157
8396
|
|
|
8158
8397
|
// src/notes/project-namespace.ts
|
|
@@ -8406,6 +8645,11 @@ function withPathQueue(path, operation) {
|
|
|
8406
8645
|
});
|
|
8407
8646
|
return result;
|
|
8408
8647
|
}
|
|
8648
|
+
function withPathQueues(paths, operation) {
|
|
8649
|
+
const keys = [...new Set(paths.map((path) => resolve3(path)))].sort();
|
|
8650
|
+
const lock = (index) => index === keys.length ? operation() : withPathQueue(keys[index], () => lock(index + 1));
|
|
8651
|
+
return lock(0);
|
|
8652
|
+
}
|
|
8409
8653
|
function errno2(error) {
|
|
8410
8654
|
return typeof error === "object" && error !== null ? error.code : void 0;
|
|
8411
8655
|
}
|
|
@@ -8475,6 +8719,7 @@ async function namespacesForPattern(pattern, identity2, status) {
|
|
|
8475
8719
|
}
|
|
8476
8720
|
function normalizePattern(pattern, identity2) {
|
|
8477
8721
|
if (!pattern) return pattern;
|
|
8722
|
+
if (!pattern.startsWith("@") && !pattern.includes("/")) return `**/${pattern}`;
|
|
8478
8723
|
if (pattern.startsWith("@project/")) return `@projects/${identity2.projectKey}/${pattern.slice("@project/".length)}`;
|
|
8479
8724
|
if (pattern.startsWith("@self/")) return `@agents/${identity2.agent}/${pattern.slice("@self/".length)}`;
|
|
8480
8725
|
if (pattern.startsWith("@model/")) return `@models/${identity2.model}/${pattern.slice("@model/".length)}`;
|
|
@@ -8531,6 +8776,7 @@ function assertWritablePath(vpath) {
|
|
|
8531
8776
|
if (bytes > MAX_NOTE_PATH_BYTES) throw new NoteError("too_large", `Path too long: ${bytes} bytes; the limit is ${MAX_NOTE_PATH_BYTES}.`);
|
|
8532
8777
|
}
|
|
8533
8778
|
function megabytes(bytes) {
|
|
8779
|
+
if (bytes < 1e6) return `${Math.ceil(bytes / 1e3)} KB`;
|
|
8534
8780
|
return `${Math.ceil(bytes / 1e4) / 100} MB`;
|
|
8535
8781
|
}
|
|
8536
8782
|
function assertSerializedSize(content) {
|
|
@@ -8558,20 +8804,35 @@ function assertDreamNote(scope, who, identity2, raw, address) {
|
|
|
8558
8804
|
}
|
|
8559
8805
|
function createNotesStore(input) {
|
|
8560
8806
|
const identity2 = snapshotNotesIdentity(input);
|
|
8807
|
+
async function assertPinAdmission(root, path, meta, previous, source) {
|
|
8808
|
+
const livePin = (value, name) => value !== void 0 && value.crumpledAt === void 0 && effectiveNotePolicy(value, name).pinned;
|
|
8809
|
+
if (!livePin(meta, path) || livePin(previous, path)) return;
|
|
8810
|
+
if (source?.root === root && livePin(source.meta, source.path)) return;
|
|
8811
|
+
let count = 0;
|
|
8812
|
+
for (const name of await walkMarkdown(root)) {
|
|
8813
|
+
const raw = await readFileIfExists(join3(root, name));
|
|
8814
|
+
if (raw !== void 0 && livePin(parseNote(raw).meta, name)) count++;
|
|
8815
|
+
}
|
|
8816
|
+
if (count >= MAX_PINNED_NOTES) throw new NoteError("pin_limit", `This notebook already has ${count} live pinned notes; the limit is ${MAX_PINNED_NOTES}. Unpin or crumple one first. Nothing was saved.`);
|
|
8817
|
+
}
|
|
8561
8818
|
async function write(address, content, options = {}) {
|
|
8562
8819
|
const stableOptions = { ...options };
|
|
8820
|
+
validateNotePolicy(stableOptions);
|
|
8563
8821
|
const destination = assertAddress(address);
|
|
8564
8822
|
assertWritablePath(destination.path);
|
|
8565
8823
|
const scope = destination.scope;
|
|
8566
8824
|
assertWritableNamespace(scope, destination.who, identity2);
|
|
8567
8825
|
const origin = stableOptions.origin === void 0 ? void 0 : assertOrigin(stableOptions.origin);
|
|
8568
8826
|
const path = physicalPath(scope, destination.path, identity2, destination.who);
|
|
8569
|
-
|
|
8827
|
+
const root = scopeDir(scope, identity2, destination.who);
|
|
8828
|
+
return withPathQueues([root], () => withPathQueue(path, async () => {
|
|
8570
8829
|
const now = writeStamp();
|
|
8571
8830
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
8572
8831
|
const existingRaw = await readFileIfExists(path);
|
|
8573
8832
|
assertDreamNote(scope, destination.who, identity2, existingRaw, address);
|
|
8574
8833
|
const existing = existingRaw === void 0 ? void 0 : parseNote(existingRaw, now).meta;
|
|
8834
|
+
if (existing) assertNoteUnlocked(existing, stableOptions.readonly);
|
|
8835
|
+
const previous = existing === void 0 ? void 0 : { ...existing };
|
|
8575
8836
|
const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
|
|
8576
8837
|
const meta = existing ?? {
|
|
8577
8838
|
scope,
|
|
@@ -8583,14 +8844,16 @@ function createNotesStore(input) {
|
|
|
8583
8844
|
...scope === "session" ? { project: identity2.projectKey } : {}
|
|
8584
8845
|
};
|
|
8585
8846
|
meta.scope = scope;
|
|
8847
|
+
applyNotePolicy(meta, stableOptions);
|
|
8586
8848
|
if (origin !== void 0) meta.origin = origin;
|
|
8587
8849
|
delete meta.crumpledAt;
|
|
8588
8850
|
meta.updatedAt = now;
|
|
8589
8851
|
const serialized = serializeNote(meta, cleanBody);
|
|
8590
8852
|
assertSerializedSize(serialized);
|
|
8853
|
+
await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
|
|
8591
8854
|
await atomicWrite(path, serialized);
|
|
8592
|
-
return { meta, outcome };
|
|
8593
|
-
});
|
|
8855
|
+
return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
|
|
8856
|
+
}));
|
|
8594
8857
|
}
|
|
8595
8858
|
async function read(address) {
|
|
8596
8859
|
const destination = assertAddress(address);
|
|
@@ -8610,18 +8873,21 @@ function createNotesStore(input) {
|
|
|
8610
8873
|
async function update(address, edits, options = {}) {
|
|
8611
8874
|
const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
|
|
8612
8875
|
const stableOptions = { ...options };
|
|
8876
|
+
validateNotePolicy(stableOptions);
|
|
8613
8877
|
const from = assertAddress(address);
|
|
8614
8878
|
const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
|
|
8615
8879
|
assertWritablePath(destination.path);
|
|
8616
8880
|
const scope = destination.scope;
|
|
8617
8881
|
assertWritableNamespace(from.scope, from.who, identity2);
|
|
8618
8882
|
assertWritableNamespace(scope, destination.who, identity2);
|
|
8619
|
-
if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0) {
|
|
8620
|
-
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
|
|
8883
|
+
if (operations.length === 0 && stableOptions.origin === void 0 && stableOptions.crumpled === void 0 && stableOptions.renameTo === void 0 && stableOptions.pinned === void 0 && stableOptions.budget === void 0 && stableOptions.readonly === void 0) {
|
|
8884
|
+
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
|
|
8621
8885
|
}
|
|
8622
8886
|
const fromPath = physicalPath(from.scope, from.path, identity2, from.who);
|
|
8623
8887
|
const path = physicalPath(scope, destination.path, identity2, destination.who);
|
|
8624
8888
|
const differentPaths = resolve3(fromPath) !== resolve3(path);
|
|
8889
|
+
const fromRoot = scopeDir(from.scope, identity2, from.who);
|
|
8890
|
+
const root = scopeDir(scope, identity2, destination.who);
|
|
8625
8891
|
const mutate = async () => {
|
|
8626
8892
|
const raw = await readFileIfExists(fromPath);
|
|
8627
8893
|
if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
|
|
@@ -8635,7 +8901,10 @@ function createNotesStore(input) {
|
|
|
8635
8901
|
throw new NoteError("already_exists", `${noteIdentity(identity2, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
|
|
8636
8902
|
}
|
|
8637
8903
|
const { meta, body } = parseNote(raw);
|
|
8904
|
+
assertNoteUnlocked(meta, stableOptions.readonly);
|
|
8905
|
+
if (moved && targetRaw !== void 0) assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
|
|
8638
8906
|
const beforeMeta = { ...meta };
|
|
8907
|
+
applyNotePolicy(meta, stableOptions);
|
|
8639
8908
|
meta.scope = scope;
|
|
8640
8909
|
if (from.scope !== "session" && scope === "session") meta.project = identity2.projectKey;
|
|
8641
8910
|
if (from.scope === "session" && scope !== "session") delete meta.project;
|
|
@@ -8663,41 +8932,48 @@ function createNotesStore(input) {
|
|
|
8663
8932
|
if (stableOptions.crumpled === false) delete meta.crumpledAt;
|
|
8664
8933
|
const bodyChanged = body !== next;
|
|
8665
8934
|
const originChanged = beforeMeta.origin !== meta.origin;
|
|
8666
|
-
|
|
8935
|
+
const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
|
|
8936
|
+
if (bodyChanged || originChanged || policyChanged || moved) meta.updatedAt = writeStamp();
|
|
8667
8937
|
const serialized = serializeNote(meta, next);
|
|
8668
8938
|
assertSerializedSize(serialized);
|
|
8669
|
-
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
8939
|
+
const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
8670
8940
|
let change;
|
|
8671
8941
|
if (bodyChanged && (metadataChanged || moved)) change = { kind: "body", before: raw, after: serialized };
|
|
8672
8942
|
else if (bodyChanged) change = { kind: "body", before: body, after: next };
|
|
8673
8943
|
else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
|
|
8674
8944
|
else change = { kind: "none", before: "", after: "" };
|
|
8945
|
+
await assertPinAdmission(
|
|
8946
|
+
root,
|
|
8947
|
+
noteFileName(destination.path),
|
|
8948
|
+
meta,
|
|
8949
|
+
moved ? targetRaw === void 0 ? void 0 : parseNote(targetRaw).meta : beforeMeta,
|
|
8950
|
+
moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : void 0
|
|
8951
|
+
);
|
|
8675
8952
|
await atomicWrite(sameFile ? sourceReal : path, serialized);
|
|
8676
8953
|
if (moved) await rm(fromPath, { force: true });
|
|
8677
|
-
return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
|
|
8954
|
+
return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
|
|
8678
8955
|
};
|
|
8679
|
-
|
|
8680
|
-
const [first, second] = [fromPath, path].sort();
|
|
8681
|
-
return withPathQueue(first, () => withPathQueue(second, mutate));
|
|
8956
|
+
return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
|
|
8682
8957
|
}
|
|
8683
8958
|
async function rename3(fromAddress, toAddress) {
|
|
8684
|
-
const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
|
|
8685
|
-
return { meta, replacedCrumpledTarget };
|
|
8959
|
+
const { meta, warnings, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
|
|
8960
|
+
return { meta, warnings, replacedCrumpledTarget };
|
|
8686
8961
|
}
|
|
8687
8962
|
async function forget(address) {
|
|
8688
8963
|
if (identity2.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
|
|
8689
8964
|
const target = assertAddress(address);
|
|
8690
8965
|
assertWritableNamespace(target.scope, target.who, identity2);
|
|
8691
8966
|
const path = physicalPath(target.scope, target.path, identity2, target.who);
|
|
8692
|
-
return withPathQueue(path, async () => {
|
|
8967
|
+
return withPathQueues([scopeDir(target.scope, identity2, target.who)], () => withPathQueue(path, async () => {
|
|
8693
8968
|
const raw = await readFileIfExists(path);
|
|
8694
8969
|
if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
|
|
8695
8970
|
assertDreamNote(target.scope, target.who, identity2, raw, address);
|
|
8696
8971
|
const { meta } = parseNote(raw);
|
|
8972
|
+
assertNoteUnlocked(meta);
|
|
8697
8973
|
if (meta.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity2, address).address} isn't crumpled; crumple it before deleting.`);
|
|
8698
8974
|
await unlink(path);
|
|
8699
8975
|
return { ...meta, scope: target.scope };
|
|
8700
|
-
});
|
|
8976
|
+
}));
|
|
8701
8977
|
}
|
|
8702
8978
|
async function* scan(options, status) {
|
|
8703
8979
|
const glob = assertGlobPattern(options.glob);
|
|
@@ -8759,8 +9035,9 @@ function createNotesStore(input) {
|
|
|
8759
9035
|
const rows = [];
|
|
8760
9036
|
for await (const note of scan(stableOptions, status)) {
|
|
8761
9037
|
const { address, path, scope, meta, body } = note;
|
|
9038
|
+
const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
|
|
8762
9039
|
if (stableQueries.length === 0) {
|
|
8763
|
-
rows.push({ address, path, scope, meta, matches: [] });
|
|
9040
|
+
rows.push({ address, path, scope, meta, warnings, matches: [] });
|
|
8764
9041
|
continue;
|
|
8765
9042
|
}
|
|
8766
9043
|
let baseChars = 0;
|
|
@@ -8772,7 +9049,7 @@ function createNotesStore(input) {
|
|
|
8772
9049
|
}
|
|
8773
9050
|
baseChars += Array.from(line).length + 1;
|
|
8774
9051
|
}
|
|
8775
|
-
if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
|
|
9052
|
+
if (matches.length > 0) rows.push({ address, path, scope, meta, warnings, matches });
|
|
8776
9053
|
}
|
|
8777
9054
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
8778
9055
|
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
|
@@ -8789,20 +9066,8 @@ var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
|
|
|
8789
9066
|
var DEFAULT_READ_WINDOW_CHARS = 12e3;
|
|
8790
9067
|
var MAX_READ_WINDOW_CHARS = 5e4;
|
|
8791
9068
|
var HISTORY_PREVIEW_CHARS = 1200;
|
|
8792
|
-
function prefixFit(text, fits) {
|
|
8793
|
-
if (fits(text)) return text;
|
|
8794
|
-
const chars = Array.from(text);
|
|
8795
|
-
let low = 0;
|
|
8796
|
-
let high = chars.length;
|
|
8797
|
-
while (low < high) {
|
|
8798
|
-
const mid = Math.ceil((low + high) / 2);
|
|
8799
|
-
if (fits(chars.slice(0, mid).join(""))) low = mid;
|
|
8800
|
-
else high = mid - 1;
|
|
8801
|
-
}
|
|
8802
|
-
return chars.slice(0, low).join("");
|
|
8803
|
-
}
|
|
8804
9069
|
|
|
8805
|
-
// src/
|
|
9070
|
+
// src/result.ts
|
|
8806
9071
|
var OperationErrorSchema = typebox_exports.Object({
|
|
8807
9072
|
code: typebox_exports.String(),
|
|
8808
9073
|
message: typebox_exports.String()
|
|
@@ -8816,6 +9081,8 @@ function failure(code, message) {
|
|
|
8816
9081
|
const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}\u2026[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
|
|
8817
9082
|
return { ok: false, error: { code, message: bounded } };
|
|
8818
9083
|
}
|
|
9084
|
+
|
|
9085
|
+
// src/tools/result.ts
|
|
8819
9086
|
var WireErrorSchema = typebox_exports.Object({ error: typebox_exports.String(), code: typebox_exports.String() }, { additionalProperties: false });
|
|
8820
9087
|
function wireResult(result) {
|
|
8821
9088
|
if (result.ok) return result.data;
|
|
@@ -8870,190 +9137,6 @@ function renderTextWindow(window) {
|
|
|
8870
9137
|
[truncated; continue at offset_chars=${next}]`;
|
|
8871
9138
|
}
|
|
8872
9139
|
|
|
8873
|
-
// src/history/history.ts
|
|
8874
|
-
var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
|
|
8875
|
-
var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
|
|
8876
|
-
function isTextContent(part) {
|
|
8877
|
-
return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
|
|
8878
|
-
}
|
|
8879
|
-
function contentText(content) {
|
|
8880
|
-
if (typeof content === "string") return content;
|
|
8881
|
-
return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
|
|
8882
|
-
}
|
|
8883
|
-
function argumentText(execution) {
|
|
8884
|
-
return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
|
|
8885
|
-
}
|
|
8886
|
-
function nestedCallLine(call) {
|
|
8887
|
-
const parts = [`${call.id} ${call.name} [${call.status}]`];
|
|
8888
|
-
if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
|
|
8889
|
-
if (call.error !== void 0) parts.push(`error: ${call.error}`);
|
|
8890
|
-
parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
|
|
8891
|
-
return `- ${parts.join(" ")}`;
|
|
8892
|
-
}
|
|
8893
|
-
function historyDocument(event) {
|
|
8894
|
-
if (event.execution === void 0) return event.text;
|
|
8895
|
-
const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
|
|
8896
|
-
if (event.text !== "") sections.push(`--- output ---
|
|
8897
|
-
${event.text}`);
|
|
8898
|
-
const nested = event.execution.nestedCalls;
|
|
8899
|
-
if (nested !== void 0) {
|
|
8900
|
-
const header2 = nested.complete ? "complete" : "incomplete";
|
|
8901
|
-
sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
|
|
8902
|
-
${nested.calls.map(nestedCallLine).join("\n")}`);
|
|
8903
|
-
}
|
|
8904
|
-
return sections.join("\n");
|
|
8905
|
-
}
|
|
8906
|
-
var documents = /* @__PURE__ */ new WeakMap();
|
|
8907
|
-
function eventDocument(event) {
|
|
8908
|
-
const cached = documents.get(event);
|
|
8909
|
-
if (cached !== void 0) return cached;
|
|
8910
|
-
const text = historyDocument(event);
|
|
8911
|
-
documents.set(event, text);
|
|
8912
|
-
return text;
|
|
8913
|
-
}
|
|
8914
|
-
function toolEvent(item, result) {
|
|
8915
|
-
const run = result ?? item;
|
|
8916
|
-
const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
|
|
8917
|
-
const truncated = run.outputTruncated === true;
|
|
8918
|
-
return {
|
|
8919
|
-
seq: item.seq,
|
|
8920
|
-
windowId: item.windowId,
|
|
8921
|
-
role: "tool",
|
|
8922
|
-
text: result?.text ?? (item.role === "tool" ? item.text : ""),
|
|
8923
|
-
createdAt: item.createdAt,
|
|
8924
|
-
execution: {
|
|
8925
|
-
name: item.toolName ?? "unknown",
|
|
8926
|
-
status,
|
|
8927
|
-
// A call records its arguments; a bare result records none, and gets none invented.
|
|
8928
|
-
...item.arguments === void 0 ? {} : { arguments: item.arguments },
|
|
8929
|
-
...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
|
|
8930
|
-
...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
|
|
8931
|
-
}
|
|
8932
|
-
};
|
|
8933
|
-
}
|
|
8934
|
-
function projectHistory(rawWindows, highestSeq, branchSeqs) {
|
|
8935
|
-
const raw = rawWindows.flatMap((current) => current.items).sort((a, b) => a.seq - b.seq);
|
|
8936
|
-
const resultsById = /* @__PURE__ */ new Map();
|
|
8937
|
-
for (const item of raw) {
|
|
8938
|
-
if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
|
|
8939
|
-
}
|
|
8940
|
-
const pairedResults = /* @__PURE__ */ new Map();
|
|
8941
|
-
for (const item of raw) {
|
|
8942
|
-
const result = item.role === "tool_call" && item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
|
|
8943
|
-
if (result && result.seq > item.seq && !pairedResults.has(result.seq)) {
|
|
8944
|
-
pairedResults.set(result.seq, item.seq);
|
|
8945
|
-
}
|
|
8946
|
-
}
|
|
8947
|
-
const windows = rawWindows.map((current) => ({
|
|
8948
|
-
windowId: current.windowId,
|
|
8949
|
-
...current.createdAt ? { createdAt: current.createdAt } : {},
|
|
8950
|
-
items: current.items.flatMap((item) => {
|
|
8951
|
-
if (pairedResults.has(item.seq)) return [];
|
|
8952
|
-
if (item.role === "tool_call" || item.role === "tool") {
|
|
8953
|
-
const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
|
|
8954
|
-
const paired = result && pairedResults.get(result.seq) === item.seq ? result : void 0;
|
|
8955
|
-
return [toolEvent(item, paired)];
|
|
8956
|
-
}
|
|
8957
|
-
return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
|
|
8958
|
-
})
|
|
8959
|
-
}));
|
|
8960
|
-
return { windows, highestSeq, branchSeqs, pairedResults };
|
|
8961
|
-
}
|
|
8962
|
-
var NestedCallSummarySchema = typebox_exports.Object({
|
|
8963
|
-
call_count: typebox_exports.Integer({ minimum: 0 }),
|
|
8964
|
-
complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
|
|
8965
|
-
}, { additionalProperties: false });
|
|
8966
|
-
var ToolSummarySchema = typebox_exports.Object({
|
|
8967
|
-
tool: typebox_exports.Optional(typebox_exports.String()),
|
|
8968
|
-
tool_status: typebox_exports.Optional(ToolCallStatusSchema),
|
|
8969
|
-
output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
|
|
8970
|
-
full_output_path: typebox_exports.Optional(typebox_exports.String())
|
|
8971
|
-
}, { additionalProperties: false });
|
|
8972
|
-
function toolSummary(event) {
|
|
8973
|
-
const execution = event.execution;
|
|
8974
|
-
if (!execution) return {};
|
|
8975
|
-
return {
|
|
8976
|
-
tool: execution.name,
|
|
8977
|
-
tool_status: execution.status,
|
|
8978
|
-
...execution.outputTruncated ? { output_truncated: true } : {},
|
|
8979
|
-
...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
|
|
8980
|
-
};
|
|
8981
|
-
}
|
|
8982
|
-
function nestedCallSummary(event) {
|
|
8983
|
-
const nested = event.execution?.nestedCalls;
|
|
8984
|
-
return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
|
|
8985
|
-
}
|
|
8986
|
-
var HistoryFoldedRowSchema = typebox_exports.Object({
|
|
8987
|
-
session: typebox_exports.Optional(typebox_exports.String()),
|
|
8988
|
-
first_seq: typebox_exports.Integer({ minimum: 1 }),
|
|
8989
|
-
last_seq: typebox_exports.Integer({ minimum: 1 }),
|
|
8990
|
-
count: typebox_exports.Integer({ minimum: 1 }),
|
|
8991
|
-
tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
|
|
8992
|
-
}, { additionalProperties: false });
|
|
8993
|
-
var HistoryPageItemSchema = typebox_exports.Object({
|
|
8994
|
-
session: typebox_exports.Optional(typebox_exports.String()),
|
|
8995
|
-
folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
|
|
8996
|
-
seq: typebox_exports.Integer({ minimum: 1 }),
|
|
8997
|
-
role: HistoryRoleSchema,
|
|
8998
|
-
created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
|
|
8999
|
-
...ToolSummarySchema.properties,
|
|
9000
|
-
content: typebox_exports.String(),
|
|
9001
|
-
truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
|
|
9002
|
-
offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
|
|
9003
|
-
}, { additionalProperties: false });
|
|
9004
|
-
var MAX_FOLD_TOOL_NAMES = 20;
|
|
9005
|
-
var MAX_FOLD_TOOL_NAME_CHARS = 120;
|
|
9006
|
-
function visibleItem(event, maxChars, matchOffset) {
|
|
9007
|
-
const document = eventDocument(event);
|
|
9008
|
-
const chars = Array.from(document);
|
|
9009
|
-
const start = matchOffset ?? 0;
|
|
9010
|
-
const limit = Math.max(0, maxChars);
|
|
9011
|
-
const truncated = start > 0 || start + limit < chars.length;
|
|
9012
|
-
return {
|
|
9013
|
-
seq: event.seq,
|
|
9014
|
-
role: event.role,
|
|
9015
|
-
created_at: event.createdAt ?? null,
|
|
9016
|
-
...toolSummary(event),
|
|
9017
|
-
content: truncated ? chars.slice(start, start + limit).join("") : document,
|
|
9018
|
-
truncated,
|
|
9019
|
-
...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
|
|
9020
|
-
};
|
|
9021
|
-
}
|
|
9022
|
-
function allItems(projection) {
|
|
9023
|
-
return projection.windows.flatMap((current) => current.items);
|
|
9024
|
-
}
|
|
9025
|
-
function inSelection(event, params) {
|
|
9026
|
-
if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
|
|
9027
|
-
if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
|
|
9028
|
-
if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
|
|
9029
|
-
if (event.createdAt === void 0) return false;
|
|
9030
|
-
const at = Date.parse(event.createdAt);
|
|
9031
|
-
return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
|
|
9032
|
-
}
|
|
9033
|
-
function filteredItems(projection, params, conversation) {
|
|
9034
|
-
let items = allItems(projection).filter((item) => inSelection(item, params));
|
|
9035
|
-
if (params.roles) items = items.filter((item) => params.roles.includes(item.role));
|
|
9036
|
-
if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
|
|
9037
|
-
return items.sort((a, b) => a.seq - b.seq);
|
|
9038
|
-
}
|
|
9039
|
-
|
|
9040
|
-
// src/tools/schema.ts
|
|
9041
|
-
var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
|
|
9042
|
-
var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
|
|
9043
|
-
var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
|
|
9044
|
-
var InvalidQueryError = class extends Error {
|
|
9045
|
-
constructor(message) {
|
|
9046
|
-
super(message);
|
|
9047
|
-
this.name = "InvalidQueryError";
|
|
9048
|
-
}
|
|
9049
|
-
};
|
|
9050
|
-
function searchQueries(query) {
|
|
9051
|
-
const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
|
|
9052
|
-
if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
|
|
9053
|
-
if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
|
|
9054
|
-
return candidates.filter((candidate) => candidate !== "");
|
|
9055
|
-
}
|
|
9056
|
-
|
|
9057
9140
|
// src/tools/notes-context.ts
|
|
9058
9141
|
import { statSync as statSync2 } from "node:fs";
|
|
9059
9142
|
import { resolve as resolve4 } from "node:path";
|
|
@@ -9081,6 +9164,26 @@ var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("s
|
|
|
9081
9164
|
var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
|
|
9082
9165
|
description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
|
|
9083
9166
|
}));
|
|
9167
|
+
var POLICY_PARAMETERS = {
|
|
9168
|
+
pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
|
|
9169
|
+
budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 2048 for every note). Over budget warns but saves; boot does not truncate." })),
|
|
9170
|
+
readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
|
|
9171
|
+
};
|
|
9172
|
+
var PolicySchema = {
|
|
9173
|
+
pinned: typebox_exports.Boolean(),
|
|
9174
|
+
budget: typebox_exports.Integer(),
|
|
9175
|
+
readonly: typebox_exports.Boolean()
|
|
9176
|
+
};
|
|
9177
|
+
var WarningsSchema = { warnings: typebox_exports.Array(typebox_exports.String()) };
|
|
9178
|
+
function policyAt(meta, address) {
|
|
9179
|
+
return effectiveNotePolicy(meta, noteFileName(assertAddress(address).path));
|
|
9180
|
+
}
|
|
9181
|
+
function renderPolicy(policy) {
|
|
9182
|
+
return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
|
|
9183
|
+
}
|
|
9184
|
+
function withWarnings(text, data) {
|
|
9185
|
+
return [text, ...data.warnings].join("\n");
|
|
9186
|
+
}
|
|
9084
9187
|
var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
|
|
9085
9188
|
var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
|
|
9086
9189
|
var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
|
|
@@ -9094,11 +9197,12 @@ function failureOf(error) {
|
|
|
9094
9197
|
if (isFilesystemError(error)) return failure("io_error", "notes operation failed");
|
|
9095
9198
|
throw error;
|
|
9096
9199
|
}
|
|
9097
|
-
var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
|
|
9200
|
+
var NORMALIZED_META_KEYS = /* @__PURE__ */ new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly"]);
|
|
9098
9201
|
var MAX_METADATA_ENTRY_BYTES = 1024;
|
|
9099
9202
|
var MAX_METADATA_VERBATIM_BYTES = 2048;
|
|
9100
9203
|
var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
|
|
9101
9204
|
var NoteMetadataSchema = typebox_exports.Object({
|
|
9205
|
+
...PolicySchema,
|
|
9102
9206
|
origin: typebox_exports.Union([...ORIGIN_VALUES]),
|
|
9103
9207
|
created_at: typebox_exports.String(),
|
|
9104
9208
|
updated_at: typebox_exports.String(),
|
|
@@ -9106,7 +9210,7 @@ var NoteMetadataSchema = typebox_exports.Object({
|
|
|
9106
9210
|
project: typebox_exports.Optional(typebox_exports.String()),
|
|
9107
9211
|
extra: typebox_exports.Record(typebox_exports.String(), typebox_exports.Unknown())
|
|
9108
9212
|
}, { additionalProperties: false });
|
|
9109
|
-
function noteMetadata(meta) {
|
|
9213
|
+
function noteMetadata(meta, address) {
|
|
9110
9214
|
const extra = {};
|
|
9111
9215
|
let verbatimBytes = 0;
|
|
9112
9216
|
const put = (key, value) => {
|
|
@@ -9124,6 +9228,7 @@ function noteMetadata(meta) {
|
|
|
9124
9228
|
put(key, value);
|
|
9125
9229
|
}
|
|
9126
9230
|
return {
|
|
9231
|
+
...policyAt(meta, address),
|
|
9127
9232
|
origin: meta.origin,
|
|
9128
9233
|
created_at: localIso(meta.createdAt),
|
|
9129
9234
|
updated_at: localIso(meta.updatedAt),
|
|
@@ -9134,6 +9239,7 @@ function noteMetadata(meta) {
|
|
|
9134
9239
|
}
|
|
9135
9240
|
function renderMetadata(metadata) {
|
|
9136
9241
|
const fields = [
|
|
9242
|
+
renderPolicy(metadata),
|
|
9137
9243
|
`origin ${metadata.origin}`,
|
|
9138
9244
|
`created ${metadata.created_at}`,
|
|
9139
9245
|
`updated ${metadata.updated_at}`,
|
|
@@ -9162,6 +9268,8 @@ var NoteIdentitySchema = {
|
|
|
9162
9268
|
};
|
|
9163
9269
|
var ListedFileSchema = typebox_exports.Object({
|
|
9164
9270
|
...NoteIdentitySchema,
|
|
9271
|
+
...PolicySchema,
|
|
9272
|
+
...WarningsSchema,
|
|
9165
9273
|
updated_at: typebox_exports.String(),
|
|
9166
9274
|
crumpled_at: typebox_exports.Optional(typebox_exports.String())
|
|
9167
9275
|
}, { additionalProperties: false });
|
|
@@ -9180,16 +9288,21 @@ var SnapshotSchema = {
|
|
|
9180
9288
|
};
|
|
9181
9289
|
var NotesWriteDataSchema = typebox_exports.Object({
|
|
9182
9290
|
...NoteIdentitySchema,
|
|
9291
|
+
...PolicySchema,
|
|
9292
|
+
...WarningsSchema,
|
|
9183
9293
|
outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
|
|
9184
9294
|
}, { additionalProperties: false });
|
|
9185
9295
|
var NotesUpdateDataSchema = typebox_exports.Object({
|
|
9186
9296
|
...NoteIdentitySchema,
|
|
9297
|
+
...PolicySchema,
|
|
9298
|
+
...WarningsSchema,
|
|
9187
9299
|
change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
|
|
9188
9300
|
rename_from: typebox_exports.Optional(typebox_exports.String())
|
|
9189
9301
|
}, { additionalProperties: false });
|
|
9190
9302
|
var NotesReadDataSchema = typebox_exports.Object({
|
|
9191
9303
|
...NoteIdentitySchema,
|
|
9192
9304
|
metadata: NoteMetadataSchema,
|
|
9305
|
+
...WarningsSchema,
|
|
9193
9306
|
...TextWindowSchema.properties
|
|
9194
9307
|
}, { additionalProperties: false });
|
|
9195
9308
|
var NotesListDataSchema = typebox_exports.Object({
|
|
@@ -9221,11 +9334,12 @@ function snapshot(rows, limit, status, renderData, shrink) {
|
|
|
9221
9334
|
return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
|
|
9222
9335
|
}
|
|
9223
9336
|
function listedFile(row, identity2) {
|
|
9224
|
-
|
|
9337
|
+
const policy = policyAt(row.meta, row.address);
|
|
9338
|
+
return { ...noteIdentity(identity2, row.address), ...policy, warnings: row.warnings ?? (row.body === void 0 ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
|
|
9225
9339
|
}
|
|
9226
|
-
var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9340
|
+
var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9227
9341
|
function renderWriteData(data) {
|
|
9228
|
-
return `${data.outcome} ${renderIdentity(data)}
|
|
9342
|
+
return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
|
|
9229
9343
|
}
|
|
9230
9344
|
var notesWrite = {
|
|
9231
9345
|
name: "notes_write",
|
|
@@ -9237,8 +9351,8 @@ var notesWrite = {
|
|
|
9237
9351
|
async execute(params, context2) {
|
|
9238
9352
|
try {
|
|
9239
9353
|
const identity2 = notesIdentityForCall(context2, params.cwd);
|
|
9240
|
-
const { outcome } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin });
|
|
9241
|
-
return success({ ...noteIdentity(identity2, params.address), outcome });
|
|
9354
|
+
const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
|
|
9355
|
+
return success({ ...noteIdentity(identity2, params.address), outcome, ...policyAt(meta, params.address), warnings });
|
|
9242
9356
|
} catch (error) {
|
|
9243
9357
|
return failureOf(error);
|
|
9244
9358
|
}
|
|
@@ -9249,18 +9363,20 @@ var notesUpdateParameters = typebox_exports.Object({
|
|
|
9249
9363
|
address: typebox_exports.String(),
|
|
9250
9364
|
edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
|
|
9251
9365
|
origin: ORIGIN,
|
|
9366
|
+
...POLICY_PARAMETERS,
|
|
9252
9367
|
crumpled: CRUMPLED_PARAMETER,
|
|
9253
9368
|
replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
|
|
9254
9369
|
rename_to: typebox_exports.Optional(typebox_exports.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." })),
|
|
9255
9370
|
cwd: CWD_PARAMETER
|
|
9256
9371
|
}, { additionalProperties: false });
|
|
9257
9372
|
function renderUpdateData(data) {
|
|
9258
|
-
|
|
9373
|
+
const receipt = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
|
|
9374
|
+
return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
|
|
9259
9375
|
}
|
|
9260
9376
|
var notesUpdate = {
|
|
9261
9377
|
name: "notes_update",
|
|
9262
9378
|
label: "Notes update",
|
|
9263
|
-
description: `Change part of a note's body,
|
|
9379
|
+
description: `Change part of a note's body, policy (pinned/budget/readonly), origin, crumpled state, or address. A readonly note requires explicit readonly:false before any change, or in the same call. When things change, replace the stale part in place; don't just tack an update onto the bottom. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
|
|
9264
9380
|
parameters: notesUpdateParameters,
|
|
9265
9381
|
outputSchema: resultSchema(NotesUpdateDataSchema),
|
|
9266
9382
|
executionMode: "sequential",
|
|
@@ -9269,11 +9385,11 @@ var notesUpdate = {
|
|
|
9269
9385
|
const identity2 = notesIdentityForCall(context2, params.cwd);
|
|
9270
9386
|
const store = createNotesStore(identity2);
|
|
9271
9387
|
const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
|
|
9272
|
-
const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
|
|
9388
|
+
const { change, moved, meta, warnings } = await store.update(params.address, params.edits, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
|
|
9273
9389
|
onChange?.(change);
|
|
9274
9390
|
const from = noteIdentity(identity2, params.address).address;
|
|
9275
9391
|
const to = noteIdentity(identity2, renameTo ?? params.address);
|
|
9276
|
-
return success({ ...to, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
|
|
9392
|
+
return success({ ...to, ...policyAt(meta, to.address), warnings, ...moved ? { rename_from: from } : {}, change_kind: moved ? "moved" : change.kind });
|
|
9277
9393
|
} catch (error) {
|
|
9278
9394
|
return failureOf(error);
|
|
9279
9395
|
}
|
|
@@ -9282,8 +9398,8 @@ var notesUpdate = {
|
|
|
9282
9398
|
};
|
|
9283
9399
|
var notesReadParameters = typebox_exports.Object({ address: typebox_exports.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
|
|
9284
9400
|
function renderReadData(data) {
|
|
9285
|
-
return `${renderIdentity(data)}
|
|
9286
|
-
${renderMetadata(data.metadata)}
|
|
9401
|
+
return withWarnings(`${renderIdentity(data)}
|
|
9402
|
+
${renderMetadata(data.metadata)}`, data) + `
|
|
9287
9403
|
|
|
9288
9404
|
${renderTextWindow(data)}`;
|
|
9289
9405
|
}
|
|
@@ -9301,8 +9417,9 @@ var notesRead = {
|
|
|
9301
9417
|
if (!note) return failure("not_found", `No note at ${resolved.address}.`);
|
|
9302
9418
|
const totalChars = Array.from(note.body).length;
|
|
9303
9419
|
if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
|
|
9304
|
-
const metadata = noteMetadata(note.meta);
|
|
9305
|
-
|
|
9420
|
+
const metadata = noteMetadata(note.meta, resolved.address);
|
|
9421
|
+
const warnings = noteBudgetWarnings(note.body, metadata);
|
|
9422
|
+
return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
|
|
9306
9423
|
} catch (error) {
|
|
9307
9424
|
return failureOf(error);
|
|
9308
9425
|
}
|
|
@@ -9313,7 +9430,8 @@ var notesListParameters = typebox_exports.Object({ glob: GLOB_PARAMETER, limit:
|
|
|
9313
9430
|
function renderListData(data) {
|
|
9314
9431
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
9315
9432
|
for (const file of data.files) {
|
|
9316
|
-
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.last_accessed === void 0 ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
|
|
9433
|
+
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at}${file.last_accessed === void 0 ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === void 0 ? "" : ` | crumpled ${file.crumpled_at}`}`);
|
|
9434
|
+
lines.push(...file.warnings.map((warning) => ` ${warning}`));
|
|
9317
9435
|
}
|
|
9318
9436
|
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
9319
9437
|
for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
|
|
@@ -9340,7 +9458,8 @@ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Opti
|
|
|
9340
9458
|
function renderSearchData(data) {
|
|
9341
9459
|
const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
|
|
9342
9460
|
for (const file of data.files) {
|
|
9343
|
-
lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
9461
|
+
lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
|
|
9462
|
+
lines.push(...file.warnings.map((warning) => ` ${warning}`));
|
|
9344
9463
|
for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
|
|
9345
9464
|
}
|
|
9346
9465
|
if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
|
|
@@ -9446,7 +9565,7 @@ function prepareSelection(projection, params) {
|
|
|
9446
9565
|
const folds = !params.roles && params.query === void 0;
|
|
9447
9566
|
const candidates = [];
|
|
9448
9567
|
let run = [];
|
|
9449
|
-
for (const event of filteredItems(projection, params
|
|
9568
|
+
for (const event of filteredItems(projection, params)) {
|
|
9450
9569
|
if (folds && (event.role === "tool" || event.role === "context")) {
|
|
9451
9570
|
run.push(event);
|
|
9452
9571
|
continue;
|
|
@@ -9496,7 +9615,7 @@ function corpusSelection(params) {
|
|
|
9496
9615
|
return resolveSelection(params);
|
|
9497
9616
|
}
|
|
9498
9617
|
function sessionRepresentative(projection, scoped) {
|
|
9499
|
-
const events = filteredItems(projection, scoped
|
|
9618
|
+
const events = filteredItems(projection, scoped).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
|
|
9500
9619
|
if (scoped.roles) return events.at(-1);
|
|
9501
9620
|
return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
|
|
9502
9621
|
}
|
|
@@ -9540,7 +9659,7 @@ var CorpusCollector = class {
|
|
|
9540
9659
|
/** Returns whether this session contributes an overview representative. */
|
|
9541
9660
|
add(session, projection) {
|
|
9542
9661
|
if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
|
|
9543
|
-
for (const event of filteredItems(projection, this.scoped
|
|
9662
|
+
for (const event of filteredItems(projection, this.scoped)) {
|
|
9544
9663
|
const document = eventDocument(event);
|
|
9545
9664
|
if ((event.role === "user" || event.role === "assistant") && document === "") continue;
|
|
9546
9665
|
const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
|
|
@@ -9576,10 +9695,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
|
|
|
9576
9695
|
break;
|
|
9577
9696
|
}
|
|
9578
9697
|
const page = pageData(prepared, start, end, maxChars);
|
|
9579
|
-
if (!fits(page)) {
|
|
9580
|
-
const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
|
|
9581
|
-
return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
9582
|
-
}
|
|
9698
|
+
if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
|
|
9583
9699
|
return success(page);
|
|
9584
9700
|
}
|
|
9585
9701
|
|
|
@@ -9707,6 +9823,12 @@ function renderRead(data) {
|
|
|
9707
9823
|
return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
9708
9824
|
}
|
|
9709
9825
|
var plainText = (text) => text;
|
|
9826
|
+
function pageOutcome(result) {
|
|
9827
|
+
if (!("pageTooLarge" in result)) return result;
|
|
9828
|
+
const { count, multi } = result.pageTooLarge;
|
|
9829
|
+
const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
|
|
9830
|
+
return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
9831
|
+
}
|
|
9710
9832
|
var sessionParameter = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
|
|
9711
9833
|
var historyListParameters = typebox_exports.Object({
|
|
9712
9834
|
session: sessionParameter,
|
|
@@ -9729,7 +9851,7 @@ var historyList = {
|
|
|
9729
9851
|
async execute(params, context2, wrapText = plainText) {
|
|
9730
9852
|
const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
|
|
9731
9853
|
const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
|
|
9732
|
-
if (params.session === void 0) return selectPage(await currentHistory(context2), params, fits, maxChars);
|
|
9854
|
+
if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), params, fits, maxChars));
|
|
9733
9855
|
const selector = parseSessionSelector(params.session);
|
|
9734
9856
|
if (!selector.ok) return selector;
|
|
9735
9857
|
const corpus = "corpus" in context2 ? context2.corpus : void 0;
|
|
@@ -9758,7 +9880,7 @@ var historyList = {
|
|
|
9758
9880
|
}
|
|
9759
9881
|
}
|
|
9760
9882
|
const notice2 = notices.length ? { notice: notices.join("") } : {};
|
|
9761
|
-
const result2 = collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited);
|
|
9883
|
+
const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
|
|
9762
9884
|
return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
|
|
9763
9885
|
}
|
|
9764
9886
|
const target = await resolveSession(corpus, selector.data);
|
|
@@ -9766,7 +9888,7 @@ var historyList = {
|
|
|
9766
9888
|
const loaded = await loadHistorySession(target.data);
|
|
9767
9889
|
if (!loaded.ok) return loaded;
|
|
9768
9890
|
const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
|
|
9769
|
-
const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
|
|
9891
|
+
const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
|
|
9770
9892
|
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
9771
9893
|
},
|
|
9772
9894
|
render: (result) => renderOutcome(result, renderPage)
|
|
@@ -11060,8 +11182,6 @@ async function loadNotesSnapshot(identity2, openedAt, loadNamespace) {
|
|
|
11060
11182
|
|
|
11061
11183
|
// src/boot/text.ts
|
|
11062
11184
|
var SHELF_FRESH_LIMIT = 3;
|
|
11063
|
-
var CHEATSHEET_BOOT_MAX_CHARS = 1536;
|
|
11064
|
-
var MAP_BOOT_MAX_CHARS = 4096;
|
|
11065
11185
|
var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
|
|
11066
11186
|
var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
|
|
11067
11187
|
var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
|
|
@@ -11104,9 +11224,15 @@ Still a tie? *shrugs* You've got a brain. Use it.
|
|
|
11104
11224
|
Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
|
|
11105
11225
|
${NOTES_PROTOCOL_CLOSE_TAG}`;
|
|
11106
11226
|
var MAPS_BLOCK = `<notesoup:maps>
|
|
11107
|
-
Every notebook's root
|
|
11108
|
-
|
|
11109
|
-
|
|
11227
|
+
Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
|
|
11228
|
+
Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
|
|
11229
|
+
reads them, and next is you. So keep them short, and keep them true.
|
|
11230
|
+
|
|
11231
|
+
Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
|
|
11232
|
+
live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
|
|
11233
|
+
starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
|
|
11234
|
+
and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
|
|
11235
|
+
explicitly set \`readonly:false\` to unlock, on its own or with your changes.
|
|
11110
11236
|
|
|
11111
11237
|
- **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
|
|
11112
11238
|
a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
|
|
@@ -11178,20 +11304,22 @@ function notesIndex(snapshot2, tools, agentName, modelName) {
|
|
|
11178
11304
|
continue;
|
|
11179
11305
|
}
|
|
11180
11306
|
const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
|
|
11181
|
-
const
|
|
11182
|
-
|
|
11183
|
-
|
|
11184
|
-
});
|
|
11185
|
-
const fresh = rows.filter((row) => row.path !== "MAP.md" && row.path !== "CHEATSHEET.md").slice(0, SHELF_FRESH_LIMIT).map((row) => {
|
|
11307
|
+
const pins = rows.filter((row) => effectiveNotePolicy(row.meta, row.path).pinned).sort((a, b) => pinnedPageOrder(a.path) - pinnedPageOrder(b.path) || a.path.localeCompare(b.path));
|
|
11308
|
+
const pinned = pins.slice(0, MAX_PINNED_NOTES);
|
|
11309
|
+
const fresh = rows.filter((row) => !effectiveNotePolicy(row.meta, row.path).pinned).slice(0, SHELF_FRESH_LIMIT).map((row) => {
|
|
11186
11310
|
const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, snapshot2.openedAt)}`;
|
|
11187
11311
|
const title = feedTitle(row.body);
|
|
11188
11312
|
return title === void 0 ? ` ${locator}` : ` ${title}
|
|
11189
11313
|
${locator}`;
|
|
11190
11314
|
});
|
|
11191
11315
|
if (pinned.length === 0 && fresh.length === 0) continue;
|
|
11192
|
-
const parts = pinned.map((row) =>
|
|
11316
|
+
const parts = pinned.map((row) => {
|
|
11317
|
+
const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
|
|
11318
|
+
return `${row.address}
|
|
11193
11319
|
|
|
11194
|
-
${indent(
|
|
11320
|
+
${indent([...warnings, row.body].join("\n"))}`;
|
|
11321
|
+
});
|
|
11322
|
+
if (pins.length > MAX_PINNED_NOTES) parts.push(indent(`Warning: only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`));
|
|
11195
11323
|
if (fresh.length > 0) parts.push(`recent
|
|
11196
11324
|
|
|
11197
11325
|
${fresh.join("\n\n")}`);
|
|
@@ -11199,13 +11327,7 @@ ${fresh.join("\n\n")}`);
|
|
|
11199
11327
|
}
|
|
11200
11328
|
return shelves.length > 0 ? ["YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500", ...shelves].join("\n\n\n") : "YOUR NOTES\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nNone yet. A blank slate is a fine place to start \u2014 just don't finish there.";
|
|
11201
11329
|
}
|
|
11202
|
-
function
|
|
11203
|
-
const chars = Array.from(body);
|
|
11204
|
-
if (chars.length <= maxChars) return body;
|
|
11205
|
-
return `${chars.slice(0, maxChars).join("")}
|
|
11206
|
-
[truncated at ${maxChars} chars; slim this page down, full body at \`${address}\`]`;
|
|
11207
|
-
}
|
|
11208
|
-
function renderBootBlock(data) {
|
|
11330
|
+
function renderIdentity2(data) {
|
|
11209
11331
|
const shown2 = /* @__PURE__ */ new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
|
|
11210
11332
|
const windows = data.tree.windows.filter((_window, index) => shown2.has(index));
|
|
11211
11333
|
const width = Math.max(8, ...windows.map((window) => window.shortName.length));
|
|
@@ -11219,10 +11341,12 @@ function renderBootBlock(data) {
|
|
|
11219
11341
|
return `${window.isCurrent ? "\u2514\u2500" : "\u251C\u2500"} ${name}${range}${window.isCurrent ? " \u2190 you are here" : ""}`;
|
|
11220
11342
|
})
|
|
11221
11343
|
];
|
|
11222
|
-
|
|
11344
|
+
return `${WINDOW_IDENTITY_OPEN_TAG}
|
|
11223
11345
|
${lines.join("\n")}
|
|
11224
11346
|
${WINDOW_IDENTITY_CLOSE_TAG}`;
|
|
11225
|
-
|
|
11347
|
+
}
|
|
11348
|
+
function renderBootBlock(data) {
|
|
11349
|
+
return [renderIdentity2(data), renderProtocolBlock(data.tools, data.agentName), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
|
|
11226
11350
|
}
|
|
11227
11351
|
|
|
11228
11352
|
// src/budget/text.ts
|
|
@@ -11247,7 +11371,7 @@ function selectContinuation(origin) {
|
|
|
11247
11371
|
return pool[Math.floor(Math.random() * pool.length)];
|
|
11248
11372
|
}
|
|
11249
11373
|
var WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
|
|
11250
|
-
var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim CHEATSHEET.md and MAP.md; every new window loads
|
|
11374
|
+
var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md and MAP.md by default); every new window loads the pins. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
|
|
11251
11375
|
var WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
|
|
11252
11376
|
function warningPrompt() {
|
|
11253
11377
|
return `${WARNING_TIMING}
|
|
@@ -11332,21 +11456,10 @@ function settingFlag(settings2) {
|
|
|
11332
11456
|
return isPlainObject(settings2) && typeof settings2.autoCompactEnabled === "boolean" ? settings2.autoCompactEnabled : void 0;
|
|
11333
11457
|
}
|
|
11334
11458
|
function configuredWindow(settings2, env, model) {
|
|
11335
|
-
const
|
|
11336
|
-
const
|
|
11337
|
-
|
|
11338
|
-
|
|
11339
|
-
const modelSettings = isPlainObject(settings2.modelSettings) ? settings2.modelSettings : {};
|
|
11340
|
-
const perModel = modelSettings[model];
|
|
11341
|
-
if (isPlainObject(perModel)) {
|
|
11342
|
-
const value = positiveNumber(perModel.autoCompactWindow);
|
|
11343
|
-
if (value !== void 0) windows.push(value);
|
|
11344
|
-
}
|
|
11345
|
-
}
|
|
11346
|
-
if (isPlainObject(settings2)) {
|
|
11347
|
-
const value = positiveNumber(settings2.autoCompactWindow);
|
|
11348
|
-
if (value !== void 0) windows.push(value);
|
|
11349
|
-
}
|
|
11459
|
+
const root = isPlainObject(settings2) ? settings2 : {};
|
|
11460
|
+
const models = isPlainObject(root.modelSettings) ? root.modelSettings : {};
|
|
11461
|
+
const perModel = typeof model === "string" && model.length > 0 ? models[model] : void 0;
|
|
11462
|
+
const windows = [env.autoCompactWindow, isPlainObject(perModel) ? perModel.autoCompactWindow : void 0, root.autoCompactWindow].map(positiveNumber).filter((value) => value !== void 0);
|
|
11350
11463
|
return windows.length === 0 ? void 0 : Math.min(...windows);
|
|
11351
11464
|
}
|
|
11352
11465
|
function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
@@ -11413,13 +11526,6 @@ function identity(input) {
|
|
|
11413
11526
|
if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
|
|
11414
11527
|
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd, input.home), agent: input.agent, model: input.model });
|
|
11415
11528
|
}
|
|
11416
|
-
function paramProblem(schema, params) {
|
|
11417
|
-
const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
|
|
11418
|
-
if (!first) return "unrecognized shape";
|
|
11419
|
-
const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
|
|
11420
|
-
const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
|
|
11421
|
-
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
11422
|
-
}
|
|
11423
11529
|
function boundOperation(operation) {
|
|
11424
11530
|
return {
|
|
11425
11531
|
description: operation.description,
|