@picassohq/cli 0.0.0-stage → 1.0.2
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/agents/browser_agent.yaml +53 -0
- package/agents/code_reviewer.yaml +49 -0
- package/agents/codebase_investigator.yaml +70 -0
- package/agents/design_auditor.yaml +50 -0
- package/agents/devex_auditor.yaml +50 -0
- package/agents/doc_writer.yaml +54 -0
- package/agents/engineering_architect.yaml +51 -0
- package/agents/generalist.yaml +55 -0
- package/agents/migration_planner.yaml +51 -0
- package/agents/product_reviewer.yaml +48 -0
- package/agents/qa_operator.yaml +52 -0
- package/agents/release_engineer.yaml +50 -0
- package/agents/security_auditor.yaml +62 -0
- package/agents/test_writer.yaml +52 -0
- package/assets/first-light-lockup.png +0 -0
- package/assets/first-light-tagline.png +0 -0
- package/assets/house/README.md +26 -0
- package/assets/house/auraone-banner.png +0 -0
- package/assets/house/auraone-logo.png +0 -0
- package/assets/house/kiro-prism-banner.png +0 -0
- package/assets/house/kiro-prism-logo.png +0 -0
- package/assets/house/picasso-banner.png +0 -0
- package/assets/house/picasso-logo.png +0 -0
- package/assets/wordmark-app.png +0 -0
- package/assets/wordmark-tight.png +0 -0
- package/assets/wordmark.png +0 -0
- package/design/styles.css +1042 -0
- package/dist/build-info.json +37 -0
- package/dist/index.js +3062 -0
- package/goals/cli-hardening.yaml +40 -0
- package/goals/repo-maintenance.yaml +40 -0
- package/package.json +49 -4
- package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
- package/runtime/dsh/picasso-ecosystem.community.json +185 -0
- package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
- package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
- package/runtime/dsh/picasso-isolation.patch.yml +25 -0
- package/runtime/dsh/picasso-providers.patch.yml +373 -0
- package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
- package/runtime/dsh/picasso-sdk.patch.yml +204 -0
- package/runtime/engine-manifest.json +215 -0
- package/runtime/package.json +6 -0
- package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
- package/runtime/packages/picasso-cache-probe/index.js +477 -0
- package/runtime/packages/picasso-cache-probe/package.json +38 -0
- package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-commands/fresh-review.js +573 -0
- package/runtime/packages/picasso-commands/index.js +497 -0
- package/runtime/packages/picasso-commands/package.json +28 -0
- package/runtime/packages/picasso-instructions/conflicts.js +115 -0
- package/runtime/packages/picasso-instructions/formats.js +145 -0
- package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
- package/runtime/packages/picasso-instructions/glob.js +114 -0
- package/runtime/packages/picasso-instructions/globals.js +90 -0
- package/runtime/packages/picasso-instructions/imports.js +123 -0
- package/runtime/packages/picasso-instructions/index.js +326 -0
- package/runtime/packages/picasso-instructions/modes.js +64 -0
- package/runtime/packages/picasso-instructions/package.json +30 -0
- package/runtime/packages/picasso-instructions/parse.js +134 -0
- package/runtime/packages/picasso-instructions/report.js +161 -0
- package/runtime/packages/picasso-instructions/resolve.js +939 -0
- package/runtime/packages/picasso-instructions/scan.js +181 -0
- package/runtime/packages/picasso-instructions/settings.js +150 -0
- package/runtime/packages/picasso-instructions/skills.js +345 -0
- package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
- package/runtime/packages/picasso-lean-context/index.js +6280 -0
- package/runtime/packages/picasso-lean-context/package.json +26 -0
- package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/packages/picasso-lean-context/timeline.js +418 -0
- package/runtime/packages/picasso-librarian/classify.js +146 -0
- package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-librarian/index.js +878 -0
- package/runtime/packages/picasso-librarian/notes.js +159 -0
- package/runtime/packages/picasso-librarian/package.json +34 -0
- package/runtime/packages/picasso-librarian/state.js +478 -0
- package/runtime/packages/picasso-memory/index.js +1184 -0
- package/runtime/packages/picasso-memory/package.json +21 -0
- package/runtime/packages/picasso-model-router/connections.js +912 -0
- package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
- package/runtime/packages/picasso-model-router/index.js +1083 -0
- package/runtime/packages/picasso-model-router/package.json +30 -0
- package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
- package/runtime/packages/picasso-options/index.js +263 -0
- package/runtime/packages/picasso-options/package.json +28 -0
- package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
- package/runtime/packages/picasso-progress-reports/index.js +267 -0
- package/runtime/packages/picasso-progress-reports/package.json +30 -0
- package/runtime/packages/picasso-progress-reports/report.js +235 -0
- package/runtime/packages/picasso-sdk-server/aside.js +142 -0
- package/runtime/packages/picasso-sdk-server/connections.js +38 -0
- package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
- package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
- package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
- package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
- package/runtime/packages/picasso-sdk-server/goal.js +131 -0
- package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
- package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
- package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
- package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
- package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
- package/runtime/packages/picasso-sdk-server/index.js +891 -0
- package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
- package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
- package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
- package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
- package/runtime/packages/picasso-sdk-server/package.json +50 -0
- package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
- package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
- package/runtime/packages/picasso-sdk-server/queue.js +322 -0
- package/runtime/packages/picasso-sdk-server/requester.js +43 -0
- package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
- package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
- package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
- package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
- package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
- package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
- package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
- package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
- package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
- package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
- package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
- package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
- package/runtime/packages/picasso-web-search/backends.js +412 -0
- package/runtime/packages/picasso-web-search/config.js +121 -0
- package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
- package/runtime/packages/picasso-web-search/failure.js +116 -0
- package/runtime/packages/picasso-web-search/format.js +42 -0
- package/runtime/packages/picasso-web-search/index.js +71 -0
- package/runtime/packages/picasso-web-search/package.json +38 -0
- package/runtime/packages/picasso-web-search/router.js +156 -0
- package/runtime/packages/picasso-x-reader/circle.js +324 -0
- package/runtime/packages/picasso-x-reader/command.js +169 -0
- package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
- package/runtime/packages/picasso-x-reader/index.js +170 -0
- package/runtime/packages/picasso-x-reader/package.json +39 -0
- package/runtime/packages/picasso-x-reader/read.js +370 -0
- package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
- package/runtime/packages/picasso-x-reader/settings.js +131 -0
- package/runtime/packages/picasso-x-reader/urls.js +154 -0
- package/runtime/packages/picasso-x-reader/xmd.js +512 -0
- package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
- package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
- package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
- package/runtime/plugins/picasso-auto-approve/package.json +28 -0
- package/runtime/plugins/picasso-browser/index.js +424 -0
- package/runtime/plugins/picasso-browser/package.json +28 -0
- package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
- package/runtime/plugins/picasso-checkpoints/index.js +885 -0
- package/runtime/plugins/picasso-checkpoints/package.json +29 -0
- package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
- package/runtime/plugins/picasso-commands/index.js +497 -0
- package/runtime/plugins/picasso-commands/package.json +28 -0
- package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
- package/runtime/plugins/picasso-instructions/formats.js +145 -0
- package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
- package/runtime/plugins/picasso-instructions/glob.js +114 -0
- package/runtime/plugins/picasso-instructions/globals.js +90 -0
- package/runtime/plugins/picasso-instructions/imports.js +123 -0
- package/runtime/plugins/picasso-instructions/index.js +326 -0
- package/runtime/plugins/picasso-instructions/modes.js +64 -0
- package/runtime/plugins/picasso-instructions/package.json +30 -0
- package/runtime/plugins/picasso-instructions/parse.js +134 -0
- package/runtime/plugins/picasso-instructions/report.js +161 -0
- package/runtime/plugins/picasso-instructions/resolve.js +939 -0
- package/runtime/plugins/picasso-instructions/scan.js +181 -0
- package/runtime/plugins/picasso-instructions/settings.js +150 -0
- package/runtime/plugins/picasso-instructions/skills.js +345 -0
- package/runtime/plugins/picasso-lean-context/index.js +6280 -0
- package/runtime/plugins/picasso-lean-context/package.json +26 -0
- package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
- package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
- package/runtime/plugins/picasso-librarian/classify.js +146 -0
- package/runtime/plugins/picasso-librarian/index.js +878 -0
- package/runtime/plugins/picasso-librarian/notes.js +159 -0
- package/runtime/plugins/picasso-librarian/package.json +34 -0
- package/runtime/plugins/picasso-librarian/state.js +478 -0
- package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
- package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
- package/runtime/plugins/picasso-mail/inbox.js +207 -0
- package/runtime/plugins/picasso-mail/index.js +293 -0
- package/runtime/plugins/picasso-mail/package.json +22 -0
- package/runtime/plugins/picasso-memory/index.js +1184 -0
- package/runtime/plugins/picasso-memory/package.json +21 -0
- package/runtime/plugins/picasso-model-router/connections.js +912 -0
- package/runtime/plugins/picasso-model-router/index.js +1083 -0
- package/runtime/plugins/picasso-model-router/package.json +30 -0
- package/runtime/plugins/picasso-options/index.js +263 -0
- package/runtime/plugins/picasso-options/package.json +28 -0
- package/runtime/plugins/picasso-progress-reports/index.js +267 -0
- package/runtime/plugins/picasso-progress-reports/package.json +30 -0
- package/runtime/plugins/picasso-progress-reports/report.js +235 -0
- package/runtime/plugins/picasso-provider-models/index.js +436 -0
- package/runtime/plugins/picasso-provider-models/package.json +28 -0
- package/runtime/plugins/picasso-repo-index/index.js +1850 -0
- package/runtime/plugins/picasso-repo-index/package.json +28 -0
- package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
- package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
- package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
- package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
- package/runtime/plugins/picasso-trackers/index.js +895 -0
- package/runtime/plugins/picasso-trackers/package.json +28 -0
- package/runtime/plugins/picasso-web-search/backends.js +412 -0
- package/runtime/plugins/picasso-web-search/config.js +121 -0
- package/runtime/plugins/picasso-web-search/failure.js +116 -0
- package/runtime/plugins/picasso-web-search/format.js +42 -0
- package/runtime/plugins/picasso-web-search/index.js +71 -0
- package/runtime/plugins/picasso-web-search/package.json +38 -0
- package/runtime/plugins/picasso-web-search/router.js +156 -0
- package/runtime/plugins/picasso-x-reader/circle.js +324 -0
- package/runtime/plugins/picasso-x-reader/command.js +169 -0
- package/runtime/plugins/picasso-x-reader/index.js +170 -0
- package/runtime/plugins/picasso-x-reader/package.json +39 -0
- package/runtime/plugins/picasso-x-reader/read.js +370 -0
- package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
- package/runtime/plugins/picasso-x-reader/settings.js +131 -0
- package/runtime/plugins/picasso-x-reader/urls.js +154 -0
- package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
- package/runtime/relay/attachment-text.mjs +737 -0
- package/runtime/relay/companion/companion.css +126 -0
- package/runtime/relay/companion/companion.js +648 -0
- package/runtime/relay/companion/icon.svg +5 -0
- package/runtime/relay/companion/index.html +25 -0
- package/runtime/relay/companion/manifest.json +13 -0
- package/runtime/relay/companion/sw.js +41 -0
- package/runtime/relay/main.mjs +38580 -0
- package/runtime/relay/model-listing.mjs +614 -0
- package/runtime/relay/versions-routes.mjs +1400 -0
- package/runtime/verify-plugins.mjs +205 -0
- package/runtime-lock/package-lock.json +10779 -0
- package/runtime-lock/package.json +7 -0
- package/scripts/install-runtime.mjs +400 -0
- package/README.md +0 -3
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// Context timeline: what entered the model's context on each turn, what compaction removed, the cache hit and miss
|
|
2
|
+
// of every model step, and a lane per subagent. Pure folds over data Picasso already has (C1, no new model traffic):
|
|
3
|
+
//
|
|
4
|
+
// - the session's durable events (`sessionQuery.observeSession`): prompts, runtime context messages, tool calls and
|
|
5
|
+
// their results, memory recalls, compaction, `assistant/message.usage` per step, `subagent/catalog` children;
|
|
6
|
+
// - lean-context's per-step records (`ContextStats.stepsFor`, live engine only): the Tier-2 reminders the pre-step
|
|
7
|
+
// normaliser injected (plan-mode, runtime-policy, stale-todos, plan-nudge) and the step's message count. The engine logs each
|
|
8
|
+
// step's normalised messages, so the reminders themselves are read from the log (sourced `user/message` rows);
|
|
9
|
+
// the records corroborate them and add any the log missed. `stepStats` says how many steps a record covered.
|
|
10
|
+
// The same fold runs without records (`picasso context timeline` reads a saved session's log directly).
|
|
11
|
+
//
|
|
12
|
+
// Byte counts are UTF-8 bytes of the text that entered the context. Token counts are the engine's (disjoint:
|
|
13
|
+
// `inputTokens` is uncached input only), so a step's prompt is `input + cacheRead + cacheWrite` and its hit rate is
|
|
14
|
+
// `cacheRead / prompt` — the same fields `picasso-cache-probe` records as `llm-stream-usage`.
|
|
15
|
+
|
|
16
|
+
export const CONTEXT_TIMELINE_VERSION = 1;
|
|
17
|
+
/** Subagent lanes nest at most this deep (a child's own children are lanes of its lane). */
|
|
18
|
+
export const CONTEXT_TIMELINE_MAX_DEPTH = 3;
|
|
19
|
+
/** At most this many lanes per timeline (the newest spawns are dropped past it, and the cut is reported). */
|
|
20
|
+
export const CONTEXT_TIMELINE_MAX_LANES = 32;
|
|
21
|
+
|
|
22
|
+
const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
23
|
+
const int = (value) => (Number.isSafeInteger(value) ? value : undefined);
|
|
24
|
+
const str = (value) => (typeof value === "string" && value.length > 0 ? value : undefined);
|
|
25
|
+
|
|
26
|
+
/** UTF-8 bytes of a message's text parts (a bare string counts whole; non-text parts count 0). */
|
|
27
|
+
export function contentBytes(content) {
|
|
28
|
+
if (typeof content === "string") return Buffer.byteLength(content, "utf8");
|
|
29
|
+
if (!Array.isArray(content)) return 0;
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
for (const part of content) {
|
|
32
|
+
if (typeof part === "string") bytes += Buffer.byteLength(part, "utf8");
|
|
33
|
+
else if (isRecord(part) && typeof part.text === "string") bytes += Buffer.byteLength(part.text, "utf8");
|
|
34
|
+
}
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** `{input, cacheRead, cacheWrite, output}` from an `assistant/message.usage`; undefined when absent. */
|
|
39
|
+
export function stepUsage(usage) {
|
|
40
|
+
if (!isRecord(usage)) return undefined;
|
|
41
|
+
return {
|
|
42
|
+
input: int(usage.inputTokens) ?? 0,
|
|
43
|
+
cacheRead: int(usage.cacheReadTokens) ?? 0,
|
|
44
|
+
cacheWrite: int(usage.cacheWriteTokens) ?? 0,
|
|
45
|
+
output: int(usage.outputTokens) ?? 0,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Cached share of the prompt; null when the step reported no prompt tokens. */
|
|
50
|
+
export function hitRate(usage) {
|
|
51
|
+
if (!usage) return null;
|
|
52
|
+
const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
53
|
+
return prompt > 0 ? Number((usage.cacheRead / prompt).toFixed(4)) : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function addUsage(total, usage) {
|
|
57
|
+
if (!usage) return total;
|
|
58
|
+
total.input += usage.input;
|
|
59
|
+
total.cacheRead += usage.cacheRead;
|
|
60
|
+
total.cacheWrite += usage.cacheWrite;
|
|
61
|
+
total.output += usage.output;
|
|
62
|
+
return total;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const zeroUsage = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0 });
|
|
66
|
+
|
|
67
|
+
function parseArguments(raw) {
|
|
68
|
+
if (isRecord(raw)) return raw;
|
|
69
|
+
if (typeof raw !== "string" || raw.length === 0) return {};
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(raw);
|
|
72
|
+
return isRecord(parsed) ? parsed : {};
|
|
73
|
+
} catch {
|
|
74
|
+
return {};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Tools whose result is a file's contents entering the context. */
|
|
79
|
+
const FILE_READ_TOOLS = new Set(["read", "read_file", "view", "fs_read", "cat"]);
|
|
80
|
+
const SPAWN_TOOLS = new Set(["subagent", "subagent_fork", "spawn_agent", "fork_agent", "spawn", "task", "agent_task"]);
|
|
81
|
+
const SPAWN_RECEIPT = /^started subagent (\S+)\s*$/;
|
|
82
|
+
/** Sourced reminder messages (Tier 2): lean-context's plan-mode / runtime-policy / stale-todos / plan-nudge and the CLI's append. */
|
|
83
|
+
export const REMINDER_KINDS = new Set(["plan-mode", "runtime-policy", "stale-todos", "plan-nudge", "append-system-prompt"]);
|
|
84
|
+
|
|
85
|
+
/** The timeline kind of one tool call: file / skill / memory / agent / tool. */
|
|
86
|
+
function toolKind(name, args) {
|
|
87
|
+
if (FILE_READ_TOOLS.has(name)) return "file";
|
|
88
|
+
if (name === "skill") return "skill";
|
|
89
|
+
if (name === "recall") return "memory";
|
|
90
|
+
if (SPAWN_TOOLS.has(name)) return "agent";
|
|
91
|
+
if (name === "tool_call") {
|
|
92
|
+
const inner = str(args.name);
|
|
93
|
+
if (inner === "recall") return "memory";
|
|
94
|
+
if (inner && SPAWN_TOOLS.has(inner)) return "agent";
|
|
95
|
+
}
|
|
96
|
+
return "tool";
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What a timeline row names for a tool call: the file, the skill, the recall query, else the tool. */
|
|
100
|
+
function toolTarget(kind, name, args, meta) {
|
|
101
|
+
if (kind === "file") return str(meta?.path) ?? str(args.file_path) ?? str(args.path) ?? name;
|
|
102
|
+
if (kind === "skill") return str(args.name) ?? str(args.skill) ?? name;
|
|
103
|
+
if (kind === "memory") {
|
|
104
|
+
const inner = isRecord(args.arguments) ? args.arguments : args;
|
|
105
|
+
const ids = Array.isArray(inner.ids) ? inner.ids.filter((id) => typeof id === "string") : [];
|
|
106
|
+
return ids.length > 0 ? ids.join(", ") : str(inner.query) ?? "recall";
|
|
107
|
+
}
|
|
108
|
+
if (name === "tool_call") return str(args.name) ?? name;
|
|
109
|
+
return name;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Lean-context's step records for one session, attributed to the log's steps. A record carries the session's event
|
|
114
|
+
* count (`seq`, the seq the next event gets) when the normaliser ran. The engine runs `agent/pre-step` before it logs
|
|
115
|
+
* that step's `step/start` and the step's (normalised) context messages, so a record belongs to the first
|
|
116
|
+
* `step/start` at or after its seq. A record past the last logged step (a request that never started) is dropped.
|
|
117
|
+
*/
|
|
118
|
+
function attributeSteps(stepStarts, records) {
|
|
119
|
+
const byStep = new Map();
|
|
120
|
+
if (!Array.isArray(records) || records.length === 0) return byStep;
|
|
121
|
+
const starts = [...stepStarts].sort((a, b) => a.seq - b.seq);
|
|
122
|
+
for (const record of records) {
|
|
123
|
+
if (!isRecord(record) || !Number.isSafeInteger(record.seq)) continue;
|
|
124
|
+
const owner = starts.find((start) => start.seq >= record.seq);
|
|
125
|
+
// A retried pre-step for the same step keeps the newest record (the one whose messages were sent).
|
|
126
|
+
if (owner !== undefined) byStep.set(owner.key, record);
|
|
127
|
+
}
|
|
128
|
+
return byStep;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function remindersOf(record) {
|
|
132
|
+
const injected = isRecord(record?.injected) ? record.injected : {};
|
|
133
|
+
return [
|
|
134
|
+
injected.planMode === true ? "plan-mode" : null,
|
|
135
|
+
injected.runtimePolicy === true ? "runtime-policy" : null,
|
|
136
|
+
injected.staleTodos === true ? "stale-todos" : null,
|
|
137
|
+
injected.planNudge === true ? "plan-nudge" : null,
|
|
138
|
+
].filter(Boolean);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Fold one session's events into its timeline (no lanes; `buildContextTimeline` adds them).
|
|
143
|
+
* @param {readonly any[]} events - the session's durable events, ascending seq.
|
|
144
|
+
* @param {readonly any[]} [records] - lean-context step records for this session (`ContextStats.stepsFor`).
|
|
145
|
+
*/
|
|
146
|
+
export function foldSessionTimeline(events, records = []) {
|
|
147
|
+
const turns = [];
|
|
148
|
+
const compactions = [];
|
|
149
|
+
const children = [];
|
|
150
|
+
const childSeen = new Set();
|
|
151
|
+
const calls = new Map();
|
|
152
|
+
const stepStarts = [];
|
|
153
|
+
let current;
|
|
154
|
+
let lastTurn = 0;
|
|
155
|
+
let pendingPrompt;
|
|
156
|
+
let pendingContext = [];
|
|
157
|
+
|
|
158
|
+
const turnFor = (number) => {
|
|
159
|
+
if (current && (number === undefined || current.turn === number)) return current;
|
|
160
|
+
if (number !== undefined) {
|
|
161
|
+
const found = turns.find((turn) => turn.turn === number);
|
|
162
|
+
if (found) return found;
|
|
163
|
+
}
|
|
164
|
+
return current;
|
|
165
|
+
};
|
|
166
|
+
const stepOf = (turn, number) => {
|
|
167
|
+
if (!turn) return undefined;
|
|
168
|
+
const want = number ?? turn.steps.at(-1)?.step;
|
|
169
|
+
if (want === undefined) return undefined;
|
|
170
|
+
let step = turn.steps.find((candidate) => candidate.step === want);
|
|
171
|
+
if (!step) {
|
|
172
|
+
step = { step: want, seq: undefined, at: undefined, usage: null, hitRate: null, reminders: [], messageCount: null };
|
|
173
|
+
turn.steps.push(step);
|
|
174
|
+
}
|
|
175
|
+
return step;
|
|
176
|
+
};
|
|
177
|
+
const addChild = (id, label, turn, step, callId) => {
|
|
178
|
+
if (!id || childSeen.has(id)) {
|
|
179
|
+
const known = children.find((child) => child.sessionId === id);
|
|
180
|
+
if (known && label && !known.label) known.label = label;
|
|
181
|
+
if (known && callId && !known.callId) known.callId = callId;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
childSeen.add(id);
|
|
185
|
+
children.push({ sessionId: id, label: label ?? null, parentTurn: turn ?? null, parentStep: step ?? null, callId: callId ?? null });
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
189
|
+
if (!isRecord(event) || typeof event.type !== "string") continue;
|
|
190
|
+
const d = isRecord(event.data) ? event.data : {};
|
|
191
|
+
const seq = int(event.seq);
|
|
192
|
+
const at = typeof event.time === "number" ? event.time : undefined;
|
|
193
|
+
switch (event.type) {
|
|
194
|
+
case "turn/start": {
|
|
195
|
+
const number = int(d.turn) ?? lastTurn + 1;
|
|
196
|
+
current = { turn: number, seq, startedAt: at ?? null, endedAt: null, steps: [], entries: [], usage: zeroUsage(), hitRate: null };
|
|
197
|
+
turns.push(current);
|
|
198
|
+
lastTurn = number;
|
|
199
|
+
if (pendingPrompt) current.entries.push({ ...pendingPrompt, step: null });
|
|
200
|
+
for (const entry of pendingContext) current.entries.push({ ...entry, step: null });
|
|
201
|
+
pendingPrompt = undefined;
|
|
202
|
+
pendingContext = [];
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
case "turn/end": {
|
|
206
|
+
const turn = turnFor(int(d.turn));
|
|
207
|
+
if (turn) turn.endedAt = at ?? null;
|
|
208
|
+
if (turn === current) current = undefined;
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
case "step/start": {
|
|
212
|
+
const turn = turnFor(int(d.turn));
|
|
213
|
+
const step = stepOf(turn, int(d.step));
|
|
214
|
+
if (step) {
|
|
215
|
+
step.seq = seq ?? null;
|
|
216
|
+
step.at = at ?? null;
|
|
217
|
+
if (seq !== undefined) stepStarts.push({ seq, key: step });
|
|
218
|
+
}
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
case "system/message":
|
|
222
|
+
case "user/message":
|
|
223
|
+
case "developer/message": {
|
|
224
|
+
const message = isRecord(d.message) ? d.message : d;
|
|
225
|
+
const kind = str(message.source?.kind) ?? (event.type === "system/message" ? "system-prompt" : "user");
|
|
226
|
+
const bytes = contentBytes(message.content);
|
|
227
|
+
const entry =
|
|
228
|
+
kind === "user"
|
|
229
|
+
? { kind: "prompt", name: "prompt", bytes, seq: seq ?? null }
|
|
230
|
+
: { kind: REMINDER_KINDS.has(kind) ? "reminder" : "context", name: kind, bytes, seq: seq ?? null };
|
|
231
|
+
const turn = turnFor(int(d.turn));
|
|
232
|
+
if (turn && turn === current) {
|
|
233
|
+
turn.entries.push({ ...entry, step: turn.steps.at(-1)?.step ?? null });
|
|
234
|
+
} else if (kind === "user") {
|
|
235
|
+
pendingPrompt = entry;
|
|
236
|
+
} else {
|
|
237
|
+
pendingContext.push(entry);
|
|
238
|
+
}
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
case "assistant/message": {
|
|
242
|
+
const turn = turnFor(int(d.turn));
|
|
243
|
+
const step = stepOf(turn, int(d.step));
|
|
244
|
+
const usage = stepUsage(d.usage ?? d.message?.usage);
|
|
245
|
+
if (step && usage) {
|
|
246
|
+
step.usage = addUsage(step.usage ?? zeroUsage(), usage);
|
|
247
|
+
step.hitRate = hitRate(step.usage);
|
|
248
|
+
}
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
case "tool/call": {
|
|
252
|
+
const name = str(d.name) ?? "tool";
|
|
253
|
+
const args = parseArguments(d.arguments);
|
|
254
|
+
const turn = turnFor(int(d.turn));
|
|
255
|
+
const kind = toolKind(name, args);
|
|
256
|
+
const entry = {
|
|
257
|
+
kind,
|
|
258
|
+
name: toolTarget(kind, name, args, undefined),
|
|
259
|
+
tool: name,
|
|
260
|
+
step: int(d.step) ?? turn?.steps.at(-1)?.step ?? null,
|
|
261
|
+
bytes: 0,
|
|
262
|
+
seq: seq ?? null,
|
|
263
|
+
callId: str(d.callId) ?? null,
|
|
264
|
+
pending: true,
|
|
265
|
+
};
|
|
266
|
+
if (turn) turn.entries.push(entry);
|
|
267
|
+
if (entry.callId) calls.set(entry.callId, { entry, args, turn: turn?.turn, step: entry.step });
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
case "tool/result": {
|
|
271
|
+
const message = isRecord(d.message) ? d.message : {};
|
|
272
|
+
const callId = str(message.toolCallId) ?? str(message.source?.callId) ?? str(d.callId);
|
|
273
|
+
const call = callId ? calls.get(callId) : undefined;
|
|
274
|
+
const bytes = contentBytes(message.content);
|
|
275
|
+
if (call) {
|
|
276
|
+
call.entry.bytes += bytes;
|
|
277
|
+
call.entry.pending = false;
|
|
278
|
+
if (message.isError === true) call.entry.error = true;
|
|
279
|
+
if (call.entry.kind === "file") call.entry.name = toolTarget("file", call.entry.tool, call.args, d.meta);
|
|
280
|
+
const text = Array.isArray(message.content)
|
|
281
|
+
? message.content.map((part) => (isRecord(part) && typeof part.text === "string" ? part.text : "")).join("")
|
|
282
|
+
: String(message.content ?? "");
|
|
283
|
+
const spawned = SPAWN_RECEIPT.exec(text.trim());
|
|
284
|
+
if (spawned) {
|
|
285
|
+
call.entry.kind = "agent";
|
|
286
|
+
call.entry.childSessionId = spawned[1];
|
|
287
|
+
addChild(spawned[1], undefined, call.turn, call.step, callId);
|
|
288
|
+
}
|
|
289
|
+
} else {
|
|
290
|
+
const turn = turnFor(int(d.turn));
|
|
291
|
+
if (turn) turn.entries.push({ kind: "tool", name: "tool output", tool: null, step: int(d.step) ?? null, bytes, seq: seq ?? null, callId: callId ?? null });
|
|
292
|
+
}
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
case "memory/recalled": {
|
|
296
|
+
const turn = turnFor(int(d.turn));
|
|
297
|
+
const count = int(d.count) ?? (Array.isArray(d.ids) ? d.ids.length : 0);
|
|
298
|
+
if (turn) {
|
|
299
|
+
turn.entries.push({
|
|
300
|
+
kind: "memory",
|
|
301
|
+
name: `${count} memor${count === 1 ? "y" : "ies"}`,
|
|
302
|
+
step: turn.steps.at(-1)?.step ?? null,
|
|
303
|
+
bytes: contentBytes(d.content ?? d.text),
|
|
304
|
+
seq: seq ?? null,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
case "subagent/catalog": {
|
|
310
|
+
const turn = current;
|
|
311
|
+
addChild(str(d.childId), str(d.label), turn?.turn, turn?.steps.at(-1)?.step, undefined);
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
case "compaction/summary":
|
|
315
|
+
case "compaction/prune": {
|
|
316
|
+
const summary = event.type === "compaction/summary" ? d.summary : undefined;
|
|
317
|
+
// A summary is itself a model call: its usage is the engine's, reported beside the agent's steps.
|
|
318
|
+
const usage = stepUsage(d.usage) ?? null;
|
|
319
|
+
compactions.push({
|
|
320
|
+
usage,
|
|
321
|
+
hitRate: hitRate(usage),
|
|
322
|
+
kind: event.type === "compaction/summary" ? "summary" : "prune",
|
|
323
|
+
seq: seq ?? null,
|
|
324
|
+
at: at ?? null,
|
|
325
|
+
afterTurn: lastTurn,
|
|
326
|
+
inTurn: current !== undefined,
|
|
327
|
+
tokensRemoved: int(d.shadowedTokenCount) ?? null,
|
|
328
|
+
itemsRemoved: Array.isArray(d.shadowedSeqs) ? d.shadowedSeqs.length : null,
|
|
329
|
+
summaryBytes: summary === undefined ? null : contentBytes(summary),
|
|
330
|
+
});
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
default:
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Lean-context reminders, per step. Steps it never saw keep `reminders: null`.
|
|
339
|
+
const attributed = attributeSteps(stepStarts, records);
|
|
340
|
+
// The engine logs each step's normalised messages, so the reminders a step carried are its logged reminder rows.
|
|
341
|
+
// A lean-context record corroborates them (and names one the log missed, which then gets its own row).
|
|
342
|
+
let recorded = 0;
|
|
343
|
+
for (const turn of turns) {
|
|
344
|
+
for (const step of turn.steps) {
|
|
345
|
+
const logged = turn.entries.filter((entry) => entry.kind === "reminder" && entry.step === step.step).map((entry) => entry.name);
|
|
346
|
+
const record = attributed.get(step);
|
|
347
|
+
const injected = record ? remindersOf(record) : [];
|
|
348
|
+
if (record) {
|
|
349
|
+
recorded += 1;
|
|
350
|
+
step.messageCount = int(record.messageCount) ?? null;
|
|
351
|
+
for (const name of injected) {
|
|
352
|
+
if (logged.includes(name)) continue;
|
|
353
|
+
turn.entries.push({ kind: "reminder", name, step: step.step, bytes: int(record.reminderBytes?.[name]) ?? null, seq: step.seq ?? null });
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
step.reminders = [...new Set([...logged, ...injected])];
|
|
357
|
+
}
|
|
358
|
+
// Reminders join their step's rows: entries read in step order (stable), turn-level ones first.
|
|
359
|
+
turn.entries.sort((a, b) => (a.step ?? 0) - (b.step ?? 0));
|
|
360
|
+
for (const step of turn.steps) addUsage(turn.usage, step.usage);
|
|
361
|
+
turn.hitRate = hitRate(turn.usage);
|
|
362
|
+
for (const entry of turn.entries) delete entry.pending;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const totals = turns.reduce((sum, turn) => addUsage(sum, turn.usage), zeroUsage());
|
|
366
|
+
const compactionUsage = compactions.reduce((sum, compaction) => addUsage(sum, compaction.usage), zeroUsage());
|
|
367
|
+
const steps = turns.reduce((count, turn) => count + turn.steps.length, 0);
|
|
368
|
+
return {
|
|
369
|
+
turns,
|
|
370
|
+
compactions,
|
|
371
|
+
children,
|
|
372
|
+
totals: { ...totals, hitRate: hitRate(totals), turns: turns.length, steps, compaction: compactionUsage },
|
|
373
|
+
stepStats: steps === 0 || recorded === 0 ? "none" : recorded === steps ? "recorded" : "partial",
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The whole timeline for `sessionId`: its own fold plus one lane per subagent (recursively, to `maxDepth`).
|
|
379
|
+
* @param {object} input
|
|
380
|
+
* @param {string} input.sessionId
|
|
381
|
+
* @param {(sessionId: string) => Promise<readonly any[]>} input.readEvents - a session's durable events.
|
|
382
|
+
* @param {(sessionId: string) => readonly any[]} [input.stepsFor] - lean-context step records for a session.
|
|
383
|
+
*/
|
|
384
|
+
export async function buildContextTimeline({ sessionId, readEvents, stepsFor = () => [], maxDepth = CONTEXT_TIMELINE_MAX_DEPTH, maxLanes = CONTEXT_TIMELINE_MAX_LANES }) {
|
|
385
|
+
let lanesLeft = maxLanes;
|
|
386
|
+
let lanesDropped = 0;
|
|
387
|
+
const visited = new Set();
|
|
388
|
+
const build = async (id, depth) => {
|
|
389
|
+
visited.add(id);
|
|
390
|
+
const fold = foldSessionTimeline(await readEvents(id), stepsFor(id));
|
|
391
|
+
const lanes = [];
|
|
392
|
+
if (depth < maxDepth) {
|
|
393
|
+
for (const child of fold.children) {
|
|
394
|
+
if (visited.has(child.sessionId)) continue;
|
|
395
|
+
if (lanesLeft <= 0) {
|
|
396
|
+
lanesDropped += 1;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
lanesLeft -= 1;
|
|
400
|
+
let timeline;
|
|
401
|
+
let error;
|
|
402
|
+
try {
|
|
403
|
+
timeline = await build(child.sessionId, depth + 1);
|
|
404
|
+
} catch (cause) {
|
|
405
|
+
// A child whose log cannot be read is named with the reason, never filled in.
|
|
406
|
+
error = cause instanceof Error ? cause.message : String(cause);
|
|
407
|
+
}
|
|
408
|
+
lanes.push({ ...child, ...(timeline ? { timeline } : { timeline: null, error }) });
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
lanesDropped += fold.children.length;
|
|
412
|
+
}
|
|
413
|
+
const { children: _children, ...rest } = fold;
|
|
414
|
+
return { sessionId: id, ...rest, lanes };
|
|
415
|
+
};
|
|
416
|
+
const root = await build(sessionId, 0);
|
|
417
|
+
return { version: CONTEXT_TIMELINE_VERSION, ...root, lanesDropped };
|
|
418
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The librarian's one subagent task: which project does a thread started without one belong to?
|
|
2
|
+
//
|
|
3
|
+
// The task is built only from the thread's first turns, the candidate projects (name, folder, recent thread
|
|
4
|
+
// titles, notes digest). The instructions travel only as the child's first user message, so the shared
|
|
5
|
+
// tools -> system -> Tier 1 prefix stays byte-identical. The answer is a structured result (FILING_SCHEMA);
|
|
6
|
+
// `decide` turns it into a filing only when it names a real candidate with enough confidence.
|
|
7
|
+
|
|
8
|
+
export const FIRST_TURNS = 3;
|
|
9
|
+
export const TRANSCRIPT_MAX_CHARS = 6_000;
|
|
10
|
+
export const MESSAGE_MAX_CHARS = 1_500;
|
|
11
|
+
export const CANDIDATE_LIMIT = 24;
|
|
12
|
+
export const THREAD_TITLES_PER_PROJECT = 5;
|
|
13
|
+
|
|
14
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
|
|
16
|
+
export const FILING_SCHEMA = Object.freeze({
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
decision: { type: 'string', enum: ['file', 'none'], description: '"file" when the thread clearly belongs to one listed project; "none" when it fits none or you are unsure.' },
|
|
20
|
+
projectId: { type: 'string', description: 'The id in brackets of the chosen project (for example "p2"). Empty when decision is "none".' },
|
|
21
|
+
confidence: { type: 'number', description: 'How sure you are, from 0 to 1.' },
|
|
22
|
+
reason: { type: 'string', description: 'One short sentence a person reads in a list.' },
|
|
23
|
+
notes: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
description: 'Only when filing: what this thread settled for the project. Short items; empty lists when nothing was settled.',
|
|
26
|
+
properties: {
|
|
27
|
+
decisions: { type: 'array', items: { type: 'string' }, description: 'Up to 3 decisions made.' },
|
|
28
|
+
conventions: { type: 'array', items: { type: 'string' }, description: 'Up to 3 conventions agreed (naming, tools, style).' },
|
|
29
|
+
openItems: { type: 'array', items: { type: 'string' }, description: 'Up to 3 things left to do.' },
|
|
30
|
+
},
|
|
31
|
+
required: ['decisions', 'conventions', 'openItems'],
|
|
32
|
+
additionalProperties: false,
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
required: ['decision', 'projectId', 'confidence', 'reason', 'notes'],
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const textOf = (message) => (Array.isArray(message?.content) ? message.content : [])
|
|
40
|
+
.map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))
|
|
41
|
+
.join('\n')
|
|
42
|
+
.trim();
|
|
43
|
+
|
|
44
|
+
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The first `turns` turns of a session log as `[{role, text}]`: the person's prompts and the assistant's text
|
|
48
|
+
* (tool traffic and system reminders are left out). `eventAt(seq)` / `seq` is the engine's durable log.
|
|
49
|
+
*/
|
|
50
|
+
export function firstTurns(session, turns = FIRST_TURNS) {
|
|
51
|
+
const out = [];
|
|
52
|
+
const length = Number.isSafeInteger(session?.seq) ? session.seq : 0;
|
|
53
|
+
let seenTurns = 0;
|
|
54
|
+
for (let seq = 0; seq < length; seq += 1) {
|
|
55
|
+
let event;
|
|
56
|
+
try {
|
|
57
|
+
event = session.eventAt(seq);
|
|
58
|
+
} catch {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (!isRecord(event)) continue;
|
|
62
|
+
if (event.type === 'turn/start') {
|
|
63
|
+
seenTurns += 1;
|
|
64
|
+
if (seenTurns > turns) break;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (event.type === 'user/message') {
|
|
68
|
+
const kind = event.data?.source?.kind;
|
|
69
|
+
if (kind !== undefined && kind !== 'user') continue;
|
|
70
|
+
const text = textOf(event.data);
|
|
71
|
+
if (text) out.push({ role: 'person', text: clip(text, MESSAGE_MAX_CHARS) });
|
|
72
|
+
} else if (event.type === 'assistant/message') {
|
|
73
|
+
const text = textOf(event.data?.message ?? event.data);
|
|
74
|
+
if (text) out.push({ role: 'assistant', text: clip(text, MESSAGE_MAX_CHARS) });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Whether a session has at least one finished exchange worth reading (a person prompt and an assistant reply). */
|
|
81
|
+
export function hasExchange(turns) {
|
|
82
|
+
return turns.some((turn) => turn.role === 'person') && turns.some((turn) => turn.role === 'assistant');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function fenceFor(text) {
|
|
86
|
+
let longest = 2;
|
|
87
|
+
for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);
|
|
88
|
+
return '`'.repeat(longest + 1);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Candidates get short ids (`p1`, `p2`, …) in list order; the model answers with one of them. */
|
|
92
|
+
export function withIds(candidates) {
|
|
93
|
+
return candidates.slice(0, CANDIDATE_LIMIT).map((candidate, index) => ({ ...candidate, id: `p${index + 1}` }));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The complete task the librarian's subagent receives as its only user message. */
|
|
97
|
+
export function filingTask({ title, turns }, candidates) {
|
|
98
|
+
let transcript = '';
|
|
99
|
+
for (const turn of turns) {
|
|
100
|
+
const line = `${turn.role === 'person' ? 'Person' : 'Assistant'}: ${turn.text}\n\n`;
|
|
101
|
+
if (transcript.length + line.length > TRANSCRIPT_MAX_CHARS) break;
|
|
102
|
+
transcript += line;
|
|
103
|
+
}
|
|
104
|
+
transcript = transcript.trim();
|
|
105
|
+
const fence = fenceFor(transcript);
|
|
106
|
+
const lines = [
|
|
107
|
+
'You are the librarian. A person started this thread without picking a project. Decide which project it belongs to.',
|
|
108
|
+
'',
|
|
109
|
+
'Rules:',
|
|
110
|
+
'- Work only from the text below. Do not call tools, open files, run commands or delegate.',
|
|
111
|
+
'- File the thread only when it clearly belongs to exactly one listed project. When it fits none, or two fit equally, answer "none".',
|
|
112
|
+
'- When filing, list what the thread settled for that project: decisions, conventions and open items. Leave the lists empty when it settled nothing.',
|
|
113
|
+
'- Submit the structured result.',
|
|
114
|
+
'',
|
|
115
|
+
`Thread${title ? `: ${title}` : ''}`,
|
|
116
|
+
`${fence}text`,
|
|
117
|
+
transcript || '(no text)',
|
|
118
|
+
fence,
|
|
119
|
+
'',
|
|
120
|
+
'Projects:',
|
|
121
|
+
];
|
|
122
|
+
for (const candidate of candidates) {
|
|
123
|
+
lines.push(`[${candidate.id}] ${candidate.title} (${candidate.kind === 'workspace' ? 'workspace' : 'folder'}: ${candidate.path})`);
|
|
124
|
+
if (candidate.threadTitles?.length) lines.push(` Threads: ${candidate.threadTitles.slice(0, THREAD_TITLES_PER_PROJECT).join(' · ')}`);
|
|
125
|
+
if (candidate.notes) lines.push(` Notes: ${candidate.notes}`);
|
|
126
|
+
}
|
|
127
|
+
return lines.join('\n');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The structured answer → `{kind: 'file', target, reason, confidence, notes}` | `{kind: 'none', reason, confidence}` |
|
|
132
|
+
* `{kind: 'invalid', reason}`. `file` needs `decision: 'file'`, a known project id and confidence ≥ `threshold`.
|
|
133
|
+
*/
|
|
134
|
+
export function decide(structured, candidates, threshold) {
|
|
135
|
+
if (!isRecord(structured)) return { kind: 'invalid', reason: 'The model returned no structured answer.' };
|
|
136
|
+
const reason = typeof structured.reason === 'string' && structured.reason.trim() ? structured.reason.trim().replace(/\s+/g, ' ') : undefined;
|
|
137
|
+
const confidence = typeof structured.confidence === 'number' && Number.isFinite(structured.confidence) ? Math.max(0, Math.min(1, structured.confidence)) : undefined;
|
|
138
|
+
if (structured.decision !== 'file' && structured.decision !== 'none') return { kind: 'invalid', reason: 'The model answered without a decision.' };
|
|
139
|
+
if (confidence === undefined) return { kind: 'invalid', reason: 'The model answered without a confidence.' };
|
|
140
|
+
if (structured.decision === 'none') return { kind: 'none', reason: reason ?? 'It fits no project.', confidence };
|
|
141
|
+
const target = candidates.find((candidate) => candidate.id === String(structured.projectId ?? '').trim());
|
|
142
|
+
if (!target) return { kind: 'none', reason: `It named a project that isn't listed (${String(structured.projectId ?? '').slice(0, 40) || 'none'}).`, confidence };
|
|
143
|
+
if (confidence < threshold) return { kind: 'none', reason: `Not sure enough to file it into ${target.title} (${Math.round(confidence * 100)}%).${reason ? ` ${reason}` : ''}`, confidence, target };
|
|
144
|
+
const notes = isRecord(structured.notes) ? structured.notes : {};
|
|
145
|
+
return { kind: 'file', target, reason: reason ?? `It belongs to ${target.title}.`, confidence, notes };
|
|
146
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Picasso librarian — one bundle patch layer row (loader insert).
|
|
2
|
+
# ON by default; Pause (Mac Librarian page, TUI /librarian) stops all of its work. State and controls live in
|
|
3
|
+
# <picassoHome>/state/librarian.json; `PICASSO_LIBRARIAN=off` turns the worker off for a launch.
|
|
4
|
+
- insert:
|
|
5
|
+
- id: picasso-librarian
|
|
6
|
+
name: '@picasso/librarian'
|
|
7
|
+
# config:
|
|
8
|
+
# stateFile: /abs/path/librarian.json
|
|
9
|
+
# notesDir: /abs/path/notes
|
|
10
|
+
# unfiledDirs: [/abs/path]
|