@yaks/session 0.0.0-stage → 0.2.36

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 (393) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1392 -2
  3. package/_dist/admission.d.ts +15 -0
  4. package/_dist/admission.d.ts.map +1 -0
  5. package/_dist/announce.d.ts +17 -0
  6. package/_dist/announce.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +200 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/append.d.ts +10 -0
  10. package/_dist/append.d.ts.map +1 -0
  11. package/_dist/archive.d.ts +6 -0
  12. package/_dist/archive.d.ts.map +1 -0
  13. package/_dist/asks.d.ts +11 -0
  14. package/_dist/asks.d.ts.map +1 -0
  15. package/_dist/audit.d.ts +15 -0
  16. package/_dist/audit.d.ts.map +1 -0
  17. package/_dist/bounce.d.ts +19 -0
  18. package/_dist/bounce.d.ts.map +1 -0
  19. package/_dist/bus.d.ts +8 -0
  20. package/_dist/bus.d.ts.map +1 -0
  21. package/_dist/cache.d.ts +45 -0
  22. package/_dist/cache.d.ts.map +1 -0
  23. package/_dist/child-notice.d.ts +6 -0
  24. package/_dist/child-notice.d.ts.map +1 -0
  25. package/_dist/children.d.ts +59 -0
  26. package/_dist/children.d.ts.map +1 -0
  27. package/_dist/cli.d.ts +8 -0
  28. package/_dist/cli.d.ts.map +1 -0
  29. package/_dist/comp.d.ts +9 -0
  30. package/_dist/comp.d.ts.map +1 -0
  31. package/_dist/compact.d.ts +19 -0
  32. package/_dist/compact.d.ts.map +1 -0
  33. package/_dist/conversation.d.ts +158 -0
  34. package/_dist/conversation.d.ts.map +1 -0
  35. package/_dist/cost.d.ts +13 -0
  36. package/_dist/cost.d.ts.map +1 -0
  37. package/_dist/deferred.d.ts +79 -0
  38. package/_dist/deferred.d.ts.map +1 -0
  39. package/_dist/ended.d.ts +27 -0
  40. package/_dist/ended.d.ts.map +1 -0
  41. package/_dist/files.d.ts +73 -0
  42. package/_dist/files.d.ts.map +1 -0
  43. package/_dist/fork.d.ts +23 -0
  44. package/_dist/fork.d.ts.map +1 -0
  45. package/_dist/graft.d.ts +33 -0
  46. package/_dist/graft.d.ts.map +1 -0
  47. package/_dist/graph.d.ts +14 -0
  48. package/_dist/graph.d.ts.map +1 -0
  49. package/_dist/handoff.d.ts +29 -0
  50. package/_dist/handoff.d.ts.map +1 -0
  51. package/_dist/imported.d.ts +63 -0
  52. package/_dist/imported.d.ts.map +1 -0
  53. package/_dist/intake.d.ts +43 -0
  54. package/_dist/intake.d.ts.map +1 -0
  55. package/_dist/joined.d.ts +35 -0
  56. package/_dist/joined.d.ts.map +1 -0
  57. package/_dist/lease.d.ts +21 -0
  58. package/_dist/lease.d.ts.map +1 -0
  59. package/_dist/lines.d.ts +13 -0
  60. package/_dist/lines.d.ts.map +1 -0
  61. package/_dist/mod.d.ts +107 -0
  62. package/_dist/mod.d.ts.map +1 -0
  63. package/_dist/naming.d.ts +10 -0
  64. package/_dist/naming.d.ts.map +1 -0
  65. package/_dist/native.d.ts +13 -0
  66. package/_dist/native.d.ts.map +1 -0
  67. package/_dist/parts.d.ts +145 -0
  68. package/_dist/parts.d.ts.map +1 -0
  69. package/_dist/plugin.d.ts +33 -0
  70. package/_dist/plugin.d.ts.map +1 -0
  71. package/_dist/project.d.ts +67 -0
  72. package/_dist/project.d.ts.map +1 -0
  73. package/_dist/prose.d.ts +7 -0
  74. package/_dist/prose.d.ts.map +1 -0
  75. package/_dist/providers.d.ts +36 -0
  76. package/_dist/providers.d.ts.map +1 -0
  77. package/_dist/reach.d.ts +39 -0
  78. package/_dist/reach.d.ts.map +1 -0
  79. package/_dist/react.d.ts +236 -0
  80. package/_dist/react.d.ts.map +1 -0
  81. package/_dist/readers.d.ts +221 -0
  82. package/_dist/readers.d.ts.map +1 -0
  83. package/_dist/reap.d.ts +21 -0
  84. package/_dist/reap.d.ts.map +1 -0
  85. package/_dist/recall.d.ts +32 -0
  86. package/_dist/recall.d.ts.map +1 -0
  87. package/_dist/routes.d.ts +15 -0
  88. package/_dist/routes.d.ts.map +1 -0
  89. package/_dist/run.d.ts +81 -0
  90. package/_dist/run.d.ts.map +1 -0
  91. package/_dist/service.d.ts +131 -0
  92. package/_dist/service.d.ts.map +1 -0
  93. package/_dist/source.d.ts +9 -0
  94. package/_dist/source.d.ts.map +1 -0
  95. package/_dist/start.d.ts +29 -0
  96. package/_dist/start.d.ts.map +1 -0
  97. package/_dist/state.d.ts +75 -0
  98. package/_dist/state.d.ts.map +1 -0
  99. package/_dist/status.d.ts +38 -0
  100. package/_dist/status.d.ts.map +1 -0
  101. package/_dist/tail.d.ts +121 -0
  102. package/_dist/tail.d.ts.map +1 -0
  103. package/_dist/timing.d.ts +9 -0
  104. package/_dist/timing.d.ts.map +1 -0
  105. package/_dist/told.d.ts +17 -0
  106. package/_dist/told.d.ts.map +1 -0
  107. package/_dist/tools.d.ts +41 -0
  108. package/_dist/tools.d.ts.map +1 -0
  109. package/_dist/transcript.d.ts +5 -0
  110. package/_dist/transcript.d.ts.map +1 -0
  111. package/_dist/turn.d.ts +49 -0
  112. package/_dist/turn.d.ts.map +1 -0
  113. package/_dist/unknown.d.ts +6 -0
  114. package/_dist/unknown.d.ts.map +1 -0
  115. package/_dist/views.d.ts +9 -0
  116. package/_dist/views.d.ts.map +1 -0
  117. package/_dist/vocab.d.ts +9 -0
  118. package/_dist/vocab.d.ts.map +1 -0
  119. package/_dist/wait.d.ts +15 -0
  120. package/_dist/wait.d.ts.map +1 -0
  121. package/_dist/wake.d.ts +116 -0
  122. package/_dist/wake.d.ts.map +1 -0
  123. package/_dist/watch.d.ts +52 -0
  124. package/_dist/watch.d.ts.map +1 -0
  125. package/_dist/who.d.ts +84 -0
  126. package/_dist/who.d.ts.map +1 -0
  127. package/_dist/window.d.ts +43 -0
  128. package/_dist/window.d.ts.map +1 -0
  129. package/admission.js +137 -0
  130. package/admission.js.map +1 -0
  131. package/admission.ts +164 -0
  132. package/announce.js +123 -0
  133. package/announce.js.map +1 -0
  134. package/announce.ts +126 -0
  135. package/answer.js +372 -0
  136. package/answer.js.map +1 -0
  137. package/answer.ts +426 -0
  138. package/append.js +125 -0
  139. package/append.js.map +1 -0
  140. package/append.ts +205 -0
  141. package/archive.js +62 -0
  142. package/archive.js.map +1 -0
  143. package/archive.ts +62 -0
  144. package/asks.js +80 -0
  145. package/asks.js.map +1 -0
  146. package/asks.ts +106 -0
  147. package/attempt.js +46 -0
  148. package/attempt.js.map +1 -0
  149. package/attempt.ts +60 -0
  150. package/audit.js +57 -0
  151. package/audit.js.map +1 -0
  152. package/audit.ts +65 -0
  153. package/bounce.js +29 -0
  154. package/bounce.js.map +1 -0
  155. package/bounce.ts +34 -0
  156. package/bus.js +568 -0
  157. package/bus.js.map +1 -0
  158. package/bus.ts +683 -0
  159. package/cache.js +169 -0
  160. package/cache.js.map +1 -0
  161. package/cache.ts +230 -0
  162. package/child-notice.js +128 -0
  163. package/child-notice.js.map +1 -0
  164. package/child-notice.ts +136 -0
  165. package/children.js +937 -0
  166. package/children.js.map +1 -0
  167. package/children.ts +925 -0
  168. package/claude-control.js +8 -0
  169. package/claude-control.js.map +1 -0
  170. package/claude-control.ts +12 -0
  171. package/cli.js +23 -0
  172. package/cli.js.map +1 -0
  173. package/cli.ts +28 -0
  174. package/comp.js +76 -0
  175. package/comp.js.map +1 -0
  176. package/comp.ts +78 -0
  177. package/compact.js +157 -0
  178. package/compact.js.map +1 -0
  179. package/compact.ts +209 -0
  180. package/compact_ask.js +280 -0
  181. package/compact_ask.js.map +1 -0
  182. package/compact_ask.ts +199 -0
  183. package/continue.js +131 -0
  184. package/continue.js.map +1 -0
  185. package/continue.ts +143 -0
  186. package/conversation.js +337 -0
  187. package/conversation.js.map +1 -0
  188. package/conversation.ts +593 -0
  189. package/cost.js +111 -0
  190. package/cost.js.map +1 -0
  191. package/cost.ts +93 -0
  192. package/deferred.js +207 -0
  193. package/deferred.js.map +1 -0
  194. package/deferred.ts +219 -0
  195. package/deno.json +1 -0
  196. package/dependencies.js +114 -0
  197. package/dependencies.js.map +1 -0
  198. package/dependencies.ts +110 -0
  199. package/draining.js +20 -0
  200. package/draining.js.map +1 -0
  201. package/draining.ts +26 -0
  202. package/ended.js +210 -0
  203. package/ended.js.map +1 -0
  204. package/ended.ts +225 -0
  205. package/files.js +285 -0
  206. package/files.js.map +1 -0
  207. package/files.ts +318 -0
  208. package/fork.js +96 -0
  209. package/fork.js.map +1 -0
  210. package/fork.ts +124 -0
  211. package/graft.js +97 -0
  212. package/graft.js.map +1 -0
  213. package/graft.ts +88 -0
  214. package/graph.js +49 -0
  215. package/graph.js.map +1 -0
  216. package/graph.ts +61 -0
  217. package/handoff.js +111 -0
  218. package/handoff.js.map +1 -0
  219. package/handoff.ts +147 -0
  220. package/help.js +432 -0
  221. package/help.js.map +1 -0
  222. package/help.ts +431 -0
  223. package/hooks.js +253 -0
  224. package/hooks.js.map +1 -0
  225. package/hooks.ts +333 -0
  226. package/imported.js +259 -0
  227. package/imported.js.map +1 -0
  228. package/imported.ts +201 -0
  229. package/inspect.js +353 -0
  230. package/inspect.js.map +1 -0
  231. package/inspect.ts +378 -0
  232. package/intake.js +115 -0
  233. package/intake.js.map +1 -0
  234. package/intake.ts +124 -0
  235. package/joined.js +67 -0
  236. package/joined.js.map +1 -0
  237. package/joined.ts +69 -0
  238. package/lease.js +146 -0
  239. package/lease.js.map +1 -0
  240. package/lease.ts +151 -0
  241. package/lifecycle.js +49 -0
  242. package/lifecycle.js.map +1 -0
  243. package/lifecycle.ts +46 -0
  244. package/lines.js +171 -0
  245. package/lines.js.map +1 -0
  246. package/lines.ts +177 -0
  247. package/listen.js +604 -0
  248. package/listen.js.map +1 -0
  249. package/listen.ts +976 -0
  250. package/log.js +78 -0
  251. package/log.js.map +1 -0
  252. package/log.ts +88 -0
  253. package/mod.js +107 -0
  254. package/mod.js.map +1 -0
  255. package/mod.ts +113 -0
  256. package/name.js +51 -0
  257. package/name.js.map +1 -0
  258. package/name.ts +84 -0
  259. package/naming.js +96 -0
  260. package/naming.js.map +1 -0
  261. package/naming.ts +102 -0
  262. package/native.js +17 -0
  263. package/native.js.map +1 -0
  264. package/native.ts +17 -0
  265. package/package.json +133 -4
  266. package/parts.js +334 -0
  267. package/parts.js.map +1 -0
  268. package/parts.ts +383 -0
  269. package/plugin.js +77 -0
  270. package/plugin.js.map +1 -0
  271. package/plugin.ts +98 -0
  272. package/project.js +354 -0
  273. package/project.js.map +1 -0
  274. package/project.ts +407 -0
  275. package/prompt.js +57 -0
  276. package/prompt.js.map +1 -0
  277. package/prompt.ts +92 -0
  278. package/prose.js +43 -0
  279. package/prose.js.map +1 -0
  280. package/prose.ts +63 -0
  281. package/providers.js +279 -0
  282. package/providers.js.map +1 -0
  283. package/providers.ts +306 -0
  284. package/pruning.js +80 -0
  285. package/pruning.js.map +1 -0
  286. package/pruning.ts +147 -0
  287. package/reach.js +923 -0
  288. package/reach.js.map +1 -0
  289. package/reach.ts +1107 -0
  290. package/react.js +2259 -0
  291. package/react.js.map +1 -0
  292. package/react.ts +2864 -0
  293. package/readers.js +956 -0
  294. package/readers.js.map +1 -0
  295. package/readers.ts +1017 -0
  296. package/reap.js +60 -0
  297. package/reap.js.map +1 -0
  298. package/reap.ts +65 -0
  299. package/recall.js +67 -0
  300. package/recall.js.map +1 -0
  301. package/recall.ts +114 -0
  302. package/reopen.js +45 -0
  303. package/reopen.js.map +1 -0
  304. package/reopen.ts +44 -0
  305. package/result-entry.js +32 -0
  306. package/result-entry.js.map +1 -0
  307. package/result-entry.ts +34 -0
  308. package/resume.js +266 -0
  309. package/resume.js.map +1 -0
  310. package/resume.ts +283 -0
  311. package/routes.js +129 -0
  312. package/routes.js.map +1 -0
  313. package/routes.ts +147 -0
  314. package/routine.js +179 -0
  315. package/routine.js.map +1 -0
  316. package/routine.ts +191 -0
  317. package/run.js +932 -0
  318. package/run.js.map +1 -0
  319. package/run.ts +999 -0
  320. package/service.js +806 -0
  321. package/service.js.map +1 -0
  322. package/service.ts +911 -0
  323. package/source.js +26 -0
  324. package/source.js.map +1 -0
  325. package/source.ts +40 -0
  326. package/start.js +197 -0
  327. package/start.js.map +1 -0
  328. package/start.ts +214 -0
  329. package/state.js +247 -0
  330. package/state.js.map +1 -0
  331. package/state.ts +404 -0
  332. package/status.js +1222 -0
  333. package/status.js.map +1 -0
  334. package/status.ts +1555 -0
  335. package/status_bench.ts +50 -0
  336. package/statusline.js +187 -0
  337. package/statusline.js.map +1 -0
  338. package/statusline.ts +232 -0
  339. package/tail.js +748 -0
  340. package/tail.js.map +1 -0
  341. package/tail.ts +815 -0
  342. package/talk.js +58 -0
  343. package/talk.js.map +1 -0
  344. package/talk.ts +51 -0
  345. package/task-context.js +41 -0
  346. package/task-context.js.map +1 -0
  347. package/task-context.ts +53 -0
  348. package/texted.js +65 -0
  349. package/texted.js.map +1 -0
  350. package/texted.ts +65 -0
  351. package/timing.js +37 -0
  352. package/timing.js.map +1 -0
  353. package/timing.ts +52 -0
  354. package/told.js +56 -0
  355. package/told.js.map +1 -0
  356. package/told.ts +54 -0
  357. package/tools.js +595 -0
  358. package/tools.js.map +1 -0
  359. package/tools.ts +633 -0
  360. package/transcript.js +34 -0
  361. package/transcript.js.map +1 -0
  362. package/transcript.ts +41 -0
  363. package/turn.js +47 -0
  364. package/turn.js.map +1 -0
  365. package/turn.ts +68 -0
  366. package/unknown.js +8 -0
  367. package/unknown.js.map +1 -0
  368. package/unknown.ts +9 -0
  369. package/views.js +15 -0
  370. package/views.js.map +1 -0
  371. package/views.ts +21 -0
  372. package/vocab.js +24 -0
  373. package/vocab.js.map +1 -0
  374. package/vocab.json +1573 -0
  375. package/vocab.ts +30 -0
  376. package/wait.js +30 -0
  377. package/wait.js.map +1 -0
  378. package/wait.ts +45 -0
  379. package/wake.js +552 -0
  380. package/wake.js.map +1 -0
  381. package/wake.ts +597 -0
  382. package/watch.js +520 -0
  383. package/watch.js.map +1 -0
  384. package/watch.ts +596 -0
  385. package/who.js +309 -0
  386. package/who.js.map +1 -0
  387. package/who.ts +347 -0
  388. package/window.js +179 -0
  389. package/window.js.map +1 -0
  390. package/window.ts +268 -0
  391. package/woken.js +129 -0
  392. package/woken.js.map +1 -0
  393. package/woken.ts +127 -0
