notesoup 0.0.0-stage → 0.39.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/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +21 -0
- package/dist/src/boot/text.js +52 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +151 -0
- package/dist/src/history/history.js +195 -0
- package/dist/src/history/query.d.ts +75 -0
- package/dist/src/history/query.js +143 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +104 -0
- package/dist/src/notes/store.js +478 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +10 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +11 -0
- package/dist/src/pi/tool-names.js +11 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +67 -0
- package/dist/src/tools/history.js +251 -0
- package/dist/src/tools/notes.d.ts +282 -0
- package/dist/src/tools/notes.js +378 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +79 -0
- package/dist/src/tools/result.js +130 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +368 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +556 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +300 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +497 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +528 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +88 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9324 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +241 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +66 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +270 -0
- package/src/history/query.ts +147 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +497 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +12 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +13 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +273 -0
- package/src/tools/notes.ts +394 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +169 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/** Recorded details live once, in the pageable event document; tools expose a small summary. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
|
|
4
|
+
/** The four public roles a history event carries on the wire, in presentation order. */
|
|
5
|
+
export const HistoryRoleSchema = Type.Union([Type.Literal("user"), Type.Literal("assistant"), Type.Literal("tool"), Type.Literal("context")]);
|
|
6
|
+
export type HistoryRole = Static<typeof HistoryRoleSchema>;
|
|
7
|
+
|
|
8
|
+
/** How a recorded tool run ended. A call with no recorded result has not ended. */
|
|
9
|
+
export const ToolCallStatusSchema = Type.Union([Type.Literal("ok"), Type.Literal("error"), Type.Literal("unfinished")]);
|
|
10
|
+
export type ToolCallStatus = Static<typeof ToolCallStatusSchema>;
|
|
11
|
+
|
|
12
|
+
/** Internal recorded facts, not a second copy in the public read schema. */
|
|
13
|
+
export type NestedCallRecord = {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
arguments?: Record<string, unknown>;
|
|
17
|
+
argumentsBytes?: number;
|
|
18
|
+
status: ToolCallStatus;
|
|
19
|
+
durationMs?: number;
|
|
20
|
+
error?: string;
|
|
21
|
+
};
|
|
22
|
+
export type RecordedNestedCalls = { calls: NestedCallRecord[]; complete: boolean };
|
|
23
|
+
export type ToolExecutionFacts = {
|
|
24
|
+
name: string;
|
|
25
|
+
status: ToolCallStatus;
|
|
26
|
+
arguments?: Record<string, unknown>;
|
|
27
|
+
outputTruncated?: boolean;
|
|
28
|
+
fullOutputPath?: string;
|
|
29
|
+
nestedCalls?: RecordedNestedCalls;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** One projection event: its facts, and the document they render to. */
|
|
33
|
+
export type HistoryEvent = {
|
|
34
|
+
seq: number;
|
|
35
|
+
windowId: string;
|
|
36
|
+
role: HistoryRole;
|
|
37
|
+
createdAt: string | undefined;
|
|
38
|
+
/** Message body for user/assistant/context; the run's output for a tool event. */
|
|
39
|
+
text: string;
|
|
40
|
+
/** Whole recorded facts, rendered by eventDocument. */
|
|
41
|
+
execution?: ToolExecutionFacts;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export type HistoryWindow = { windowId: string; createdAt?: string; items: HistoryEvent[] };
|
|
45
|
+
|
|
46
|
+
/** Paired result seqs stay on the branch but redirect readers to the call's event. */
|
|
47
|
+
export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
|
|
48
|
+
export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null };
|
|
49
|
+
|
|
50
|
+
/** Native entries after the adapter allocates seqs and selects the active branch. */
|
|
51
|
+
export type DecodedHistoryItem = {
|
|
52
|
+
seq: number;
|
|
53
|
+
windowId: string;
|
|
54
|
+
role: "user" | "assistant" | "tool_call" | "tool" | "system" | "developer";
|
|
55
|
+
/** Message body; for a tool call or result, the arguments or output text respectively. */
|
|
56
|
+
text: string;
|
|
57
|
+
createdAt?: string;
|
|
58
|
+
toolName?: string;
|
|
59
|
+
/** Internal pairing key; never serialized. */
|
|
60
|
+
toolCallId?: string;
|
|
61
|
+
/** The recorded arguments object, exactly as the host stored it. */
|
|
62
|
+
arguments?: Record<string, unknown>;
|
|
63
|
+
outputTruncated?: boolean;
|
|
64
|
+
fullOutputPath?: string;
|
|
65
|
+
/** The run reported an error. */
|
|
66
|
+
toolError?: boolean;
|
|
67
|
+
/** Native outcome for a standalone run (e.g. bash exit status). */
|
|
68
|
+
recordedStatus?: ToolCallStatus;
|
|
69
|
+
/** toolResult only: the calls this run made to other tools. */
|
|
70
|
+
nestedCalls?: RecordedNestedCalls;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export type DecodedHistoryWindow = { windowId: string; createdAt?: string; items: DecodedHistoryItem[] };
|
|
74
|
+
|
|
75
|
+
function isTextContent(part: unknown): part is { type: "text"; text: string } {
|
|
76
|
+
return typeof part === "object" && part !== null && (part as { type: "text"; text: string }).type === "text" && typeof (part as { type: "text"; text: string }).text === "string";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function contentText(content: unknown): string {
|
|
80
|
+
if (typeof content === "string") return content;
|
|
81
|
+
return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function argumentText(execution: ToolExecutionFacts): string {
|
|
85
|
+
return execution.arguments === undefined ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function nestedCallLine(call: NestedCallRecord): string {
|
|
89
|
+
const parts = [`${call.id} ${call.name} [${call.status}]`];
|
|
90
|
+
if (call.durationMs !== undefined) parts.push(`${call.durationMs}ms`);
|
|
91
|
+
if (call.error !== undefined) parts.push(`error: ${call.error}`);
|
|
92
|
+
parts.push(call.arguments === undefined ? (call.argumentsBytes === undefined ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)`) : JSON.stringify(call.arguments));
|
|
93
|
+
return `- ${parts.join(" ")}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Canonical searchable/readable text, without UI headers or continuation footers. */
|
|
97
|
+
export function historyDocument(event: HistoryEvent): string {
|
|
98
|
+
if (event.execution === undefined) return event.text;
|
|
99
|
+
const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
|
|
100
|
+
// An unfinished call has no recorded output at all, and saying so by omission is truthful.
|
|
101
|
+
if (event.text !== "") sections.push(`--- output ---\n${event.text}`);
|
|
102
|
+
const nested = event.execution.nestedCalls;
|
|
103
|
+
if (nested !== undefined) {
|
|
104
|
+
const header = nested.complete ? "complete" : "incomplete";
|
|
105
|
+
sections.push(`--- nested calls (${header}, ${nested.calls.length} recorded) ---\n${nested.calls.map(nestedCallLine).join("\n")}`);
|
|
106
|
+
}
|
|
107
|
+
return sections.join("\n");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const documents = new WeakMap<HistoryEvent, string>();
|
|
111
|
+
|
|
112
|
+
/** Memoized `historyDocument`: search, preview, and read must agree on the same characters. */
|
|
113
|
+
export function eventDocument(event: HistoryEvent): string {
|
|
114
|
+
const cached = documents.get(event);
|
|
115
|
+
if (cached !== undefined) return cached;
|
|
116
|
+
const text = historyDocument(event);
|
|
117
|
+
documents.set(event, text);
|
|
118
|
+
return text;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Pair a call with its result, or preserve a standalone run's recorded outcome. */
|
|
122
|
+
function toolEvent(item: DecodedHistoryItem, result?: DecodedHistoryItem): HistoryEvent {
|
|
123
|
+
const run = result ?? item;
|
|
124
|
+
// Only a call without a result is unfinished; standalone results carry their own outcome.
|
|
125
|
+
const status: ToolCallStatus = item.role === "tool_call" && result === undefined
|
|
126
|
+
? "unfinished"
|
|
127
|
+
: run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
|
|
128
|
+
const truncated = run.outputTruncated === true;
|
|
129
|
+
return {
|
|
130
|
+
seq: item.seq,
|
|
131
|
+
windowId: item.windowId,
|
|
132
|
+
role: "tool",
|
|
133
|
+
text: result?.text ?? (item.role === "tool" ? item.text : ""),
|
|
134
|
+
createdAt: item.createdAt,
|
|
135
|
+
execution: {
|
|
136
|
+
name: item.toolName ?? "unknown",
|
|
137
|
+
status,
|
|
138
|
+
// A call records its arguments; a bare result records none, and gets none invented.
|
|
139
|
+
...(item.arguments === undefined ? {} : { arguments: item.arguments }),
|
|
140
|
+
...(truncated ? { outputTruncated: true, ...(run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {}) } : {}),
|
|
141
|
+
...(run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}),
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Pair results into call events; consumed result seqs are not alternate read addresses. */
|
|
147
|
+
export function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: number, branchSeqs: Set<number>): HistoryProjection {
|
|
148
|
+
const raw = rawWindows.flatMap((current) => current.items);
|
|
149
|
+
const resultsById = new Map<string, DecodedHistoryItem>();
|
|
150
|
+
for (const item of raw) {
|
|
151
|
+
if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
|
|
152
|
+
}
|
|
153
|
+
const pairedResults = new Map<number, number>();
|
|
154
|
+
const consumed = new Set<number>();
|
|
155
|
+
const windows: HistoryWindow[] = rawWindows.map((current) => ({
|
|
156
|
+
windowId: current.windowId,
|
|
157
|
+
...(current.createdAt ? { createdAt: current.createdAt } : {}),
|
|
158
|
+
items: current.items.flatMap((item): HistoryEvent[] => {
|
|
159
|
+
if (consumed.has(item.seq)) return [];
|
|
160
|
+
if (item.role === "tool_call") {
|
|
161
|
+
const result = item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
|
|
162
|
+
const paired = result && result.seq > item.seq && !consumed.has(result.seq) ? result : undefined;
|
|
163
|
+
if (paired) {
|
|
164
|
+
consumed.add(paired.seq);
|
|
165
|
+
pairedResults.set(paired.seq, item.seq);
|
|
166
|
+
}
|
|
167
|
+
return [toolEvent(item, paired)];
|
|
168
|
+
}
|
|
169
|
+
if (item.role === "tool") return [toolEvent(item)];
|
|
170
|
+
return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
|
|
171
|
+
}),
|
|
172
|
+
}));
|
|
173
|
+
return { windows, highestSeq, branchSeqs, pairedResults };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Summary shared by list, search and read. Full arguments/calls are in the document. */
|
|
177
|
+
export const NestedCallSummarySchema = Type.Object({
|
|
178
|
+
call_count: Type.Integer({ minimum: 0 }),
|
|
179
|
+
complete: Type.Boolean({ description: "Whether the host recorded all nested calls." }),
|
|
180
|
+
}, { additionalProperties: false });
|
|
181
|
+
|
|
182
|
+
export const ToolSummarySchema = Type.Object({
|
|
183
|
+
tool: Type.Optional(Type.String()),
|
|
184
|
+
tool_status: Type.Optional(ToolCallStatusSchema),
|
|
185
|
+
output_truncated: Type.Optional(Type.Boolean()),
|
|
186
|
+
full_output_path: Type.Optional(Type.String()),
|
|
187
|
+
nested_calls: Type.Optional(NestedCallSummarySchema),
|
|
188
|
+
}, { additionalProperties: false });
|
|
189
|
+
|
|
190
|
+
export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema> {
|
|
191
|
+
const execution = event.execution;
|
|
192
|
+
if (!execution) return {};
|
|
193
|
+
return {
|
|
194
|
+
tool: execution.name,
|
|
195
|
+
tool_status: execution.status,
|
|
196
|
+
...(execution.outputTruncated ? { output_truncated: true } : {}),
|
|
197
|
+
...(execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}),
|
|
198
|
+
...(execution.nestedCalls ? { nested_calls: { call_count: execution.nestedCalls.calls.length, complete: execution.nestedCalls.complete } } : {}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Stable identity and a verbatim preview, starting at the search match when present. */
|
|
203
|
+
export const HistoryPageItemSchema = Type.Object({
|
|
204
|
+
seq: Type.Integer({ minimum: 1 }),
|
|
205
|
+
window_id: Type.String(),
|
|
206
|
+
role: HistoryRoleSchema,
|
|
207
|
+
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
208
|
+
...ToolSummarySchema.properties,
|
|
209
|
+
tool_name_omitted: Type.Optional(Type.Boolean({ description: "Name omitted to fit; read this seq." })),
|
|
210
|
+
truncated: Type.Boolean({ description: "Preview is partial; read this seq for more." }),
|
|
211
|
+
total_chars: Type.Integer({ minimum: 0 }),
|
|
212
|
+
content: Type.String(),
|
|
213
|
+
offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Search match/preview start, in code points." })),
|
|
214
|
+
}, { additionalProperties: false });
|
|
215
|
+
export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
|
|
216
|
+
|
|
217
|
+
/** A run of tool/context events the conversation view replaces with counts. */
|
|
218
|
+
export const HistoryFoldedRowSchema = Type.Object({
|
|
219
|
+
folded: Type.Literal(true),
|
|
220
|
+
first_seq: Type.Integer({ minimum: 1 }),
|
|
221
|
+
last_seq: Type.Integer({ minimum: 1 }),
|
|
222
|
+
count: Type.Integer({ minimum: 1 }),
|
|
223
|
+
tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Counts by tool name." }),
|
|
224
|
+
omitted_tools: Type.Optional(Type.Integer({ minimum: 1, description: "Number of omitted tool names." })),
|
|
225
|
+
}, { additionalProperties: false });
|
|
226
|
+
export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
|
|
227
|
+
|
|
228
|
+
/** Bound fold summaries while preserving exact counts in count/omitted_tools. */
|
|
229
|
+
export const MAX_FOLD_TOOL_NAMES = 20;
|
|
230
|
+
|
|
231
|
+
/** Longest tool name a fold row lists; longer names are counted in `omitted_tools` instead. */
|
|
232
|
+
export const MAX_FOLD_TOOL_NAME_CHARS = 120;
|
|
233
|
+
|
|
234
|
+
/** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
|
|
235
|
+
export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem {
|
|
236
|
+
const document = eventDocument(event);
|
|
237
|
+
const chars = Array.from(document);
|
|
238
|
+
const start = matchOffset ?? 0;
|
|
239
|
+
const truncated = start > 0 || start + maxChars < chars.length;
|
|
240
|
+
return {
|
|
241
|
+
seq: event.seq,
|
|
242
|
+
window_id: event.windowId,
|
|
243
|
+
role: event.role,
|
|
244
|
+
created_at: event.createdAt ?? null,
|
|
245
|
+
...toolSummary(event),
|
|
246
|
+
truncated,
|
|
247
|
+
total_chars: chars.length,
|
|
248
|
+
content: truncated ? chars.slice(start, start + maxChars).join("") : document,
|
|
249
|
+
...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function allItems(projection: HistoryProjection): HistoryEvent[] {
|
|
254
|
+
return projection.windows.flatMap((current) => current.items);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
|
|
258
|
+
if (typeof params.window_id !== "string") return undefined;
|
|
259
|
+
const known = projection.windows.map((current) => current.windowId);
|
|
260
|
+
return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Default list is a conversation; explicit roles and search show the requested events. */
|
|
264
|
+
export function filteredItems(projection: HistoryProjection, params: HistoryFilter, mode: "list" | "search"): HistoryEvent[] {
|
|
265
|
+
let items = allItems(projection);
|
|
266
|
+
if (typeof params.window_id === "string") items = items.filter((item) => item.windowId === params.window_id);
|
|
267
|
+
if (params.roles) items = items.filter((item) => params.roles!.includes(item.role));
|
|
268
|
+
if (!params.roles && mode === "list") items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
|
|
269
|
+
return items.sort((a, b) => a.seq - b.seq);
|
|
270
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Stable-anchor paging and folding. The operation supplies the full-response budget check. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
import { failure, success, type Outcome } from "../tools/result.js";
|
|
4
|
+
import { prefixFit } from "../tools/output.js";
|
|
5
|
+
import { allItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
|
|
6
|
+
|
|
7
|
+
type PageRow = HistoryPageItem | HistoryFoldedRow;
|
|
8
|
+
type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem };
|
|
9
|
+
type AnchorParams = { before?: number; after?: number; limit?: number; max_chars_per_item?: number };
|
|
10
|
+
|
|
11
|
+
export const HistoryPageSchema = Type.Object({
|
|
12
|
+
items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
|
|
13
|
+
older_before: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as before to page older." }),
|
|
14
|
+
newer_after: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as after to page newer." }),
|
|
15
|
+
}, { additionalProperties: false });
|
|
16
|
+
/** Search never returns conversation folds. */
|
|
17
|
+
export const HistorySearchPageSchema = Type.Object({
|
|
18
|
+
...HistoryPageSchema.properties,
|
|
19
|
+
items: Type.Array(HistoryPageItemSchema),
|
|
20
|
+
}, { additionalProperties: false });
|
|
21
|
+
|
|
22
|
+
/** One whole page payload, before it becomes an outcome. */
|
|
23
|
+
export type HistoryPage = Static<typeof HistoryPageSchema>;
|
|
24
|
+
|
|
25
|
+
/** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
|
|
26
|
+
function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPageItem) => boolean): HistoryPageItem {
|
|
27
|
+
if (fits(item)) return item;
|
|
28
|
+
const shrinkContent = (base: HistoryPageItem): HistoryPageItem => ({
|
|
29
|
+
...base,
|
|
30
|
+
truncated: true,
|
|
31
|
+
content: prefixFit(base.content, (candidate) => fits({ ...base, truncated: true, content: candidate })),
|
|
32
|
+
});
|
|
33
|
+
const withContent = shrinkContent(item);
|
|
34
|
+
if (fits(withContent)) return withContent;
|
|
35
|
+
if (item.tool === undefined) return withContent;
|
|
36
|
+
const { tool: _dropped, ...withoutName } = item;
|
|
37
|
+
const named = { ...withoutName, tool_name_omitted: true };
|
|
38
|
+
if (fits(named)) return named;
|
|
39
|
+
return shrinkContent(named);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isFoldableEvent(event: HistoryEvent): boolean {
|
|
43
|
+
return event.role === "tool" || event.role === "context";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isConversationView(params: HistoryFilter): boolean {
|
|
47
|
+
return !params.roles;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Folded counts stay exact even when some distinct tool names must be omitted. */
|
|
51
|
+
function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
|
|
52
|
+
if (events.length === 0) return [];
|
|
53
|
+
const sorted = [...events].sort((a, b) => a.seq - b.seq);
|
|
54
|
+
const counts = new Map<string, number>();
|
|
55
|
+
for (const event of sorted) {
|
|
56
|
+
if (event.role !== "tool") continue;
|
|
57
|
+
const name = event.execution?.name ?? "unknown";
|
|
58
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
59
|
+
}
|
|
60
|
+
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
61
|
+
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
62
|
+
const tools = Object.fromEntries(entries);
|
|
63
|
+
const omitted = counts.size - entries.length;
|
|
64
|
+
return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools, ...(omitted > 0 ? { omitted_tools: omitted } : {}) }];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function pageAnchors(vis: HistoryEvent[], selected: HistoryEvent[], before: number | undefined, after: number | undefined): { older_before: number | null; newer_after: number | null } {
|
|
68
|
+
if (selected.length === 0) return { older_before: null, newer_after: null };
|
|
69
|
+
const lower = after ?? 0;
|
|
70
|
+
const upper = before ?? Number.POSITIVE_INFINITY;
|
|
71
|
+
// Selected events are in seq order.
|
|
72
|
+
const first = selected[0]!.seq;
|
|
73
|
+
const last = selected.at(-1)!.seq;
|
|
74
|
+
return {
|
|
75
|
+
older_before: vis.some((event) => event.seq > lower && event.seq < first && event.seq < upper) ? first : null,
|
|
76
|
+
newer_after: vis.some((event) => event.seq > last && event.seq < upper && event.seq > lower) ? last : null,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function foldRows(projection: HistoryProjection, params: HistoryFilter & AnchorParams, selected: HistoryEvent[], anchors: { older_before: number | null; newer_after: number | null }): HistoryFoldedRow[] {
|
|
81
|
+
const lower = params.after ?? 0;
|
|
82
|
+
const upper = params.before ?? Number.POSITIVE_INFINITY;
|
|
83
|
+
if (selected.length === 0) {
|
|
84
|
+
// Even a range with no conversation can contain tool/context events.
|
|
85
|
+
const hidden = allItems(projection).filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper && isFoldableEvent(event));
|
|
86
|
+
return foldedRuns(hidden);
|
|
87
|
+
}
|
|
88
|
+
const windowEvents = allItems(projection)
|
|
89
|
+
.filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper)
|
|
90
|
+
.sort((a, b) => a.seq - b.seq);
|
|
91
|
+
const folded: HistoryFoldedRow[] = [];
|
|
92
|
+
const firstSeq = selected[0]!.seq;
|
|
93
|
+
const lastSeq = selected.at(-1)!.seq;
|
|
94
|
+
if (anchors.older_before === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
|
|
95
|
+
// pageData already ordered selected by seq.
|
|
96
|
+
for (let i = 0; i + 1 < selected.length; i++) {
|
|
97
|
+
const left = selected[i]!.seq;
|
|
98
|
+
const right = selected[i + 1]!.seq;
|
|
99
|
+
folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
|
|
100
|
+
}
|
|
101
|
+
if (anchors.newer_after === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
|
|
102
|
+
return folded;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function pageData(projection: HistoryProjection, params: HistoryFilter & AnchorParams, vis: HistoryEvent[], selected: Candidate[], maxChars: number, folds: boolean): HistoryPage {
|
|
106
|
+
const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
|
|
107
|
+
const selectedEvents = orderedSelected.map((candidate) => candidate.event);
|
|
108
|
+
const anchors = pageAnchors(vis, selectedEvents, params.before, params.after);
|
|
109
|
+
const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
|
|
110
|
+
let rows: PageRow[] = visible;
|
|
111
|
+
if (folds) {
|
|
112
|
+
const folded = foldRows(projection, params, selectedEvents, anchors);
|
|
113
|
+
rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
|
|
114
|
+
}
|
|
115
|
+
return { items: rows, ...anchors };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function orderedCandidates(vis: Candidate[], before: number | undefined, after: number | undefined, limit: number): Candidate[] {
|
|
119
|
+
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
120
|
+
if (before !== undefined && after !== undefined) return ascending.filter((candidate) => candidate.event.seq > after && candidate.event.seq < before).slice(0, limit);
|
|
121
|
+
if (after !== undefined) return ascending.filter((candidate) => candidate.event.seq > after).slice(0, limit);
|
|
122
|
+
if (before !== undefined) return ascending.filter((candidate) => candidate.event.seq < before).reverse().slice(0, limit);
|
|
123
|
+
return ascending.slice(-limit).reverse();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Grow the page in query order; shorten the first preview only when no full row fits. */
|
|
127
|
+
export function selectPage(projection: HistoryProjection, params: HistoryFilter & AnchorParams, vis: Candidate[], folds: boolean, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
|
|
128
|
+
const before = params.before;
|
|
129
|
+
const after = params.after;
|
|
130
|
+
const limit = params.limit ?? 20;
|
|
131
|
+
const candidates = orderedCandidates(vis, before, after, limit);
|
|
132
|
+
const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
|
|
133
|
+
const kept: Candidate[] = [];
|
|
134
|
+
for (const candidate of candidates) {
|
|
135
|
+
if (fits(pageData(projection, params, allVisible, [...kept, candidate], maxChars, folds))) {
|
|
136
|
+
kept.push(candidate);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, params, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
const page = pageData(projection, params, allVisible, kept, maxChars, folds);
|
|
143
|
+
if (!fits(page)) {
|
|
144
|
+
return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow the range with before/after or read one seq`, { rows: page.items.length });
|
|
145
|
+
}
|
|
146
|
+
return success(page);
|
|
147
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default, createNotesoup } from "./pi/extension.js";
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { NoteError } from "./errors.js";
|
|
2
|
+
import type { NotesIdentity } from "./identity.js";
|
|
3
|
+
import { SLUG_PATTERN, type Scope } from "./paths.js";
|
|
4
|
+
|
|
5
|
+
export type NoteAddress = { scope: Scope; path: string; who?: string };
|
|
6
|
+
|
|
7
|
+
export const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
|
|
8
|
+
|
|
9
|
+
/** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
|
|
10
|
+
function shown(value: unknown): string {
|
|
11
|
+
const json = JSON.stringify(value);
|
|
12
|
+
return json === undefined ? String(value) : json;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function assertVirtualPath(value: unknown): string {
|
|
16
|
+
if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", `invalid address ${shown(value)}: path must be a non-empty string`);
|
|
17
|
+
if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject backslashes, leading "/", and NUL`);
|
|
18
|
+
const parts = value.split("/");
|
|
19
|
+
if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: paths reject "..", ".", and empty segments`);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
25
|
+
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
26
|
+
* slash also matches zero segments, so it covers the root too), `?` matches exactly
|
|
27
|
+
* one non-`/` character. Everything else is literal and the match is anchored to the
|
|
28
|
+
* whole path.
|
|
29
|
+
*/
|
|
30
|
+
export function globToRegExp(pattern: string): RegExp {
|
|
31
|
+
let source = "^";
|
|
32
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
33
|
+
const char = pattern[index]!;
|
|
34
|
+
if (char === "*") {
|
|
35
|
+
if (pattern[index + 1] === "*") {
|
|
36
|
+
const followedBySlash = pattern[index + 2] === "/";
|
|
37
|
+
source += followedBySlash ? "(?:[^]*\\/)?" : "[^]*";
|
|
38
|
+
index += followedBySlash ? 2 : 1;
|
|
39
|
+
} else {
|
|
40
|
+
source += "[^/]*";
|
|
41
|
+
}
|
|
42
|
+
} else {
|
|
43
|
+
source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return new RegExp(`${source}$`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
|
|
50
|
+
export function assertGlobPattern(value: unknown): string | undefined {
|
|
51
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
52
|
+
if (typeof value !== "string") throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns must be strings`);
|
|
53
|
+
if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `invalid pattern ${shown(value)}: glob patterns reject NUL and backslashes`);
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Decode one public note address into its physical home and virtual path. @self and @model
|
|
59
|
+
* are relative; explicit agents/models addresses always name a canonical slug.
|
|
60
|
+
*/
|
|
61
|
+
export function assertAddress(value: unknown): NoteAddress {
|
|
62
|
+
if (typeof value !== "string") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
63
|
+
let scope: Scope = "session";
|
|
64
|
+
let path = value;
|
|
65
|
+
let who: string | undefined;
|
|
66
|
+
if (value.startsWith("@")) {
|
|
67
|
+
const rest = value.slice(1);
|
|
68
|
+
const headEnd = rest.indexOf("/");
|
|
69
|
+
const head = headEnd === -1 ? rest : rest.slice(0, headEnd);
|
|
70
|
+
const tail = headEnd === -1 ? "" : rest.slice(headEnd + 1);
|
|
71
|
+
path = tail;
|
|
72
|
+
if (head === "project") scope = "project";
|
|
73
|
+
else if (head === "human") scope = "human";
|
|
74
|
+
else if (head === "self") scope = "agent";
|
|
75
|
+
else if (head === "model") scope = "model";
|
|
76
|
+
else if (head === "agents" || head === "models") {
|
|
77
|
+
const nameEnd = tail.indexOf("/");
|
|
78
|
+
who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
|
|
79
|
+
if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
80
|
+
scope = head === "agents" ? "agent" : "model";
|
|
81
|
+
path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
|
|
82
|
+
} else {
|
|
83
|
+
throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
84
|
+
}
|
|
85
|
+
if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
86
|
+
if (path === "" && who === undefined) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
87
|
+
}
|
|
88
|
+
if (path.includes("@")) throw new NoteError("invalid_address", `invalid address ${shown(value)}: ${ADDRESS_FORMS}`);
|
|
89
|
+
assertVirtualPath(path);
|
|
90
|
+
return { scope, path, who };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Render a virtual path in its one unambiguous address form, used to match patterns. */
|
|
94
|
+
export function canonicalAddressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string {
|
|
95
|
+
if (scope === "session") return path;
|
|
96
|
+
if (scope === "project") return `@project/${path}`;
|
|
97
|
+
if (scope === "human") return `@human/${path}`;
|
|
98
|
+
if (scope === "agent") return `@agents/${who ?? identity.agent}/${path}`;
|
|
99
|
+
return `@models/${who ?? identity.model}/${path}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Render the address a caller sees. The current agent and model homes read as @self/ and
|
|
104
|
+
* @model/ so ordinary sessions are not taught explicit ids; only other homes (dream) name one.
|
|
105
|
+
*/
|
|
106
|
+
export function addressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string {
|
|
107
|
+
if (scope === "agent" && (who === undefined || who === identity.agent)) return `@self/${path}`;
|
|
108
|
+
if (scope === "model" && (who === undefined || who === identity.model)) return `@model/${path}`;
|
|
109
|
+
return canonicalAddressFor(identity, scope, path, who);
|
|
110
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
|
|
2
|
+
|
|
3
|
+
/** Typed store refusal. Edit locations are exposed in camelCase. */
|
|
4
|
+
export class NoteError extends Error {
|
|
5
|
+
readonly code: NoteErrorCode;
|
|
6
|
+
readonly lineNumbers?: number[];
|
|
7
|
+
readonly editIndex?: number;
|
|
8
|
+
constructor(code: NoteErrorCode, message: string, extra: { lineNumbers?: number[]; editIndex?: number } = {}) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "NoteError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.lineNumbers = extra.lineNumbers;
|
|
13
|
+
this.editIndex = extra.editIndex;
|
|
14
|
+
}
|
|
15
|
+
}
|