@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.
Files changed (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,878 @@
1
+ // @picasso/librarian — files threads started without a project (dsh 0.2.2-rc.3 cordis plugin).
2
+ //
3
+ // Watching. `agent/status` going idle on a top-level thread whose working directory is an "unfiled" folder (the
4
+ // Studio default workspace `<picassoHome>/workspace`, the engine's default workspace, the account home) queues a
5
+ // look `delayMs` later (default 2 minutes; each later turn pushes it back, so the librarian reads after the person
6
+ // pauses). "Look at everything" queues every unfiled top-level thread now.
7
+ //
8
+ // Looking. ONE subagent per look, through the engine's real subagent path (`subagents.startActivation` on the
9
+ // `spawn` provider: a fresh child with no parent context, `delivery: 'caller'`). Its only user message is the
10
+ // filing task (classify.js): the thread's first turns plus the candidate projects (workspaces and the folders
11
+ // other threads ran in, with their recent thread titles and notes). No agent preset is selected and nothing is
12
+ // added to the system prompt or tools, so Tier 1 stays byte-identical. Every tool call the child tries is denied
13
+ // (`tools/pre-execute`) except `structured_output`, its answer: the librarian reads, it never edits code. The model
14
+ // is `settings.model` (the person's choice), else the router's cheapest ladder tier, else the thread's own route.
15
+ //
16
+ // Filing. A confident answer moves the thread to the project's folder (`workingDirectory.set`, the engine's own
17
+ // move), detaches it from the unfiled workspace and attaches it to the project's workspace when the engine allows,
18
+ // records the filing in the state file (the relay groups the thread under that project) and merges what the thread
19
+ // settled into the project's notes file (notes.js; recall reaches it on demand, never Tier 1).
20
+ //
21
+ // C1. Nothing is faked: a failed or unstructured child answer is recorded in Recent as an error with the engine's
22
+ // own diagnostic; a look that never ran is not counted as one.
23
+ //
24
+ // Budget and pause. Each look's tokens (the child's `assistant/message` usage) count against
25
+ // `settings.dailyTokenBudget` (local day). At the budget the queue waits for midnight. Pause aborts the running look
26
+ // and stops the timer; nothing runs while paused. With nothing queued no timer exists, and wake-ups are at least
27
+ // `minGapMs` (60 s) apart, so an idle engine does no librarian work.
28
+ //
29
+ // State (`state.js`): `<picassoHome>/state/librarian.json`, shared with the relay (`GET /librarian`, SSE) and the TUI
30
+ // (`/librarian`), persisted on every change, so a restart resumes the queue. Controls written by another process
31
+ // (pause, look-all, budget) arrive through a file watch.
32
+ //
33
+ // Remote (`librarian/*`): `get`, `pause`, `resume`, `lookAll`, `setBudget {dailyTokenBudget}`.
34
+ import { randomUUID } from 'node:crypto';
35
+ import { existsSync, realpathSync, statSync, watch } from 'node:fs';
36
+ import { homedir } from 'node:os';
37
+ import { basename, dirname, join, resolve, sep } from 'node:path';
38
+
39
+ import { FILING_SCHEMA, decide, filingTask, firstTurns, hasExchange, withIds } from './classify.js';
40
+ import { notesDigest, readNotes, updateNotes } from './notes.js';
41
+ import {
42
+ CLAIM_MS,
43
+ DEFAULT_CONFIDENCE,
44
+ DEFAULT_DELAY_MS,
45
+ budgetLeft,
46
+ clampBudget,
47
+ claimedElsewhere,
48
+ dequeue,
49
+ enqueue,
50
+ isProcessAlive,
51
+ nextLocalMidnight,
52
+ notesDirPath,
53
+ orderedQueue,
54
+ picassoHomeDir,
55
+ readState,
56
+ recordOutcome,
57
+ stateFilePath,
58
+ stateView,
59
+ updateState,
60
+ } from './state.js';
61
+
62
+ export * from './state.js';
63
+ export { FILING_SCHEMA, decide, filingTask, firstTurns, hasExchange, withIds } from './classify.js';
64
+ export { listNotes, mergeNotes, noteIdFor, notesDigest, notesFileFor, parseNotes, readNotes, renderNotes, updateNotes } from './notes.js';
65
+
66
+ export const name = 'picasso-librarian';
67
+ export const dshTarget = '0.2.2-rc.3';
68
+ export const SERVICE_KEY = 'librarian';
69
+ export const SPAWN_PROVIDER = 'spawn';
70
+ export const CHILD_LABEL = 'Librarian';
71
+ export const MIN_GAP_MS = 60_000;
72
+ /** A thread is looked at no more than this many times while it stays unfiled. */
73
+ export const MAX_LOOKS_PER_THREAD = 3;
74
+ /** The engine's tool a structured-output child submits its result with: the only tool a librarian child may call. */
75
+ export const STRUCTURED_OUTPUT_TOOL = 'structured_output';
76
+ export const DENY_REASON = 'The librarian only reads the thread it was given; it does not run tools.';
77
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods';
78
+
79
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
80
+ const nonempty = (value) => (typeof value === 'string' && value.trim() !== '' ? value : undefined);
81
+ const errorText = (error) => (error instanceof Error ? error.message : String(error));
82
+
83
+ export function normalizePath(path) {
84
+ if (typeof path !== 'string' || path === '') return undefined;
85
+ let out = resolve(path);
86
+ try {
87
+ out = realpathSync(out);
88
+ } catch {
89
+ // A folder that no longer exists keeps its spelled path.
90
+ }
91
+ while (out.length > 1 && out.endsWith(sep)) out = out.slice(0, -1);
92
+ return out;
93
+ }
94
+
95
+ /** `/repo/.picasso/worktrees/x` → `/repo`: a worktree thread belongs to its repository's project. */
96
+ export function projectRootOf(path) {
97
+ const marker = `${sep}.picasso${sep}worktrees${sep}`;
98
+ const at = path.indexOf(marker);
99
+ return at > 0 ? path.slice(0, at) : path;
100
+ }
101
+
102
+ /** Whether an agent is a delegated child (subagent) or a side thread. */
103
+ export function isChildAgent(agent) {
104
+ const header = agent?.session?.header;
105
+ if (!isRecord(header)) return false;
106
+ if (header.origin === 'subagent' || header.parentSession !== undefined) return true;
107
+ return Number.isSafeInteger(header.delegationDepth) && header.delegationDepth > 0;
108
+ }
109
+
110
+ /** The tokens one `assistant/message` event reports (input + output). */
111
+ export function usageTokens(event) {
112
+ const usage = event?.data?.usage ?? event?.data?.message?.usage;
113
+ if (!isRecord(usage)) return 0;
114
+ const input = Number(usage.inputTokens ?? 0);
115
+ const output = Number(usage.outputTokens ?? 0);
116
+ return (Number.isFinite(input) ? input : 0) + (Number.isFinite(output) ? output : 0);
117
+ }
118
+
119
+ function outputText(blocks) {
120
+ return (Array.isArray(blocks) ? blocks : [])
121
+ .map((block) => (isRecord(block) && block.type === 'text' && typeof block.text === 'string' ? block.text : ''))
122
+ .join('')
123
+ .trim();
124
+ }
125
+
126
+ /**
127
+ * The engine-independent librarian. `deps` adapts the engine (see `engineDeps`); tests pass fakes.
128
+ * listSessions() → [{sessionId, title?, cwd?, origin?, parentSessionId?, archived?, updatedAt?}]
129
+ * agentFor(id) → {agent} | {unavailable: true} | {error} (live, else cold-resumed when the host can)
130
+ * cwdOf(agent), titleOf(agent), isRunning(agent)
131
+ * workspaces() → [{id, title, path, sessionIds}]; defaultWorkspacePath() → string|undefined
132
+ * startChild({agent, childId, task, schema, model, signal}) → {result, tokens}
133
+ * fileInto(agent, target) → {path, workspace: 'attached'|'folder'}
134
+ * modelChoice() → {provider, model} | undefined
135
+ * setTimeout/clearTimeout/now/watch
136
+ */
137
+ export class Librarian {
138
+ constructor(deps, options = {}) {
139
+ this.deps = deps;
140
+ this.file = options.stateFile ?? stateFilePath(options.env);
141
+ this.notesDir = options.notesDir ?? notesDirPath(options.env);
142
+ this.home = options.picassoHome ?? picassoHomeDir(options.env);
143
+ this.extraUnfiled = (options.unfiledDirs ?? []).map(normalizePath).filter(Boolean);
144
+ this.minGapMs = Number.isFinite(options.minGapMs) ? options.minGapMs : MIN_GAP_MS;
145
+ this.envDelayMs = Number.isFinite(options.delayMs) ? options.delayMs : undefined;
146
+ this.now = deps.now ?? Date.now;
147
+ this.setTimer = deps.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
148
+ this.clearTimer = deps.clearTimeout ?? ((handle) => clearTimeout(handle));
149
+ this.timer = undefined;
150
+ this.lastWake = undefined;
151
+ this.busy = false;
152
+ this.inflight = undefined;
153
+ this.childIds = new Set();
154
+ this.unreachable = new Set();
155
+ this.listeners = new Set();
156
+ this.closed = false;
157
+ this.knownPaused = undefined;
158
+ }
159
+
160
+ // ---- state ----
161
+
162
+ read() {
163
+ return readState(this.file, this.now());
164
+ }
165
+
166
+ update(mutate) {
167
+ const { state, result } = updateState(this.file, mutate, { now: this.now });
168
+ this.changed(state);
169
+ return { state, result };
170
+ }
171
+
172
+ changed(state) {
173
+ this.knownPaused = state.paused;
174
+ for (const listener of this.listeners) {
175
+ try {
176
+ listener(state);
177
+ } catch {
178
+ // a listener's failure is its own
179
+ }
180
+ }
181
+ }
182
+
183
+ onChange(listener) {
184
+ this.listeners.add(listener);
185
+ return () => this.listeners.delete(listener);
186
+ }
187
+
188
+ view() {
189
+ return stateView(this.read(), this.now());
190
+ }
191
+
192
+ delayMs(state) {
193
+ return this.envDelayMs ?? state.settings.delayMs ?? DEFAULT_DELAY_MS;
194
+ }
195
+
196
+ // ---- which folders mean "no project" ----
197
+
198
+ unfiledDirs() {
199
+ const dirs = new Set(this.extraUnfiled);
200
+ for (const path of [join(this.home, 'workspace'), homedir(), this.deps.defaultWorkspacePath?.()]) {
201
+ const normal = normalizePath(path);
202
+ if (normal) dirs.add(normal);
203
+ }
204
+ return dirs;
205
+ }
206
+
207
+ isUnfiled(cwd) {
208
+ const normal = normalizePath(cwd);
209
+ return normal !== undefined && this.unfiledDirs().has(normal);
210
+ }
211
+
212
+ // ---- lifecycle ----
213
+
214
+ /** Resume after a restart: a look this process (or a dead one) left half-done goes back to the queue. */
215
+ start() {
216
+ this.update((state) => {
217
+ if (state.working && (state.working.pid === process.pid || !isProcessAlive(state.working.pid))) delete state.working;
218
+ for (const item of state.queue) if (item.claim && (item.claim.pid === process.pid || !isProcessAlive(item.claim.pid))) delete item.claim;
219
+ });
220
+ this.schedule();
221
+ }
222
+
223
+ close() {
224
+ this.closed = true;
225
+ this.cancelTimer();
226
+ this.inflight?.abort(new Error('The librarian stopped.'));
227
+ }
228
+
229
+ cancelTimer() {
230
+ if (this.timer !== undefined) this.clearTimer(this.timer);
231
+ this.timer = undefined;
232
+ }
233
+
234
+ /** One timer at most: the earliest due item this process can work on, never sooner than `minGapMs` after the last wake. */
235
+ schedule() {
236
+ this.cancelTimer();
237
+ if (this.closed || this.busy) return;
238
+ const state = this.read();
239
+ if (state.paused) return;
240
+ const now = this.now();
241
+ const eligible = orderedQueue(state).filter((item) => !claimedElsewhere(item, now) && !this.unreachable.has(item.sessionId));
242
+ if (eligible.length === 0) return;
243
+ let at = eligible[0].dueAt;
244
+ if (budgetLeft(state) <= 0) at = Math.max(at, nextLocalMidnight(now));
245
+ let delay = Math.max(0, at - now);
246
+ if (this.lastWake !== undefined) delay = Math.max(delay, this.lastWake + this.minGapMs - now);
247
+ this.timer = this.setTimer(() => {
248
+ this.timer = undefined;
249
+ void this.tick();
250
+ }, delay);
251
+ this.timer?.unref?.();
252
+ }
253
+
254
+ async tick() {
255
+ if (this.closed || this.busy) return;
256
+ this.lastWake = this.now();
257
+ this.busy = true;
258
+ try {
259
+ for (;;) {
260
+ const claimed = this.claimNext();
261
+ if (!claimed) break;
262
+ try {
263
+ await this.look(claimed);
264
+ } catch (error) {
265
+ // A look that failed before its model call (the engine refused to open the thread, …) is shown, once.
266
+ this.update((state, now) => {
267
+ dequeue(state, claimed.sessionId);
268
+ if (state.working?.sessionId === claimed.sessionId) delete state.working;
269
+ recordOutcome(state, { sessionId: claimed.sessionId, title: claimed.title, outcome: 'error', summary: "Couldn't look", detail: errorText(error) }, now);
270
+ });
271
+ }
272
+ if (this.closed || this.read().paused) break;
273
+ }
274
+ } catch (error) {
275
+ this.deps.log?.(`picasso-librarian: ${errorText(error)}`);
276
+ } finally {
277
+ this.busy = false;
278
+ this.schedule();
279
+ }
280
+ }
281
+
282
+ /** Take the next due item under the lock (`claim` names this process), or nothing. */
283
+ claimNext() {
284
+ const { result } = this.update((state, now) => {
285
+ if (state.paused || budgetLeft(state) <= 0) return undefined;
286
+ const item = orderedQueue(state).find((entry) => entry.dueAt <= now && !claimedElsewhere(entry, now) && !this.unreachable.has(entry.sessionId));
287
+ if (!item) return undefined;
288
+ item.claim = { pid: process.pid, until: now + CLAIM_MS };
289
+ return { ...item };
290
+ });
291
+ return result;
292
+ }
293
+
294
+ release(sessionId, change = {}) {
295
+ this.update((state) => {
296
+ const item = state.queue.find((entry) => entry.sessionId === sessionId);
297
+ if (item) {
298
+ delete item.claim;
299
+ Object.assign(item, change);
300
+ }
301
+ if (state.working?.sessionId === sessionId) delete state.working;
302
+ });
303
+ }
304
+
305
+ skip(item, detail) {
306
+ this.update((state, now) => {
307
+ dequeue(state, item.sessionId);
308
+ if (state.working?.sessionId === item.sessionId) delete state.working;
309
+ recordOutcome(state, { sessionId: item.sessionId, title: item.title, outcome: 'skipped', summary: 'Skipped', detail }, now);
310
+ });
311
+ }
312
+
313
+ // ---- watching ----
314
+
315
+ /** `agent/status`: a top-level thread in an unfiled folder that just went idle gets a look `delayMs` later. */
316
+ noteStatus(agent, running) {
317
+ if (this.closed || !agent?.session || isChildAgent(agent) || this.childIds.has(agent.session.id)) return;
318
+ if (running) return;
319
+ const sessionId = agent.session.id;
320
+ const cwd = this.deps.cwdOf(agent);
321
+ if (!this.isUnfiled(cwd)) return;
322
+ const state = this.read();
323
+ const looks = state.recent.filter((entry) => entry.sessionId === sessionId && entry.outcome !== 'skipped').length;
324
+ if (looks >= MAX_LOOKS_PER_THREAD || state.filings[sessionId]) return;
325
+ this.unreachable.delete(sessionId);
326
+ const title = nonempty(this.deps.titleOf?.(agent));
327
+ this.update((next, now) => {
328
+ enqueue(next, { sessionId, cwd, reason: 'new-thread', queuedAt: now, dueAt: now + this.delayMs(next), ...(title ? { title } : {}) });
329
+ });
330
+ this.schedule();
331
+ }
332
+
333
+ // ---- controls ----
334
+
335
+ pause() {
336
+ this.update((state) => {
337
+ state.paused = true;
338
+ });
339
+ this.cancelTimer();
340
+ this.inflight?.abort(new Error('Paused.'));
341
+ return this.view();
342
+ }
343
+
344
+ resume() {
345
+ this.update((state) => {
346
+ state.paused = false;
347
+ });
348
+ this.schedule();
349
+ return this.view();
350
+ }
351
+
352
+ setBudget(value) {
353
+ const raw = isRecord(value) ? value.dailyTokenBudget : value;
354
+ const budget = clampBudget(raw);
355
+ if (budget === undefined) throw new LibrarianError('bad-request', 'dailyTokenBudget must be a number of tokens.');
356
+ this.update((state) => {
357
+ state.settings.dailyTokenBudget = budget;
358
+ });
359
+ this.schedule();
360
+ return this.view();
361
+ }
362
+
363
+ /** Queue every unfiled top-level thread that has not been decided yet, due now (in list order). */
364
+ async lookAll() {
365
+ const sessions = await this.deps.listSessions();
366
+ const unfiled = sessions.filter((row) => !row.archived && row.origin !== 'subagent' && !row.parentSessionId && this.isUnfiled(row.cwd));
367
+ let added = 0;
368
+ this.update((state, now) => {
369
+ const decided = new Set(Object.keys(state.filings));
370
+ unfiled.forEach((row, index) => {
371
+ if (decided.has(row.sessionId)) return;
372
+ if (enqueue(state, { sessionId: row.sessionId, cwd: row.cwd, reason: 'look-all', queuedAt: now, dueAt: now + index, ...(row.title ? { title: row.title } : {}) }, { sooner: true })) added += 1;
373
+ });
374
+ state.controls.lookAllHandledAt = now;
375
+ });
376
+ this.unreachable.clear();
377
+ this.schedule();
378
+ return { ...this.view(), added };
379
+ }
380
+
381
+ /** Another process changed the file: follow its pause, run its look-all request, re-plan the timer. */
382
+ async fileChanged() {
383
+ if (this.closed) return;
384
+ const state = this.read();
385
+ if (state.paused && this.knownPaused === false) this.inflight?.abort(new Error('Paused.'));
386
+ this.knownPaused = state.paused;
387
+ const requested = state.controls.lookAllRequestedAt;
388
+ if (!state.paused && requested !== undefined && requested > (state.controls.lookAllHandledAt ?? 0)) {
389
+ await this.lookAll();
390
+ return;
391
+ }
392
+ if (!this.busy) this.schedule();
393
+ }
394
+
395
+ // ---- one look ----
396
+
397
+ /** Workspaces and the folders other threads ran in (worktrees fold into their repository), newest activity first. */
398
+ async gatherCandidates(sessionId) {
399
+ const unfiled = this.unfiledDirs();
400
+ const state = this.read();
401
+ const byPath = new Map();
402
+ const add = (path, make) => {
403
+ const normal = normalizePath(path);
404
+ if (!normal || unfiled.has(normal) || !isDirectory(normal)) return undefined;
405
+ if (!byPath.has(normal)) byPath.set(normal, make(normal));
406
+ return byPath.get(normal);
407
+ };
408
+ for (const workspace of this.deps.workspaces?.() ?? []) {
409
+ add(workspace.path, (path) => ({ kind: 'workspace', workspaceId: workspace.id, title: nonempty(workspace.title) ?? basename(path), path, threadTitles: [], lastActive: 0 }));
410
+ }
411
+ let rows = [];
412
+ try {
413
+ rows = await this.deps.listSessions();
414
+ } catch (error) {
415
+ this.deps.log?.(`picasso-librarian: listing threads failed: ${errorText(error)}`);
416
+ }
417
+ for (const row of rows) {
418
+ if (row.sessionId === sessionId || row.archived || row.origin === 'subagent' || row.parentSessionId) continue;
419
+ const filed = state.filings[row.sessionId];
420
+ const where = filed?.path ?? row.cwd;
421
+ if (!where) continue;
422
+ const root = projectRootOf(normalizePath(where) ?? where);
423
+ const project = add(root, (path) => ({ kind: 'folder', title: basename(path) || path, path, threadTitles: [], lastActive: 0 }));
424
+ if (!project) continue;
425
+ if (row.title && project.threadTitles.length < 5 && !project.threadTitles.includes(row.title)) project.threadTitles.push(row.title);
426
+ project.lastActive = Math.max(project.lastActive, Number(row.updatedAt ?? 0) || 0);
427
+ }
428
+ const list = [...byPath.values()].sort((a, b) => b.lastActive - a.lastActive || a.title.localeCompare(b.title));
429
+ for (const candidate of list) {
430
+ const digest = notesDigest(readNotes(this.notesDir, candidate.path));
431
+ if (digest) candidate.notes = digest;
432
+ }
433
+ return withIds(list);
434
+ }
435
+
436
+ modelChoice() {
437
+ const state = this.read();
438
+ return state.settings.model ?? this.deps.modelChoice?.();
439
+ }
440
+
441
+ async look(item) {
442
+ const resolved = await this.deps.agentFor(item.sessionId);
443
+ if (resolved?.unavailable) {
444
+ // This engine cannot open that thread (another surface owns it); leave it for one that can.
445
+ this.unreachable.add(item.sessionId);
446
+ this.release(item.sessionId);
447
+ return;
448
+ }
449
+ if (!resolved?.agent) {
450
+ this.skip(item, resolved?.error ? `Couldn't open the thread: ${resolved.error}` : 'The thread is gone.');
451
+ return;
452
+ }
453
+ const agent = resolved.agent;
454
+ const title = nonempty(this.deps.titleOf?.(agent)) ?? item.title;
455
+ const cwd = this.deps.cwdOf(agent);
456
+ if (!this.isUnfiled(cwd)) {
457
+ this.skip({ ...item, title }, `Already in ${basename(cwd ?? '') || 'a project'}.`);
458
+ return;
459
+ }
460
+ if (this.deps.isRunning?.(agent)) {
461
+ this.release(item.sessionId, { dueAt: this.now() + this.delayMs(this.read()) });
462
+ return;
463
+ }
464
+ const turns = firstTurns(agent.session);
465
+ if (!hasExchange(turns)) {
466
+ if (item.reason === 'look-all') this.skip({ ...item, title }, 'Nothing to read yet.');
467
+ else this.release(item.sessionId, { dueAt: this.now() + this.delayMs(this.read()) });
468
+ return;
469
+ }
470
+ const candidates = await this.gatherCandidates(item.sessionId);
471
+ if (candidates.length === 0) {
472
+ this.skip({ ...item, title }, 'No projects to file into yet.');
473
+ return;
474
+ }
475
+
476
+ const childId = randomUUID();
477
+ const controller = new AbortController();
478
+ this.inflight = controller;
479
+ this.childIds.add(childId);
480
+ this.update((state, now) => {
481
+ state.working = { sessionId: item.sessionId, startedAt: now, pid: process.pid, ...(title ? { title } : {}) };
482
+ });
483
+ let tokens = 0;
484
+ let outcome;
485
+ try {
486
+ const run = await this.deps.startChild({
487
+ agent,
488
+ childId,
489
+ task: filingTask({ title, turns }, candidates),
490
+ schema: FILING_SCHEMA,
491
+ model: this.modelChoice(),
492
+ signal: controller.signal,
493
+ });
494
+ tokens = Math.max(0, Math.round(run?.tokens ?? 0));
495
+ const result = run?.result;
496
+ if (controller.signal.aborted) {
497
+ outcome = { aborted: true };
498
+ } else if (result?.stopReason !== 'completed') {
499
+ const said = outputText(result?.output);
500
+ outcome = { outcome: 'error', summary: "Couldn't look", detail: nonempty(result?.diagnostic) ?? `The model stopped (${result?.stopReason ?? 'no result'}).${said ? ` ${said.slice(0, 200)}` : ''}` };
501
+ } else {
502
+ const threshold = this.read().settings.confidence ?? DEFAULT_CONFIDENCE;
503
+ const decision = decide(result.structured, candidates, threshold);
504
+ if (decision.kind === 'invalid') {
505
+ outcome = { outcome: 'error', summary: "Couldn't look", detail: decision.reason };
506
+ } else if (decision.kind === 'none') {
507
+ outcome = { outcome: 'unchanged', summary: 'Nothing to change', detail: decision.reason };
508
+ } else {
509
+ const target = decision.target;
510
+ const filed = await this.deps.fileInto(agent, target);
511
+ const path = filed?.path ?? target.path;
512
+ // A workspace target is recorded even when the engine keeps the thread in its creation folder's workspace:
513
+ // the relay shows the thread in the chosen workspace's group from this record.
514
+ const filing = { path, title: target.title, ...(target.workspaceId ? { workspaceId: target.workspaceId } : {}) };
515
+ try {
516
+ updateNotes(this.notesDir, { title: target.title, path: target.path }, decision.notes, this.now());
517
+ } catch (error) {
518
+ this.deps.log?.(`picasso-librarian: notes for ${target.title} not written: ${errorText(error)}`);
519
+ }
520
+ outcome = { outcome: 'filed', summary: `Filed into ${target.title}`, detail: decision.reason, target: filing, filing };
521
+ }
522
+ }
523
+ } catch (error) {
524
+ outcome = controller.signal.aborted ? { aborted: true } : { outcome: 'error', summary: "Couldn't look", detail: errorText(error) };
525
+ } finally {
526
+ this.childIds.delete(childId);
527
+ this.inflight = undefined;
528
+ }
529
+
530
+ this.update((state, now) => {
531
+ if (state.working?.sessionId === item.sessionId) delete state.working;
532
+ if (outcome.aborted) {
533
+ // Paused mid-look: the item goes back to the queue untouched; the tokens it spent still count.
534
+ const queued = state.queue.find((entry) => entry.sessionId === item.sessionId);
535
+ if (queued) delete queued.claim;
536
+ state.counters.tokens += tokens;
537
+ return;
538
+ }
539
+ dequeue(state, item.sessionId);
540
+ const { filing, ...entry } = outcome;
541
+ recordOutcome(state, { ...entry, sessionId: item.sessionId, title, tokens, childId }, now);
542
+ if (filing) state.filings[item.sessionId] = { ...filing, at: now };
543
+ });
544
+ }
545
+ }
546
+
547
+ export class LibrarianError extends Error {
548
+ constructor(code, message) {
549
+ super(message);
550
+ this.name = 'LibrarianError';
551
+ this.code = `librarian/${code}`;
552
+ }
553
+ }
554
+
555
+ function isDirectory(path) {
556
+ try {
557
+ return statSync(path).isDirectory();
558
+ } catch {
559
+ return false;
560
+ }
561
+ }
562
+
563
+ // ---- the engine adapter ----
564
+
565
+ /** A session's title from the engine's `title` projection. */
566
+ function titleFor(ctx, session) {
567
+ try {
568
+ const title = ctx.get('sessionProjections')?.snapshot?.(session, ['title'])?.values?.title;
569
+ return nonempty(title);
570
+ } catch {
571
+ return undefined;
572
+ }
573
+ }
574
+
575
+ function rowTitle(row) {
576
+ const values = isRecord(row?.projections?.values) ? row.projections.values : {};
577
+ return nonempty(values.title) ?? nonempty(row?.title);
578
+ }
579
+
580
+ /** The engine services the librarian needs, read lazily (a missing one fails only the feature that needs it). */
581
+ export function engineDeps(ctx, { childTokens, log } = {}) {
582
+ const get = (key) => {
583
+ try {
584
+ return ctx.get?.(key) ?? ctx[key];
585
+ } catch {
586
+ return undefined;
587
+ }
588
+ };
589
+ const tokensFor = (childId) => {
590
+ let total = childTokens?.get(childId) ?? 0;
591
+ if (total > 0) return total;
592
+ const session = get('sessions')?.get?.(childId) ?? get('agents')?.get?.(childId)?.session;
593
+ if (session && typeof session.eventAt === 'function') {
594
+ for (let seq = 0; seq < (session.seq ?? 0); seq += 1) {
595
+ try {
596
+ const event = session.eventAt(seq);
597
+ if (event?.type === 'assistant/message') total += usageTokens(event);
598
+ } catch {
599
+ // skip unreadable events
600
+ }
601
+ }
602
+ }
603
+ return total;
604
+ };
605
+ return {
606
+ log: log ?? ((line) => ctx.logger?.warn?.(line)),
607
+ async listSessions() {
608
+ const controller = get('sessionController');
609
+ if (controller && typeof controller.list === 'function') {
610
+ const listed = await controller.list({});
611
+ const items = Array.isArray(listed?.items) ? listed.items : Array.isArray(listed) ? listed : [];
612
+ const archived = new Set(get('workspaceRegistry')?.requireState?.()?.archivedSessionIds ?? []);
613
+ return items.map((row) => {
614
+ const values = isRecord(row?.projections?.values) ? row.projections.values : {};
615
+ return {
616
+ sessionId: row.sessionId,
617
+ title: rowTitle(row),
618
+ cwd: nonempty(values.workingDirectory) ?? nonempty(row.cwd),
619
+ origin: row.origin,
620
+ parentSessionId: row.parentSessionId,
621
+ archived: archived.has(row.sessionId),
622
+ updatedAt: row.updatedAt,
623
+ };
624
+ });
625
+ }
626
+ const sessions = get('sessions');
627
+ return (sessions?.list?.() ?? []).map((session) => ({
628
+ sessionId: session.id,
629
+ title: titleFor(ctx, session),
630
+ cwd: get('workingDirectory')?.get?.(session) ?? session.header?.cwd,
631
+ origin: session.header?.origin,
632
+ parentSessionId: session.header?.parentSession,
633
+ updatedAt: session.header?.createdAt,
634
+ }));
635
+ },
636
+ async agentFor(sessionId) {
637
+ const live = get('agents')?.get?.(sessionId);
638
+ if (live) return { agent: live };
639
+ const controller = get('sessionController');
640
+ if (!controller || typeof controller.resolveAgent !== 'function') return { unavailable: true };
641
+ const found = await controller.resolveAgent(sessionId);
642
+ if (found?.agent) return { agent: found.agent };
643
+ const code = found?.error?.code;
644
+ if (code === 'session/not-found') return {};
645
+ if (code === 'session/writer-held') return { unavailable: true };
646
+ return { error: found?.error?.message ?? 'unknown error' };
647
+ },
648
+ cwdOf(agent) {
649
+ return get('workingDirectory')?.get?.(agent.session) ?? agent.session?.header?.cwd;
650
+ },
651
+ titleOf(agent) {
652
+ return titleFor(ctx, agent.session);
653
+ },
654
+ isRunning(agent) {
655
+ return agent?.status === 'running';
656
+ },
657
+ workspaces() {
658
+ const registry = get('workspaceRegistry');
659
+ try {
660
+ return (registry?.list?.() ?? []).map((entity) => ({ id: entity.id, title: entity.title, path: entity.path, sessionIds: entity.sessionIds }));
661
+ } catch {
662
+ return [];
663
+ }
664
+ },
665
+ defaultWorkspacePath() {
666
+ const registry = get('workspaceRegistry');
667
+ try {
668
+ const id = registry?.requireState?.()?.defaultWorkspaceId;
669
+ return id === undefined ? undefined : registry.get(id)?.path;
670
+ } catch {
671
+ return undefined;
672
+ }
673
+ },
674
+ modelChoice() {
675
+ try {
676
+ const tier = get('modelRouter')?.policy?.()?.ladder?.[0];
677
+ if (nonempty(tier?.provider) && nonempty(tier?.model)) return { provider: tier.provider, model: tier.model };
678
+ } catch {
679
+ // no router policy
680
+ }
681
+ return undefined;
682
+ },
683
+ async startChild({ agent, childId, task, schema, model, signal }) {
684
+ const subagents = get('subagents');
685
+ if (!subagents || typeof subagents.startActivation !== 'function') throw new Error('This engine cannot start subagents.');
686
+ const provider = typeof subagents.getProvider === 'function' ? subagents.getProvider(SPAWN_PROVIDER) : undefined;
687
+ if (!provider) throw new Error('This engine has no fresh subagent provider.');
688
+ if (provider.inheritsParentContext !== false) throw new Error('The fresh subagent provider would see the thread; the librarian refuses it.');
689
+ childTokens?.set(childId, 0);
690
+ // The child cannot delegate anyway (every tool it tries is denied); the depth cap is the engine's own.
691
+ const maxDepth = typeof subagents.resolveMaxDepth === 'function' ? subagents.resolveMaxDepth() : undefined;
692
+ try {
693
+ const activation = await subagents.startActivation({
694
+ provider: SPAWN_PROVIDER,
695
+ label: CHILD_LABEL,
696
+ childId,
697
+ request: {
698
+ cwd: agent.session.header?.cwd ?? get('workingDirectory')?.get?.(agent.session),
699
+ prompt: [{ type: 'text', text: task }],
700
+ parent: agent,
701
+ outputSchema: schema,
702
+ ...(maxDepth === undefined ? {} : { maxDepth }),
703
+ ...(model ? { agentOptions: { provider: model.provider, model: model.model } } : {}),
704
+ },
705
+ signal,
706
+ delivery: 'caller',
707
+ });
708
+ const onAbort = () => {
709
+ try {
710
+ activation.dispose?.();
711
+ } catch {
712
+ // best effort
713
+ }
714
+ };
715
+ signal.addEventListener('abort', onAbort, { once: true });
716
+ try {
717
+ const result = await activation.result;
718
+ return { result, tokens: tokensFor(childId) };
719
+ } finally {
720
+ signal.removeEventListener('abort', onAbort);
721
+ // The look is over: release the resident child (its log stays on disk under the thread).
722
+ Promise.resolve().then(() => activation.dispose?.()).catch(() => undefined);
723
+ }
724
+ } finally {
725
+ childTokens?.delete(childId);
726
+ }
727
+ },
728
+ async fileInto(agent, target) {
729
+ const directory = get('workingDirectory');
730
+ if (!directory || typeof directory.set !== 'function') throw new Error('This engine cannot move a thread to another folder.');
731
+ const sessionId = agent.session.id;
732
+ const path = await directory.set(agent, target.path);
733
+ let workspace = 'folder';
734
+ const registry = get('workspaceRegistry');
735
+ if (registry) {
736
+ for (const entity of registry.list?.() ?? []) {
737
+ if (normalizePath(entity.path) === normalizePath(path)) {
738
+ try {
739
+ await entity.attachSession(sessionId);
740
+ workspace = 'attached';
741
+ } catch {
742
+ // The engine keeps a thread in the workspace of the folder it was created in; the move still stands.
743
+ }
744
+ } else if (entity.sessionIds?.includes?.(sessionId)) {
745
+ try {
746
+ await entity.detachSession(sessionId);
747
+ } catch (error) {
748
+ log?.(`picasso-librarian: could not detach ${sessionId} from ${entity.path}: ${errorText(error)}`);
749
+ }
750
+ }
751
+ }
752
+ }
753
+ return { path: typeof path === 'string' ? path : target.path, workspace };
754
+ },
755
+ };
756
+ }
757
+
758
+ /** The Remote face: `librarian/get|pause|resume|lookAll|setBudget`. */
759
+ export class LibrarianService {
760
+ constructor(librarian) {
761
+ this.librarian = librarian;
762
+ }
763
+
764
+ get() {
765
+ return this.librarian.view();
766
+ }
767
+
768
+ pause() {
769
+ return this.librarian.pause();
770
+ }
771
+
772
+ resume() {
773
+ return this.librarian.resume();
774
+ }
775
+
776
+ lookAll() {
777
+ return this.librarian.lookAll();
778
+ }
779
+
780
+ setBudget(dailyTokenBudget) {
781
+ return this.librarian.setBudget(dailyTokenBudget);
782
+ }
783
+ }
784
+
785
+ const REMOTE_METHODS = ['get', 'pause', 'resume', 'lookAll', 'setBudget'];
786
+
787
+ Object.defineProperty(LibrarianService.prototype, REMOTE_METHOD_DESCRIPTOR, {
788
+ configurable: true,
789
+ value: Object.freeze({ version: 1, methods: Object.freeze(REMOTE_METHODS.map((method) => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
790
+ });
791
+
792
+ /** Settings from env (tests and the live harness): delay, gap, model. */
793
+ export function envOptions(env = process.env) {
794
+ const out = {};
795
+ const delay = Number(env.PICASSO_LIBRARIAN_DELAY_MS);
796
+ if (env.PICASSO_LIBRARIAN_DELAY_MS !== undefined && Number.isFinite(delay) && delay >= 0) out.delayMs = delay;
797
+ const gap = Number(env.PICASSO_LIBRARIAN_MIN_GAP_MS);
798
+ if (env.PICASSO_LIBRARIAN_MIN_GAP_MS !== undefined && Number.isFinite(gap) && gap >= 0) out.minGapMs = gap;
799
+ return out;
800
+ }
801
+
802
+ /**
803
+ * Cordis entry. Config: `{stateFile?, notesDir?, unfiledDirs?, disabled?}`. `PICASSO_LIBRARIAN=off` turns the
804
+ * worker off (the Remote still answers from the file).
805
+ */
806
+ export function apply(ctx, config = {}, deps = {}) {
807
+ const env = deps.env ?? process.env;
808
+ const childTokens = new Map();
809
+ const librarian = new Librarian(deps.engine ?? engineDeps(ctx, { childTokens }), {
810
+ env,
811
+ ...(nonempty(config.stateFile) ? { stateFile: config.stateFile } : {}),
812
+ ...(nonempty(config.notesDir) ? { notesDir: config.notesDir } : {}),
813
+ ...(Array.isArray(config.unfiledDirs) ? { unfiledDirs: config.unfiledDirs } : {}),
814
+ ...envOptions(env),
815
+ });
816
+ const service = new LibrarianService(librarian);
817
+ service.typertRemote = Object.freeze({ service, serviceKey: SERVICE_KEY, namespace: SERVICE_KEY });
818
+ ctx.provide?.(SERVICE_KEY, service);
819
+ const off = config.disabled === true || ['off', '0', 'false'].includes(String(env.PICASSO_LIBRARIAN ?? '').trim().toLowerCase());
820
+ if (off) return service;
821
+
822
+ // The librarian's own children may not run tools: it only reads what its task carries.
823
+ ctx.on?.('tools/pre-execute', (exec, next) => {
824
+ const id = exec?.agent?.session?.id;
825
+ // `structured_output` is how the child submits its answer; nothing else runs.
826
+ if (id !== undefined && librarian.childIds.has(id) && exec?.name !== STRUCTURED_OUTPUT_TOOL) return Promise.resolve({ kind: 'deny', reason: DENY_REASON, displayReason: { en: DENY_REASON } });
827
+ return next();
828
+ });
829
+ ctx.on?.('session/event', (session, event) => {
830
+ if (event?.type !== 'assistant/message' || !childTokens.has(session?.id)) return;
831
+ childTokens.set(session.id, (childTokens.get(session.id) ?? 0) + usageTokens(event));
832
+ });
833
+ ctx.on?.('agent/status', (payload) => {
834
+ try {
835
+ librarian.noteStatus(payload?.agent, payload?.status === 'running');
836
+ } catch (error) {
837
+ ctx.logger?.warn?.(`picasso-librarian: ${errorText(error)}`);
838
+ }
839
+ });
840
+
841
+ let watcher;
842
+ const startWatch = () => {
843
+ try {
844
+ const dir = dirname(librarian.file);
845
+ if (!existsSync(dir)) return;
846
+ const file = basename(librarian.file);
847
+ let pending;
848
+ watcher = (deps.watch ?? watch)(dir, { persistent: false }, (_event, changed) => {
849
+ if (changed !== null && changed !== undefined && String(changed) !== file) return;
850
+ clearTimeout(pending);
851
+ pending = setTimeout(() => void librarian.fileChanged(), 100);
852
+ pending.unref?.();
853
+ });
854
+ } catch (error) {
855
+ ctx.logger?.warn?.(`picasso-librarian: state watch unavailable (${errorText(error)})`);
856
+ }
857
+ };
858
+ const boot = () => {
859
+ try {
860
+ librarian.start();
861
+ } catch (error) {
862
+ ctx.logger?.warn?.(`picasso-librarian: ${errorText(error)}`);
863
+ }
864
+ startWatch();
865
+ };
866
+ if (typeof ctx.effect === 'function') {
867
+ ctx.effect(() => {
868
+ boot();
869
+ return () => {
870
+ watcher?.close?.();
871
+ librarian.close();
872
+ };
873
+ }, 'picasso-librarian');
874
+ } else {
875
+ boot();
876
+ }
877
+ return service;
878
+ }