package/help.ts ADDED
@@ -0,0 +1,431 @@
1
+ // A project's helper: the run that takes what waits for its operator, so the
2
+ // operator's own session, with its whole context, is not woken for it.
3
+ //
4
+ // ./routine.ts marks a knock `routine{project}` in the write that leaves it.
5
+ // `session_help` runs after that commit and starts the helper: one session
6
+ // wearing the project's `helper{persona}`, marked `helping{project}`, whose
7
+ // first input is every routine knock waiting, each said whole as a listener
8
+ // would say it and marked `notified` in the same write. That input carries
9
+ // `using`, so the run is started the way any is: by whatever answers a
10
+ // `using` (@yaks/spawn for a command-line provider).
11
+ //
12
+ // One helper is at work at a time, and it takes everything waiting, so a
13
+ // storm of bugs is one helper's batch. Knocks that come while it works wait
14
+ // for its `exit`, which asks again, and the helper is over from then on, so
15
+ // nothing it was told of wakes it again. Two workers racing to start one read the
16
+ // same waiting knocks, and the guard on each knock's `notified` lets one
17
+ // write through.
18
+ //
19
+ // Only a hand-up reaches the operator: a knock written through a helper,
20
+ // which ./routine.ts leaves unmarked. The helper writes its own with
21
+ // `session_handup` ({@link handed}), and so does a session opened on a topic,
22
+ // which is no helper and has no other way to reach another session. This file
23
+ // writes two, each naming what the helper had taken: one that ended badly,
24
+ // and one the next routine item stops because it said nothing for
25
+ // {@link QUIET} or was still going after {@link LIMIT}. A run that has said
26
+ // its last words can linger for good on a background command it started, and
27
+ // everything behind it would wait.
28
+ //
29
+ // A run's ending and a task's mark are not routine to the session that
30
+ // started the run or watches the task, only their reading is. When a helper
31
+ // exits, each task it took one for reaches that session as one line: the
32
+ // task, its verdict as the helper leaves it (done, cancelled, stopped for a
33
+ // run somebody asked to stop, ended early for one that otherwise did not end
34
+ // cleanly, or not ready), and the report's id.
35
+ //
36
+ // The helpers' trail is `.helping.project=<project>`: each session, with what
37
+ // it wrote under `.created.via=<session>` and the knocks it took under
38
+ // `.notified.via=<session>`.
39
+
40
+ import type { Bundle, Comp, Eid, Graph } from '@yaks/graph'
41
+ import { mint } from '@yaks/graph'
42
+ import { Stale } from '@yaks/graph/errors'
43
+ import { derivedEid } from '@yaks/graph/identity'
44
+ import { signed } from '@yaks/graph/provenance'
45
+ import { token } from '@yaks/graph/sha256'
46
+ import { human } from '@yaks/id'
47
+ import { absent, and, eq, every, fields, line, present } from '@yaks/query'
48
+ import { SESSION } from './comp.js'
49
+ import { ended as over, type Owed, owing, worksFor } from './listen.js'
50
+ import { HELPER, HELPING, ROUTINE } from './routine.js'
51
+ import { operatorOf } from './watch.js'
52
+ import { STOP_ENTRY } from './native.js'
53
+ import { cleanEnd } from './wake.js'
54
+ import { settled, statusOf } from '@yaks/task'
55
+
56
+ type G = Pick<Graph, 'vocab' | 'read' | 'get' | 'apply'>
57
+
58
+ /** How long a helper may go on before the next routine item stops it and
59
+ * starts another (ms). */
60
+ export let LIMIT = 30 * 60_000
61
+
62
+ /** How long a helper may say nothing, its transcript gaining no entry, before
63
+ * the next routine item stops it and starts another (ms). */
64
+ export let QUIET = 5 * 60_000
65
+
66
+ /** What a test holds still: the clock, {@link LIMIT} and {@link QUIET}. */
67
+ export type Opts = { now?: () => number; limit?: number; quiet?: number }
68
+
69
+ let comp = (b: Bundle | undefined, name: string): Comp =>
70
+ (b?.[name] ?? {}) as Comp
71
+ let str = (v: unknown): string => typeof v == 'string' ? v : ''
72
+ let s = (n: number) => n == 1 ? '' : 's'
73
+ let unique = (ids: string[]): Eid[] => [...new Set(ids.filter(Boolean))]
74
+
75
+ // A turn the model or a tool owes an answer: a helper not yet launched.
76
+ let WORKING = ['pending', 'running']
77
+
78
+ /** The routine knocks and letters waiting for a project's helper. */
79
+ export let waiting = (g: G, project: Eid): Promise<Bundle[]> =>
80
+ Promise.resolve(g.read(and(
81
+ eq(`${ROUTINE}.project`, project),
82
+ absent('notified'),
83
+ every(),
84
+ )))
85
+
86
+ // Who hears a project's hand-up: its operator while one can hear, else the
87
+ // project, where it waits for the next session a person opens.
88
+ let hears = async (g: G, project: Eid): Promise<Eid> =>
89
+ await operatorOf(g, project) ?? project
90
+
91
+ /** The knock `session` hands up with: one line at the operator of the project
92
+ * it works for (a helper's `helping.project`, else the home of the persona it
93
+ * wears), led by the id of the entity it concerns. The door writes it through
94
+ * that session, which is what makes it a hand-up for a helper and for a
95
+ * session opened on a topic (./routine.ts). None where the session works for
96
+ * no project. */
97
+ export let handed = async (
98
+ g: G,
99
+ session: Eid,
100
+ about: Eid,
101
+ line: string,
102
+ ): Promise<Bundle | undefined> => {
103
+ let [from] = await g.get([session], [HELPING, SESSION])
104
+ let project = str(comp(from, HELPING).project) ||
105
+ (await worksFor(g, from))[0]
106
+ if (!project) return
107
+ let [concerns] = await g.get([about])
108
+ return {
109
+ entity: { eid: '$knock' },
110
+ knock: { target: await hears(g, project), about },
111
+ doc: { body: `${human(g.vocab)(concerns)}: ${line.trim()}` },
112
+ }
113
+ }
114
+
115
+ // A knock at the operator written through `helper`, which makes it a hand-up
116
+ // (./routine.ts). Named for what it tells, so a run again tells it once.
117
+ let handUp = async (
118
+ g: G,
119
+ helper: Bundle,
120
+ key: string,
121
+ body: string,
122
+ to?: Eid,
123
+ ) => {
124
+ to ??= await hears(g, str(comp(helper, HELPING).project))
125
+ try {
126
+ await g.apply(
127
+ signed([{
128
+ entity: {
129
+ eid: derivedEid(`session help ${key} ${helper.entity.eid}`),
130
+ },
131
+ knock: { target: to },
132
+ doc: { body },
133
+ $was: { knock: { target: null } },
134
+ }], { via: helper.entity.eid }),
135
+ { trusted: true },
136
+ )
137
+ } catch (error) {
138
+ if (!(error instanceof Stale)) throw error
139
+ }
140
+ }
141
+
142
+ // What a helper had taken, as the ids a reader looks them up by.
143
+ let taken = async (g: G, helper: Eid): Promise<string> => {
144
+ let held = await g.read(and(
145
+ present(ROUTINE),
146
+ eq('notified.via', helper),
147
+ every(),
148
+ ))
149
+ return held.length
150
+ ? `${held.length} taken and maybe not handled: ` +
151
+ held.map(human(g.vocab)).join(', ')
152
+ : 'nothing taken'
153
+ }
154
+
155
+ // The helpers of a project that are not over: no `exit`, nobody asked to
156
+ // stop, not `session.ended`, and a process running or a first turn still
157
+ // owed. A native helper ends with `session.ended` and never an `exit`, so
158
+ // without that test every helper the project ever had is read and its
159
+ // status computed from its transcript.
160
+ let going = async (g: G, project: Eid): Promise<Bundle[]> => {
161
+ let has = (name: string) => !!g.vocab.comp(name)
162
+ let rows = await g.read(and(
163
+ eq(`${HELPING}.project`, project),
164
+ ...['exit', 'stop'].filter(has).map((name) => absent(name)),
165
+ absent(`${SESSION}.ended`),
166
+ fields(
167
+ `${HELPING}.project`,
168
+ 'created.at',
169
+ `${SESSION}.status`,
170
+ ...has('process') ? ['process.pid'] : [],
171
+ ),
172
+ ))
173
+ return rows.filter((b) =>
174
+ b.process || WORKING.includes(str(comp(b, SESSION).status))
175
+ )
176
+ }
177
+
178
+ // A transcript's newest entry.
179
+ let newest = async (g: G, session: Eid): Promise<Bundle | undefined> =>
180
+ (await g.read(line`.entry.session=${session}&.order=-entry.seq&.limit=1&*`))[
181
+ 0
182
+ ]
183
+
184
+ let fold = (text: string, max: number): string => {
185
+ let line = text.replace(/\s+/g, ' ').trim()
186
+ return line.length > max ? `${line.slice(0, max)}…` : line
187
+ }
188
+
189
+ // Whether a helper is at work for the project. One that said nothing for
190
+ // `quiet`, or is past the limit, is asked to stop and handed up with its last
191
+ // words, and does not count: what waits behind it would otherwise wait for
192
+ // good.
193
+ let atWork = async (g: G, project: Eid, o: Opts): Promise<boolean> => {
194
+ let now = (o.now ?? Date.now)()
195
+ let limit = o.limit ?? LIMIT, quiet = o.quiet ?? QUIET
196
+ let since = (b: Bundle | undefined) =>
197
+ now - Date.parse(str(comp(b, 'created').at))
198
+ let min = (ms: number) => Math.round(ms / 60_000)
199
+ let busy = false
200
+ for (let b of await going(g, project)) {
201
+ let last = await newest(g, b.entity.eid)
202
+ let over = since(b) >= limit
203
+ if (!over && since(last ?? b) < quiet) {
204
+ busy = true
205
+ continue
206
+ }
207
+ await g.apply([{ entity: { eid: b.entity.eid }, stop: {} }])
208
+ let words = last?.output ? fold(str(comp(last, 'content').body), 200) : ''
209
+ await handUp(
210
+ g,
211
+ b,
212
+ 'overdue',
213
+ `helper ${human(g.vocab)(b)} ` +
214
+ (over
215
+ ? `was still going after ${min(limit)} min`
216
+ : `said nothing for ${min(quiet)} min`) +
217
+ ` and was stopped, with ${await taken(g, b.entity.eid)}` +
218
+ (words ? `. Its last words: ${words}` : ''),
219
+ )
220
+ }
221
+ return busy
222
+ }
223
+
224
+ // What a helper is told: whose place it takes, how to hand up, and each
225
+ // waiting knock whole. How each kind is handled is its persona's to say.
226
+ let brief = (g: G, home: Bundle, owed: Owed[]): string => {
227
+ let name = human(g.vocab)
228
+ let project = [name(home), str(comp(home, 'doc').title)].filter(Boolean)
229
+ .join(' ')
230
+ return [
231
+ `You are the helper of ${project}'s operator. ${owed.length} ` +
232
+ `item${s(owed.length)} arrived for the operator and ${
233
+ owed.length == 1 ? 'is' : 'are'
234
+ } yours to handle. Record your work in the graph and keep the named actor ` +
235
+ "when passing on a decision. Hand up only what needs the operator's judgment or a " +
236
+ 'person, as one short line about the entity it concerns, with ' +
237
+ '`session_handup`. When handing up a scheduled wake, carry forward its ' +
238
+ 'firing date and the conditions in its note.',
239
+ ...owed.map((o) => o.line),
240
+ ].join('\n\n')
241
+ }
242
+
243
+ /** Start the project's helper on everything waiting for it, unless one is at
244
+ * work or nothing waits. A project that no longer wears `helper`, or whose
245
+ * `helper` names no provider, gives what waits back to its operator. */
246
+ export let take = async (g: G, project: Eid, o: Opts = {}): Promise<void> => {
247
+ // Read what waits before asking who is at work: two workers that both find
248
+ // nobody at work then hold a knock in common, and its guard lets one write.
249
+ let knocks = await waiting(g, project)
250
+ if (!knocks.length) return
251
+ let [home] = await g.get([project])
252
+ let { persona, provider, model, effort } = comp(home, HELPER)
253
+ if (!provider) {
254
+ await g.apply(
255
+ knocks.map((b) => ({ entity: { eid: b.entity.eid }, [ROUTINE]: null })),
256
+ { trusted: true },
257
+ )
258
+ return
259
+ }
260
+ if (await atWork(g, project, o)) return
261
+ let owed = await owing(g, knocks)
262
+ let session = mint()
263
+ let by = persona ? { by: str(persona) } : {}
264
+ let said = (b: Bundle, guarded: boolean): Bundle => ({
265
+ entity: { eid: b.entity.eid },
266
+ notified: {},
267
+ ...guarded ? { $was: { notified: { at: token(null) } } } : {},
268
+ $actor: { ...by, via: session },
269
+ })
270
+ try {
271
+ await g.apply([
272
+ {
273
+ entity: { eid: session },
274
+ [SESSION]: { operator: false, ...persona ? { persona } : {} },
275
+ [HELPING]: { project },
276
+ // The native harness answers it, isolated as every session outside
277
+ // words start is (@yaks/harness/isolated), never an outside CLI
278
+ // holding the box's shell. No `spawned` link: its ending is this
279
+ // file's to tell, and would otherwise wake the operator.
280
+ ...g.vocab.comp('native') ? { native: {} } : {},
281
+ $actor: by,
282
+ },
283
+ {
284
+ entity: { eid: mint() },
285
+ entry: { session },
286
+ content: { body: brief(g, home, owed) },
287
+ using: {
288
+ provider,
289
+ ...model ? { model } : {},
290
+ ...effort ? { effort } : {},
291
+ },
292
+ $actor: by,
293
+ },
294
+ ...owed.flatMap(({ item, same }) => [
295
+ said(item, true),
296
+ ...same.map((b) => said(b, false)),
297
+ ]),
298
+ ], { trusted: true })
299
+ } catch (error) {
300
+ // Another worker's helper took one of these first: its exit asks again
301
+ // for whatever it did not take.
302
+ if (!(error instanceof Stale)) throw error
303
+ }
304
+ }
305
+
306
+ // A helper that ended any way but cleanly, when nobody asked it to stop, is
307
+ // handed up with what it had taken.
308
+ let ended = async (g: G, helper: Bundle): Promise<void> => {
309
+ let code = comp(helper, 'exit').code
310
+ if (code === 0 || helper.stop) return
311
+ // A native helper has no exit: its transcript's status says how it ended.
312
+ let status = str(comp(helper, SESSION).status)
313
+ if (!helper.exit && status == 'settled') return
314
+ await handUp(
315
+ g,
316
+ helper,
317
+ 'ended',
318
+ `helper ${human(g.vocab)(helper)} ` +
319
+ `${
320
+ !helper.exit
321
+ ? status
322
+ : code == null
323
+ ? 'ended with no exit code'
324
+ : `exited ${code}`
325
+ }, with ` +
326
+ await taken(g, helper.entity.eid),
327
+ )
328
+ }
329
+
330
+ // A helper whose work is done is over at once, not after the quiet that ends
331
+ // a session with no process to ask about (./ended.ts): until then it watches
332
+ // every task it was told of or spoke of, and each change to one would knock it
333
+ // awake to check work its operator hears of anyway (./watch.ts `targets`).
334
+ // An observation, as ./ended.ts writes it, so `updated` stays as it was.
335
+ let rest = (g: G, helper: Eid) =>
336
+ g.apply([{ entity: { eid: helper }, [SESSION]: { ended: true } }], {
337
+ trusted: true,
338
+ stamp: false,
339
+ })
340
+
341
+ // Where a taken item's line goes: the session it knocked while that can still
342
+ // hear, else the operator.
343
+ let hearer = async (g: G, item: Bundle): Promise<Eid | undefined> => {
344
+ let to = str(comp(item, 'knock').target)
345
+ let [row] = to ? await g.get([to], [SESSION]) : []
346
+ return row?.[SESSION] && !(await over(g, [row])).has(to) ? to : undefined
347
+ }
348
+
349
+ // The verdict on a task as a helper leaves it: settled; for a run somebody
350
+ // asked to stop, stopped; for one that did not end cleanly otherwise, ended
351
+ // early; and otherwise not ready.
352
+ let verdict = (status: string | null, run?: Bundle): string => {
353
+ if (status == 'done' || status == 'cancelled') return status
354
+ if (run?.[STOP_ENTRY]) return 'stopped'
355
+ return run && !cleanEnd(run) ? 'ended early' : 'not ready'
356
+ }
357
+
358
+ // Each task a helper took a run's ending (its report, a comment on the task)
359
+ // or a mark for, as one line to whoever it knocked. A comment anyone else
360
+ // wrote stays the helper's.
361
+ let verdicts = async (g: G, helper: Bundle): Promise<void> => {
362
+ let has = (name: string) => !!g.vocab.comp(name)
363
+ if (!has('task')) return
364
+ let held = await g.read(and(
365
+ present(ROUTINE),
366
+ present('knock'),
367
+ eq('notified.via', helper.entity.eid),
368
+ every(),
369
+ ))
370
+ let ran = (b: Bundle) => b.comment ? str(comp(b, 'comment').target) : ''
371
+ let marked = (b: Bundle) => b.comment ? '' : str(comp(b, 'knock').about)
372
+ let about = unique(held.map((b) => ran(b) || marked(b)))
373
+ if (!about.length) return
374
+ let tasks = new Map(
375
+ (await g.get(about)).filter((b) => b.task).map((b) => [b.entity.eid, b]),
376
+ )
377
+ let name = human(g.vocab)
378
+ let seen = new Set<Eid>()
379
+ // A run's report first: where a run and a mark tell of one task, the line
380
+ // names the report.
381
+ for (let item of [...held.filter(ran), ...held.filter((b) => !ran(b))]) {
382
+ let report = ran(item)
383
+ let task = tasks.get(report || marked(item))
384
+ if (!task || seen.has(task.entity.eid)) continue
385
+ let via = report ? str(comp(item, 'created').via) : ''
386
+ let [run] = via
387
+ ? await g.get([via], ['process', 'exit', STOP_ENTRY].filter(has))
388
+ : []
389
+ let status = statusOf(g.vocab, task)
390
+ if (report ? !run?.process || !run.exit : !settled(status)) continue
391
+ seen.add(task.entity.eid)
392
+ let title = fold(str(comp(task, 'doc').title), 80)
393
+ await handUp(
394
+ g,
395
+ helper,
396
+ `told ${task.entity.eid}`,
397
+ `${name(task)} ${verdict(status, run)}` +
398
+ (title ? `: ${title}` : '') +
399
+ (report ? ` (report ${name(item)})` : ''),
400
+ await hearer(g, item),
401
+ )
402
+ }
403
+ }
404
+
405
+ /** The code behind `session_help`, for the entity a commit moved: a routine
406
+ * knock, a helper that exited or whose native transcript ended (./run.ts
407
+ * tells that), or a project whose `helper` went. */
408
+ export let help = async (g: G, eid: Eid, o: Opts = {}): Promise<void> => {
409
+ let has = (name: string) => !!g.vocab.comp(name)
410
+ let [row] = await g.get(
411
+ [eid],
412
+ [ROUTINE, HELPING, 'project', 'exit', 'stop', 'native'].filter(has),
413
+ )
414
+ if (!row) return
415
+ // A native helper's status is computed from its transcript, which a get
416
+ // does not read.
417
+ if (row[HELPING] && row.native) {
418
+ let [read] = await g.read(line`.entity.eid=${eid}&.fields=session.status`)
419
+ row = { ...row, [SESSION]: comp(read, SESSION) }
420
+ }
421
+ let finished = row.native &&
422
+ ['settled', 'failed', 'stopped'].includes(str(comp(row, SESSION).status))
423
+ if (row[HELPING] && (row.exit || finished)) {
424
+ await rest(g, eid)
425
+ await ended(g, row)
426
+ await verdicts(g, row)
427
+ }
428
+ let project = str(comp(row, ROUTINE).project) ||
429
+ str(comp(row, HELPING).project) || (row.project ? eid : '')
430
+ if (project) await take(g, project, o)
431
+ }
package/hooks.js ADDED
@@ -0,0 +1,253 @@
1
+ // Lifecycle commands post to the running server, preserving its JSON stdout.
2
+ // Claude Code does not support HTTP SessionStart hooks. A small shell command
3
+ // keeps its additionalContext and retries through the local CLI on failure.
4
+ // The harness transcript remains the source of turns (./service.ts).
5
+ //
6
+ // The MCP connection names its session on every call it makes (`connection`),
7
+ // so a write is stamped with its caller whether or not that call's hook ever
8
+ // arrives. The `PreToolUse` hook still says which subagent made a call, which
9
+ // one connection serving a session and all its subagents cannot
10
+ // (./announce.ts).
11
+ import * as fs from "@yaks/file/io";
12
+ import * as systemProcess from "@yaks/process/system";
13
+ import { accountHome } from "@yaks/model";
14
+ import { served } from "@yaks/api/address";
15
+ import { PATH, STATUS } from "./routes.js";
16
+ /** The Claude Code plugin that carries these hooks and the MCP connection
17
+ * (plugins/yak), as an account's settings enable it: its name, then its
18
+ * marketplace's. */ export let PLUGIN = 'yak@yak';
19
+ // The Claude Code account this process signs in with (@yaks/model).
20
+ let own = ()=>accountHome('claude', (name)=>systemProcess.env.get(name)) ?? '.claude';
21
+ /** Where a Claude Code account (its directory, this process's by default)
22
+ * keeps the MCP servers of every project: the default account beside its
23
+ * directory, in `~/.claude.json`, and any other inside it. */ export let configPath = (account = own(), home = systemProcess.env.get('HOME'))=>account == `${home}/.claude` ? `${home}/.claude.json` : `${account}/.claude.json`;
24
+ /** The local client for the MCP door of the `yak serve` at `server`. */ export let connection = (server, yak = 'yak')=>({
25
+ type: 'stdio',
26
+ command: yak,
27
+ args: [
28
+ 'mcp',
29
+ '--host',
30
+ server.replace(/\/+$/, '')
31
+ ]
32
+ });
33
+ // One door, however its host is spelled: `localhost` and `127.0.0.1` are the
34
+ // same server to everyone on this machine.
35
+ let LOOPBACK = [
36
+ 'localhost',
37
+ '127.0.0.1',
38
+ '[::1]'
39
+ ];
40
+ let door = (url)=>{
41
+ if (typeof url != 'string' || !URL.canParse(url)) return;
42
+ let u = new URL(url);
43
+ let host = LOOPBACK.includes(u.hostname) ? 'loopback' : u.hostname;
44
+ return `${u.protocol}//${host}:${u.port}${u.pathname.replace(/\/+$/, '')}`;
45
+ };
46
+ let connectedDoor = (entry)=>{
47
+ if (entry.url) return door(entry.url);
48
+ let args = entry.args ?? [];
49
+ let host = args.indexOf('--host');
50
+ return entry.command && args[0] == 'mcp' && host >= 0 ? door(`${args[host + 1]?.replace(/\/+$/, '')}/mcp`) : undefined;
51
+ };
52
+ /**
53
+ * Write the connection into Claude Code's config, keeping everything else in
54
+ * it: the first entry already on this door is replaced under its own name and
55
+ * any other on it taken out, else it is added as `name`. `remove` takes them
56
+ * all out. Answers the name it is under.
57
+ */ export let connect = (path, opts)=>{
58
+ let config = {};
59
+ try {
60
+ config = JSON.parse(fs.readTextFileSync(path));
61
+ } catch (e) {
62
+ if (!fs.isNotFound(e)) throw e;
63
+ }
64
+ let entry = connection(opts.server, opts.yak);
65
+ let servers = {
66
+ ...config.mcpServers
67
+ };
68
+ let ours = Object.keys(servers).filter((n)=>connectedDoor(servers[n]) == connectedDoor(entry));
69
+ let name = ours[0] ?? opts.name ?? 'yak';
70
+ for (let n of ours)delete servers[n];
71
+ if (!opts.remove) servers[name] = entry;
72
+ fs.writeTextFileSync(path, `${JSON.stringify({
73
+ ...config,
74
+ mcpServers: servers
75
+ }, null, 2)}\n`);
76
+ return name;
77
+ };
78
+ /** Where the entries go for a Claude Code account, this process's by
79
+ * default, unless the caller names another path. */ export let settingsPath = (account = own())=>`${account}/settings.json`;
80
+ let cmd = (command, timeout)=>({
81
+ hooks: [
82
+ {
83
+ type: 'command',
84
+ command,
85
+ ...timeout == null ? {} : {
86
+ timeout
87
+ }
88
+ }
89
+ ]
90
+ });
91
+ // A hook posted to a server: a server that is down costs the harness the
92
+ // timeout and nothing else.
93
+ let post = (url, matcher)=>({
94
+ ...matcher ? {
95
+ matcher
96
+ } : {},
97
+ hooks: [
98
+ {
99
+ type: 'http',
100
+ url,
101
+ timeout: 2
102
+ }
103
+ ]
104
+ });
105
+ // Keep a failed/partial HTTP response out of stdout before trying the CLI, if
106
+ // there is one to try. `door` is a shell word.
107
+ let quote = (s)=>"'" + s.replaceAll("'", "'\"'\"'") + "'";
108
+ let relay = (door, fallback, timeout)=>cmd('payload=$(cat); ' + 'via=${CLAUDE_CODE_SESSION_ID:-${TASKS_SESSION:-${CODEX_THREAD_ID:-}}}; ' + 'case "${CLAUDE_CODE_SESSION_ID:+${AI_AGENT:-}}" in *_agent) ' + 'case "$PWD" in */.claude/worktrees/agent-*) ' + 'agent=${PWD##*/.claude/worktrees/agent-}; agent=${agent%%/*}; ' + 'case "$agent" in \'\'|*[!0-9a-f]*) ;; *) via=$agent ;; esac ;; esac ;; esac; ' + 'if answer=$(printf %s "$payload" | curl --fail --silent ' + '--connect-timeout 0.1 --max-time 2 ' + '--header "x-via: $via" ' + "--header 'content-type: application/json' --data-binary @- " + door + '); then printf \'%s\\n\' "$answer"; ' + (fallback ? `else printf %s "$payload" | ${fallback} || true; fi` : 'fi'), timeout);
109
+ // The entries, posting to the hook door at `door`: a URL, or a shell word
110
+ // that names it, where every entry is then a command (a plugin's hooks read
111
+ // its options from their environment, which an HTTP hook's URL cannot).
112
+ let entries = (door, yak)=>{
113
+ let word = 'url' in door ? quote(door.url) : door.word;
114
+ let send = (matcher)=>'url' in door ? post(door.url, matcher) : {
115
+ ...matcher ? {
116
+ matcher
117
+ } : {},
118
+ ...relay(word)
119
+ };
120
+ return {
121
+ SessionStart: [
122
+ relay(word, `${yak} session context --hook -`)
123
+ ],
124
+ SubagentStart: [
125
+ relay(word, `${yak} session context --hook -`)
126
+ ],
127
+ UserPromptSubmit: [
128
+ relay(word, `${yak} session context --hook -`, 5)
129
+ ],
130
+ PreToolUse: [
131
+ send('mcp__.*')
132
+ ],
133
+ PostToolUse: [
134
+ send()
135
+ ],
136
+ Stop: [
137
+ send()
138
+ ],
139
+ SessionEnd: [
140
+ relay(word, `${yak} session wrap --hook -`, 5)
141
+ ]
142
+ };
143
+ };
144
+ /**
145
+ * The entries this package owns, keyed by the harness event each responds to.
146
+ *
147
+ * `server` is the origin of the `yak serve` the hook door is on. `yak` is the
148
+ * path to the command on this machine — a full path where it is not on the
149
+ * harness's path.
150
+ */ export let lifecycle = (server, yak = 'yak')=>entries({
151
+ url: `${server.replace(/\/+$/, '')}${PATH}`
152
+ }, yak);
153
+ /** The plugin's option naming the `yak serve` its hooks and MCP connection
154
+ * reach, as its hooks read it from their environment. */ export let SERVER = 'CLAUDE_PLUGIN_OPTION_SERVER';
155
+ /** The same entries as the plugin carries them (plugins/yak/hooks/hooks.json):
156
+ * the door is the server its `server` option names, else the one `yak serve`
157
+ * listens at by default. */ export let pluginHooks = (yak = 'yak')=>entries({
158
+ word: `"\${${SERVER}:-${served({})}}"${PATH}`
159
+ }, yak);
160
+ /** The status line entry: Claude Code hands what it knows to the server's
161
+ * status door, which keeps the plan readings and answers the line
162
+ * (./statusline.ts). A server that is down leaves the line empty. */ export let statusLine = (server)=>({
163
+ type: 'command',
164
+ command: 'curl --fail --silent --connect-timeout 0.1 --max-time 1 ' + "--header 'content-type: application/json' --data-binary @- " + quote(`${server.replace(/\/+$/, '')}${STATUS}`),
165
+ padding: 0
166
+ });
167
+ let ourLine = (line)=>String(line?.command ?? '').includes(STATUS);
168
+ // Ours, identified by the command it runs or the door it posts to, including
169
+ // the turn hooks an older install wrote (`session/turn.ts`), which an install
170
+ // now takes out. A person's own entry never runs either.
171
+ let MINE = /\byak\b.*\bsession (context|wrap) --hook\b|\bsession\b\S*\/turn\.ts\b/;
172
+ let mine = (h)=>(h?.hooks ?? []).some((x)=>!!x?.url?.endsWith(PATH) || MINE.test(x?.command ?? ''));
173
+ /**
174
+ * The lifecycle entries merged into the hooks a settings file already had:
175
+ * ours lead each event, everything else follows, and an earlier install of
176
+ * ours is replaced rather than doubled. `gone` removes ours and keeps the
177
+ * rest.
178
+ */ export let merged = (had, add, gone = false)=>{
179
+ let out = {};
180
+ for (let event of new Set([
181
+ ...Object.keys(had ?? {}),
182
+ ...Object.keys(add)
183
+ ])){
184
+ let was = had?.[event];
185
+ let kept = (Array.isArray(was) ? was : []).filter((h)=>!mine(h));
186
+ let ours = gone ? [] : add[event] ?? [];
187
+ if (kept.length || ours.length) out[event] = [
188
+ ...ours,
189
+ ...kept
190
+ ];
191
+ }
192
+ return out;
193
+ };
194
+ /** What an install tells the person who ran it: what changed, and what to do
195
+ * next for Claude Code to work with this graph. */ export let installed = (done, server, removed = false, mcp)=>removed ? [
196
+ `removed this graph's session hooks and status line from ${done.path}`,
197
+ ...mcp ? [
198
+ `and its MCP server ${mcp.name} from ${mcp.path}`
199
+ ] : []
200
+ ].join('\n') : [
201
+ done.plugin ? `${done.path} runs the ${PLUGIN} plugin, which carries the hooks ` + `and this graph's tools: it now reaches ${server}, and the hooks ` + 'and MCP server an earlier install wrote by hand are gone.' : `wrote the session hooks into ${done.path}.`,
202
+ ...mcp && !done.plugin ? [
203
+ `wrote this graph's tools into ${mcp.path} as the MCP server ` + `${mcp.name}, each call naming its session.`
204
+ ] : [],
205
+ done.line ? "the status line shows each plan's room." : 'the status line is your own, so it is left as it was.',
206
+ 'A Claude Code session started from now on, in any directory, is a ' + 'session in this graph.',
207
+ `next: yak serve, which the hooks post each tool call to (${server}${PATH}).`
208
+ ].join('\n');
209
+ /** Write the entries and the status line into a settings file, keeping
210
+ * everything else in it; where the account runs the plugin, point it at
211
+ * `server` and take out the entries an earlier install wrote, which the
212
+ * plugin carries. A status line of the person's own stays. */ export let install = (path, opts)=>{
213
+ let settings = {};
214
+ try {
215
+ settings = JSON.parse(fs.readTextFileSync(path));
216
+ } catch (e) {
217
+ if (!fs.isNotFound(e)) throw e;
218
+ }
219
+ let plugin = !!settings.enabledPlugins?.[PLUGIN];
220
+ let hooks = merged(settings.hooks, lifecycle(opts.server, opts.yak), opts.remove || plugin);
221
+ let next = {
222
+ ...settings,
223
+ hooks
224
+ };
225
+ if (!Object.keys(hooks).length) delete next.hooks;
226
+ let line = !settings.statusLine || ourLine(settings.statusLine);
227
+ if (line && opts.remove) delete next.statusLine;
228
+ else if (line) next.statusLine = statusLine(opts.server);
229
+ if (plugin && !opts.remove) {
230
+ let configs = settings.pluginConfigs;
231
+ next.pluginConfigs = {
232
+ ...configs,
233
+ [PLUGIN]: {
234
+ ...configs?.[PLUGIN],
235
+ options: {
236
+ ...configs?.[PLUGIN]?.options,
237
+ server: opts.server.replace(/\/+$/, '')
238
+ }
239
+ }
240
+ };
241
+ }
242
+ let dir = path.slice(0, path.lastIndexOf('/'));
243
+ if (dir) fs.mkdirSync(dir, {
244
+ recursive: true
245
+ });
246
+ fs.writeTextFileSync(path, `${JSON.stringify(next, null, 2)}\n`);
247
+ return {
248
+ path,
249
+ plugin,
250
+ line
251
+ };
252
+ };
253
+ //# sourceMappingURL=hooks.js.map