@namzu/sdk 61.3.0 → 62.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +2 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/bridge/acp/permission.d.ts +8 -0
  6. package/dist/bridge/acp/permission.d.ts.map +1 -1
  7. package/dist/bridge/acp/permission.js.map +1 -1
  8. package/dist/bridge/acp/server.d.ts.map +1 -1
  9. package/dist/bridge/acp/server.js +8 -1
  10. package/dist/bridge/acp/server.js.map +1 -1
  11. package/dist/constants/tools/index.d.ts +2 -0
  12. package/dist/constants/tools/index.d.ts.map +1 -1
  13. package/dist/constants/tools/index.js +23 -0
  14. package/dist/constants/tools/index.js.map +1 -1
  15. package/dist/eval/harness-protection.js +1 -1
  16. package/dist/eval/harness-protection.js.map +1 -1
  17. package/dist/learning/cycle.d.ts +5 -3
  18. package/dist/learning/cycle.d.ts.map +1 -1
  19. package/dist/learning/cycle.js +11 -13
  20. package/dist/learning/cycle.js.map +1 -1
  21. package/dist/learning/guidance.d.ts +74 -0
  22. package/dist/learning/guidance.d.ts.map +1 -0
  23. package/dist/learning/guidance.js +259 -0
  24. package/dist/learning/guidance.js.map +1 -0
  25. package/dist/learning/skill.d.ts +2 -2
  26. package/dist/learning/skill.d.ts.map +1 -1
  27. package/dist/learning/skill.js +6 -6
  28. package/dist/learning/skill.js.map +1 -1
  29. package/dist/learning/store.d.ts.map +1 -1
  30. package/dist/learning/store.js +6 -6
  31. package/dist/learning/store.js.map +1 -1
  32. package/dist/pals/communication/ingress-schema.d.ts +8 -8
  33. package/dist/pals/communication/schema.d.ts +2 -2
  34. package/dist/peers/client.d.ts +2 -3
  35. package/dist/peers/client.d.ts.map +1 -1
  36. package/dist/peers/client.js +2 -3
  37. package/dist/peers/client.js.map +1 -1
  38. package/dist/peers/endpoint.d.ts +1 -2
  39. package/dist/peers/endpoint.d.ts.map +1 -1
  40. package/dist/peers/endpoint.js +1 -2
  41. package/dist/peers/endpoint.js.map +1 -1
  42. package/dist/peers/protocol.d.ts.map +1 -1
  43. package/dist/peers/protocol.js +1 -0
  44. package/dist/peers/protocol.js.map +1 -1
  45. package/dist/prompt/coding-agent-doctrine.d.ts +4 -4
  46. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  47. package/dist/prompt/coding-agent-doctrine.js +5 -3
  48. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  49. package/dist/prompt/index.d.ts +0 -4
  50. package/dist/prompt/index.d.ts.map +1 -1
  51. package/dist/prompt/index.js +0 -2
  52. package/dist/prompt/index.js.map +1 -1
  53. package/dist/provider/fallback.d.ts.map +1 -1
  54. package/dist/provider/fallback.js +3 -0
  55. package/dist/provider/fallback.js.map +1 -1
  56. package/dist/provider/idle-timeout.d.ts.map +1 -1
  57. package/dist/provider/idle-timeout.js +5 -0
  58. package/dist/provider/idle-timeout.js.map +1 -1
  59. package/dist/provider/model-window-suffix.d.ts.map +1 -1
  60. package/dist/provider/model-window-suffix.js +1 -0
  61. package/dist/provider/model-window-suffix.js.map +1 -1
  62. package/dist/provider/retry.d.ts.map +1 -1
  63. package/dist/provider/retry.js +5 -0
  64. package/dist/provider/retry.js.map +1 -1
  65. package/dist/provider/step-stopped.d.ts +19 -0
  66. package/dist/provider/step-stopped.d.ts.map +1 -0
  67. package/dist/provider/step-stopped.js +25 -0
  68. package/dist/provider/step-stopped.js.map +1 -0
  69. package/dist/provider/token-budget.d.ts.map +1 -1
  70. package/dist/provider/token-budget.js +6 -1
  71. package/dist/provider/token-budget.js.map +1 -1
  72. package/dist/public-runtime.d.ts +4 -15
  73. package/dist/public-runtime.d.ts.map +1 -1
  74. package/dist/public-runtime.js +3 -14
  75. package/dist/public-runtime.js.map +1 -1
  76. package/dist/public-tools.d.ts +0 -2
  77. package/dist/public-tools.d.ts.map +1 -1
  78. package/dist/public-tools.js +0 -2
  79. package/dist/public-tools.js.map +1 -1
  80. package/dist/public-types.d.ts +3 -21
  81. package/dist/public-types.d.ts.map +1 -1
  82. package/dist/runtime/query/iteration/index.d.ts +17 -0
  83. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  84. package/dist/runtime/query/iteration/index.js +168 -5
  85. package/dist/runtime/query/iteration/index.js.map +1 -1
  86. package/dist/runtime/query/iteration/phases/per-call-review.d.ts.map +1 -1
  87. package/dist/runtime/query/iteration/phases/per-call-review.js +4 -5
  88. package/dist/runtime/query/iteration/phases/per-call-review.js.map +1 -1
  89. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  90. package/dist/runtime/query/iteration/phases/tool-review.js +6 -3
  91. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  92. package/dist/runtime/query/iteration/stream-turn.d.ts +9 -1
  93. package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
  94. package/dist/runtime/query/iteration/stream-turn.js +48 -2
  95. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  96. package/dist/runtime/query/resume-pending.d.ts.map +1 -1
  97. package/dist/runtime/query/resume-pending.js +7 -4
  98. package/dist/runtime/query/resume-pending.js.map +1 -1
  99. package/dist/runtime/query/review-policy.d.ts +40 -8
  100. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  101. package/dist/runtime/query/review-policy.js +139 -24
  102. package/dist/runtime/query/review-policy.js.map +1 -1
  103. package/dist/runtime/query/turn/completion-audit.d.ts +32 -0
  104. package/dist/runtime/query/turn/completion-audit.d.ts.map +1 -0
  105. package/dist/runtime/query/turn/completion-audit.js +56 -0
  106. package/dist/runtime/query/turn/completion-audit.js.map +1 -0
  107. package/dist/runtime/query/turn/stall-monitor.d.ts +78 -0
  108. package/dist/runtime/query/turn/stall-monitor.d.ts.map +1 -0
  109. package/dist/runtime/query/turn/stall-monitor.js +101 -0
  110. package/dist/runtime/query/turn/stall-monitor.js.map +1 -0
  111. package/dist/session/paths.d.ts +1 -2
  112. package/dist/session/paths.d.ts.map +1 -1
  113. package/dist/session/paths.js +1 -4
  114. package/dist/session/paths.js.map +1 -1
  115. package/dist/tools/builtins/bash.d.ts +2 -1
  116. package/dist/tools/builtins/bash.d.ts.map +1 -1
  117. package/dist/tools/builtins/bash.js +5 -2
  118. package/dist/tools/builtins/bash.js.map +1 -1
  119. package/dist/tools/builtins/computer-use.d.ts +80 -0
  120. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  121. package/dist/tools/builtins/computer-use.js +172 -9
  122. package/dist/tools/builtins/computer-use.js.map +1 -1
  123. package/dist/tools/builtins/content-fingerprint.d.ts +13 -0
  124. package/dist/tools/builtins/content-fingerprint.d.ts.map +1 -1
  125. package/dist/tools/builtins/content-fingerprint.js +25 -0
  126. package/dist/tools/builtins/content-fingerprint.js.map +1 -1
  127. package/dist/tools/builtins/edit.d.ts.map +1 -1
  128. package/dist/tools/builtins/edit.js +7 -2
  129. package/dist/tools/builtins/edit.js.map +1 -1
  130. package/dist/tools/builtins/shell-read-credit.d.ts +15 -0
  131. package/dist/tools/builtins/shell-read-credit.d.ts.map +1 -0
  132. package/dist/tools/builtins/shell-read-credit.js +161 -0
  133. package/dist/tools/builtins/shell-read-credit.js.map +1 -0
  134. package/dist/tools/paths.d.ts +15 -2
  135. package/dist/tools/paths.d.ts.map +1 -1
  136. package/dist/tools/paths.js +17 -2
  137. package/dist/tools/paths.js.map +1 -1
  138. package/dist/turn/evidence-recall.d.ts +1 -1
  139. package/dist/turn/evidence-recall.d.ts.map +1 -1
  140. package/dist/turn/evidence-recall.js +5 -14
  141. package/dist/turn/evidence-recall.js.map +1 -1
  142. package/dist/types/acp/index.d.ts +6 -0
  143. package/dist/types/acp/index.d.ts.map +1 -1
  144. package/dist/types/agent/base.d.ts +4 -0
  145. package/dist/types/agent/base.d.ts.map +1 -1
  146. package/dist/types/hitl/index.d.ts +8 -0
  147. package/dist/types/hitl/index.d.ts.map +1 -1
  148. package/dist/types/hitl/index.js.map +1 -1
  149. package/dist/types/ids/index.d.ts +1 -1
  150. package/dist/types/message/index.d.ts +1 -1
  151. package/dist/types/message/index.d.ts.map +1 -1
  152. package/dist/types/message/index.js +1 -0
  153. package/dist/types/message/index.js.map +1 -1
  154. package/dist/types/provider/interface.d.ts +12 -0
  155. package/dist/types/provider/interface.d.ts.map +1 -1
  156. package/dist/types/session/config.d.ts +25 -0
  157. package/dist/types/session/config.d.ts.map +1 -1
  158. package/dist/types/session/records.d.ts.map +1 -1
  159. package/dist/types/session/records.js +2 -0
  160. package/dist/types/session/records.js.map +1 -1
  161. package/dist/types/session/turn.d.ts +1 -1
  162. package/dist/types/session/turn.d.ts.map +1 -1
  163. package/dist/types/session/turn.js.map +1 -1
  164. package/package.json +1 -1
  165. package/src/agents/QueryAgent.ts +2 -0
  166. package/src/bridge/acp/permission.ts +8 -0
  167. package/src/bridge/acp/server.ts +7 -1
  168. package/src/constants/tools/index.ts +27 -0
  169. package/src/eval/harness-protection.ts +1 -1
  170. package/src/learning/cycle.ts +15 -16
  171. package/src/learning/guidance.ts +339 -0
  172. package/src/learning/skill.ts +7 -7
  173. package/src/learning/store.ts +5 -6
  174. package/src/peers/client.ts +2 -3
  175. package/src/peers/endpoint.ts +1 -2
  176. package/src/peers/protocol.ts +1 -0
  177. package/src/prompt/coding-agent-doctrine.ts +5 -3
  178. package/src/prompt/index.ts +0 -4
  179. package/src/provider/fallback.ts +7 -0
  180. package/src/provider/idle-timeout.ts +8 -0
  181. package/src/provider/model-window-suffix.ts +1 -0
  182. package/src/provider/retry.ts +8 -0
  183. package/src/provider/step-stopped.ts +27 -0
  184. package/src/provider/token-budget.ts +6 -1
  185. package/src/public-runtime.ts +10 -28
  186. package/src/public-tools.ts +0 -3
  187. package/src/public-types.ts +5 -137
  188. package/src/runtime/query/iteration/index.ts +207 -5
  189. package/src/runtime/query/iteration/phases/per-call-review.ts +7 -5
  190. package/src/runtime/query/iteration/phases/tool-review.ts +5 -3
  191. package/src/runtime/query/iteration/stream-turn.ts +51 -1
  192. package/src/runtime/query/resume-pending.ts +11 -4
  193. package/src/runtime/query/review-policy.ts +157 -24
  194. package/src/runtime/query/turn/completion-audit.ts +71 -0
  195. package/src/runtime/query/turn/stall-monitor.ts +158 -0
  196. package/src/session/paths.ts +2 -6
  197. package/src/tools/builtins/bash.ts +6 -2
  198. package/src/tools/builtins/computer-use.ts +245 -7
  199. package/src/tools/builtins/content-fingerprint.ts +25 -0
  200. package/src/tools/builtins/edit.ts +11 -2
  201. package/src/tools/builtins/shell-read-credit.ts +159 -0
  202. package/src/tools/paths.ts +18 -2
  203. package/src/turn/evidence-recall.ts +7 -15
  204. package/src/types/acp/index.ts +6 -0
  205. package/src/types/agent/base.ts +4 -0
  206. package/src/types/hitl/index.ts +8 -0
  207. package/src/types/ids/index.ts +1 -1
  208. package/src/types/message/index.ts +1 -0
  209. package/src/types/provider/interface.ts +13 -0
  210. package/src/types/session/config.ts +27 -0
  211. package/src/types/session/records.ts +2 -0
  212. package/src/types/session/turn.ts +2 -1
  213. package/dist/learning/deprecated.d.ts +0 -86
  214. package/dist/learning/deprecated.d.ts.map +0 -1
  215. package/dist/learning/deprecated.js +0 -22
  216. package/dist/learning/deprecated.js.map +0 -1
  217. package/dist/manager/resident/activity.d.ts +0 -74
  218. package/dist/manager/resident/activity.d.ts.map +0 -1
  219. package/dist/manager/resident/activity.js +0 -125
  220. package/dist/manager/resident/activity.js.map +0 -1
  221. package/dist/manager/resident/agenda.d.ts +0 -167
  222. package/dist/manager/resident/agenda.d.ts.map +0 -1
  223. package/dist/manager/resident/agenda.js +0 -588
  224. package/dist/manager/resident/agenda.js.map +0 -1
  225. package/dist/manager/resident/consumption.d.ts +0 -98
  226. package/dist/manager/resident/consumption.d.ts.map +0 -1
  227. package/dist/manager/resident/consumption.js +0 -237
  228. package/dist/manager/resident/consumption.js.map +0 -1
  229. package/dist/manager/resident/delivery-window.d.ts +0 -28
  230. package/dist/manager/resident/delivery-window.d.ts.map +0 -1
  231. package/dist/manager/resident/delivery-window.js +0 -80
  232. package/dist/manager/resident/delivery-window.js.map +0 -1
  233. package/dist/manager/resident/evidence-recall.d.ts +0 -30
  234. package/dist/manager/resident/evidence-recall.d.ts.map +0 -1
  235. package/dist/manager/resident/evidence-recall.js +0 -297
  236. package/dist/manager/resident/evidence-recall.js.map +0 -1
  237. package/dist/manager/resident/history-disk.d.ts +0 -10
  238. package/dist/manager/resident/history-disk.d.ts.map +0 -1
  239. package/dist/manager/resident/history-disk.js +0 -50
  240. package/dist/manager/resident/history-disk.js.map +0 -1
  241. package/dist/manager/resident/history.d.ts +0 -115
  242. package/dist/manager/resident/history.d.ts.map +0 -1
  243. package/dist/manager/resident/history.js +0 -203
  244. package/dist/manager/resident/history.js.map +0 -1
  245. package/dist/manager/resident/host.d.ts +0 -112
  246. package/dist/manager/resident/host.d.ts.map +0 -1
  247. package/dist/manager/resident/host.js +0 -254
  248. package/dist/manager/resident/host.js.map +0 -1
  249. package/dist/manager/resident/initiative.d.ts +0 -86
  250. package/dist/manager/resident/initiative.d.ts.map +0 -1
  251. package/dist/manager/resident/initiative.js +0 -131
  252. package/dist/manager/resident/initiative.js.map +0 -1
  253. package/dist/manager/resident/loop.d.ts +0 -49
  254. package/dist/manager/resident/loop.d.ts.map +0 -1
  255. package/dist/manager/resident/loop.js +0 -75
  256. package/dist/manager/resident/loop.js.map +0 -1
  257. package/dist/manager/resident/outbox.d.ts +0 -124
  258. package/dist/manager/resident/outbox.d.ts.map +0 -1
  259. package/dist/manager/resident/outbox.js +0 -216
  260. package/dist/manager/resident/outbox.js.map +0 -1
  261. package/dist/manager/resident/proposal.d.ts +0 -65
  262. package/dist/manager/resident/proposal.d.ts.map +0 -1
  263. package/dist/manager/resident/proposal.js +0 -77
  264. package/dist/manager/resident/proposal.js.map +0 -1
  265. package/dist/manager/resident/store.d.ts +0 -108
  266. package/dist/manager/resident/store.d.ts.map +0 -1
  267. package/dist/manager/resident/store.js +0 -205
  268. package/dist/manager/resident/store.js.map +0 -1
  269. package/dist/manager/resident/tool-evidence.d.ts +0 -112
  270. package/dist/manager/resident/tool-evidence.d.ts.map +0 -1
  271. package/dist/manager/resident/tool-evidence.js +0 -289
  272. package/dist/manager/resident/tool-evidence.js.map +0 -1
  273. package/dist/prompt/resident-learning.d.ts +0 -29
  274. package/dist/prompt/resident-learning.d.ts.map +0 -1
  275. package/dist/prompt/resident-learning.js +0 -126
  276. package/dist/prompt/resident-learning.js.map +0 -1
  277. package/dist/prompt/resident-step.d.ts +0 -42
  278. package/dist/prompt/resident-step.d.ts.map +0 -1
  279. package/dist/prompt/resident-step.js +0 -137
  280. package/dist/prompt/resident-step.js.map +0 -1
  281. package/dist/tools/resident-history.d.ts +0 -12
  282. package/dist/tools/resident-history.d.ts.map +0 -1
  283. package/dist/tools/resident-history.js +0 -82
  284. package/dist/tools/resident-history.js.map +0 -1
  285. package/dist/tools/resident-tool-evidence.d.ts +0 -9
  286. package/dist/tools/resident-tool-evidence.d.ts.map +0 -1
  287. package/dist/tools/resident-tool-evidence.js +0 -61
  288. package/dist/tools/resident-tool-evidence.js.map +0 -1
  289. package/src/learning/deprecated.ts +0 -124
  290. package/src/manager/resident/activity.ts +0 -211
  291. package/src/manager/resident/agenda.ts +0 -937
  292. package/src/manager/resident/consumption.ts +0 -335
  293. package/src/manager/resident/delivery-window.ts +0 -99
  294. package/src/manager/resident/evidence-recall.ts +0 -369
  295. package/src/manager/resident/history-disk.ts +0 -63
  296. package/src/manager/resident/history.ts +0 -348
  297. package/src/manager/resident/host.ts +0 -390
  298. package/src/manager/resident/initiative.ts +0 -231
  299. package/src/manager/resident/loop.ts +0 -119
  300. package/src/manager/resident/outbox.ts +0 -341
  301. package/src/manager/resident/proposal.ts +0 -119
  302. package/src/manager/resident/store.ts +0 -279
  303. package/src/manager/resident/tool-evidence.ts +0 -455
  304. package/src/prompt/resident-learning.ts +0 -152
  305. package/src/prompt/resident-step.ts +0 -182
  306. package/src/tools/resident-history.ts +0 -88
  307. package/src/tools/resident-tool-evidence.ts +0 -72
@@ -1,390 +0,0 @@
1
- import { setTimeout as sleep } from 'node:timers/promises'
2
- import { type LearningState, freezeLearning } from '../../learning/skill.js'
3
- import type { ResidentAgendaState, ResidentAgendaStore, ResidentPursuit } from './agenda.js'
4
- import {
5
- type ResidentObservation,
6
- type ResidentSelection,
7
- type ResidentSelector,
8
- residentObservationSchema,
9
- } from './initiative.js'
10
- import { type ResidentStep, stepResident } from './loop.js'
11
- import { type ResidentMessageInput, residentMessageInputSchema } from './outbox.js'
12
- import { ResidentConflictError, type ResidentDecision, residentDecisionSchema } from './store.js'
13
-
14
- /**
15
- * @experimental Host result describes execution, not external-effect rollback.
16
- *
17
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
18
- */
19
- export interface ResidentHostResult {
20
- readonly status: 'idle' | 'paused' | 'unresolved' | 'cancelled' | 'limit' | 'contended'
21
- readonly stepsSettled: number
22
- readonly nextWakeAt: number | null
23
- readonly selection?: ResidentSelection
24
- }
25
-
26
- /**
27
- * @experimental Explicit authorization to drive a finite number of background steps.
28
- *
29
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
30
- */
31
- export interface ResidentHostRunOptions {
32
- readonly signal: AbortSignal
33
- readonly maxSteps: number
34
- /** Maximum single idle wait; with keepAlive, also bounds local agenda polling. */
35
- readonly maxIdleMs?: number
36
- /** Keep waiting for useful work within this invocation's finite step cap. Default false. */
37
- readonly keepAlive?: boolean
38
- }
39
-
40
- /**
41
- * @experimental Immutable context from the agenda snapshot that authorized this admission.
42
- *
43
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
44
- */
45
- export interface ResidentStepContext {
46
- readonly agendaRevision: number
47
- readonly learning?: LearningState
48
- }
49
-
50
- /**
51
- * @experimental A developer callback may bind a different SDK turn for each pursuit.
52
- *
53
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
54
- */
55
- export type ResidentPursuitStep = (
56
- pursuit: ResidentPursuit,
57
- signal: AbortSignal,
58
- ) => ReturnType<ResidentStep>
59
-
60
- /**
61
- * @experimental Context-aware callback; existing two-argument steps remain assignable.
62
- *
63
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
64
- */
65
- export type ResidentContextualStep = (
66
- pursuit: ResidentPursuit,
67
- signal: AbortSignal,
68
- context: ResidentStepContext,
69
- ) => ReturnType<ResidentStep>
70
-
71
- /**
72
- * @experimental Inspect actual outcomes and resource receipts independently of model prose.
73
- *
74
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
75
- */
76
- export type ResidentObserver = (
77
- pursuit: ResidentPursuit,
78
- decision: ResidentDecision,
79
- signal: AbortSignal,
80
- ) => Promise<ResidentObservation>
81
-
82
- /**
83
- * @experimental Host validates content and destination; null means no communication.
84
- *
85
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
86
- */
87
- export type ResidentMessageFactory = (
88
- pursuit: ResidentPursuit,
89
- decision: ResidentDecision,
90
- signal: AbortSignal,
91
- ) => Promise<ResidentMessageInput | null>
92
-
93
- /**
94
- * @experimental Opt-in local selection, observed settlement and atomic outbound intent.
95
- *
96
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
97
- */
98
- export interface ResidentHostOptions {
99
- readonly select?: ResidentSelector
100
- readonly observe?: ResidentObserver
101
- readonly prepareMessage?: ResidentMessageFactory
102
- /** Bind approved learning to the exact admission snapshot. Default false. */
103
- readonly learning?: boolean
104
- }
105
-
106
- /**
107
- * @experimental Local driver for one durable agenda. Shared agenda admission
108
- * prevents overlapping pursuits across processes. Notifications are local;
109
- * opt-in keepAlive also rereads durable state on bounded idle timers.
110
- *
111
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
112
- */
113
- export class ResidentHost {
114
- private controller: AbortController | undefined
115
- private active: Promise<ResidentHostResult> | undefined
116
- private idle: AbortController | undefined
117
- private generation = 0
118
- private controls: Promise<void> = Promise.resolve()
119
- private controlsPending = 0
120
- private readonly options: ResidentHostOptions
121
-
122
- constructor(
123
- private readonly agenda: ResidentAgendaStore,
124
- private readonly step: ResidentContextualStep,
125
- options: ResidentHostOptions = {},
126
- ) {
127
- if (options.learning !== undefined && typeof options.learning !== 'boolean')
128
- throw new TypeError('Resident learning must be explicitly enabled with a boolean.')
129
- if ((options.select || options.learning) && !agenda.executionAt)
130
- throw new TypeError('Resident selection or learning requires atomic executionAt support.')
131
- if (options.observe && !agenda.settleObserved)
132
- throw new TypeError('Resident observation requires atomic settleObserved support.')
133
- if (options.prepareMessage && !agenda.settleWithMessage)
134
- throw new TypeError('Resident messages require atomic settleWithMessage support.')
135
- this.options = Object.freeze({ ...options })
136
- }
137
-
138
- /** Interrupt local idle waiting after the host learns of new durable state. */
139
- notify(): void {
140
- this.generation++
141
- this.idle?.abort()
142
- }
143
-
144
- private async snapshot(): Promise<ResidentAgendaState> {
145
- const state = await this.agenda.read()
146
- if (!state) throw new Error('Create the resident agenda before running the host.')
147
- return state
148
- }
149
-
150
- private async paused(value: boolean): Promise<void> {
151
- for (let attempt = 0; attempt < 8; attempt++) {
152
- const state = await this.snapshot()
153
- if (state.paused === value) return
154
- try {
155
- await this.agenda.setPaused(state, value)
156
- return
157
- } catch (error) {
158
- if (!(error instanceof ResidentConflictError) || attempt === 7) throw error
159
- }
160
- }
161
- }
162
-
163
- private control(update: () => Promise<void>): Promise<void> {
164
- this.controlsPending++
165
- const pending = this.controls.then(update)
166
- this.controls = pending.catch(() => {})
167
- return pending.finally(() => {
168
- this.controlsPending--
169
- })
170
- }
171
-
172
- /**
173
- * Signal current work and durably close future admission. Resolving this method
174
- * is NOT quiescence: await the turn promise before claiming the callback stopped.
175
- * An interrupted admitted pursuit remains unresolved until reconciled explicitly.
176
- */
177
- async pause(): Promise<void> {
178
- this.controller?.abort()
179
- this.notify()
180
- await this.control(() => this.paused(true))
181
- }
182
-
183
- /** Reauthorize future work only after this host's previous invocation drained. */
184
- async resume(): Promise<void> {
185
- if (this.controlsPending) throw new Error('Wait for pending resident controls before resuming.')
186
- if (this.active)
187
- throw new Error('Wait for the active resident invocation to drain before resuming.')
188
- await this.control(() => this.paused(false))
189
- this.notify()
190
- }
191
-
192
- /** Persist fresh evidence and interrupt this host's idle timer. */
193
- async wake(id: string, reason: string): Promise<void> {
194
- const state = await this.snapshot()
195
- const pursuit = state.pursuits.find((p) => p.id === id)
196
- if (!pursuit) throw new Error('Unknown resident pursuit.')
197
- await this.agenda.wake(id, pursuit.state, reason, Date.now())
198
- this.notify()
199
- }
200
-
201
- run(options: ResidentHostRunOptions): Promise<ResidentHostResult> {
202
- if (this.controlsPending) throw new Error('Wait for pending resident controls before running.')
203
- if (this.active) throw new Error('A resident host invocation is already active.')
204
- const maxIdleMs = options.maxIdleMs ?? 60_000
205
- const keepAlive = options.keepAlive ?? false
206
- if (options.keepAlive !== undefined && typeof options.keepAlive !== 'boolean')
207
- throw new TypeError('Resident keepAlive must be explicitly enabled with a boolean.')
208
- if (
209
- !Number.isSafeInteger(options.maxSteps) ||
210
- options.maxSteps < 1 ||
211
- !Number.isSafeInteger(maxIdleMs) ||
212
- maxIdleMs < 0 ||
213
- maxIdleMs > 2_147_483_647 ||
214
- (keepAlive && maxIdleMs === 0)
215
- )
216
- throw new TypeError('Invalid resident host limits.')
217
- const controller = new AbortController()
218
- this.controller = controller
219
- const signal = AbortSignal.any([controller.signal, options.signal])
220
- this.active = this.drive(options.maxSteps, maxIdleMs, keepAlive, signal).finally(() => {
221
- this.active = undefined
222
- this.controller = undefined
223
- this.idle = undefined
224
- })
225
- return this.active
226
- }
227
-
228
- private async drive(
229
- maxSteps: number,
230
- maxIdleMs: number,
231
- keepAlive: boolean,
232
- signal: AbortSignal,
233
- ): Promise<ResidentHostResult> {
234
- let stepsSettled = 0
235
- try {
236
- while (true) {
237
- signal.throwIfAborted()
238
- const observed = this.generation
239
- const state = await this.snapshot()
240
- signal.throwIfAborted()
241
- if (state.paused) return { status: 'paused', stepsSettled, nextWakeAt: null }
242
- if (state.pursuits.some((p) => p.state.phase === 'running'))
243
- return { status: 'unresolved', stepsSettled, nextWakeAt: null }
244
- const waiting = state.pursuits.filter(
245
- (p) => p.state.phase === 'waiting' && p.state.wakeAt !== null,
246
- )
247
- const now = Date.now()
248
- // Fair, deterministic baseline; this is not model-authored initiative.
249
- let due = waiting
250
- .filter((p) => (p.state.wakeAt ?? 0) <= now)
251
- .sort(
252
- (a, b) =>
253
- a.state.stepsAdmitted - b.state.stepsAdmitted ||
254
- (a.state.wakeAt ?? 0) - (b.state.wakeAt ?? 0) ||
255
- a.id.localeCompare(b.id),
256
- )[0]
257
- let selection: ResidentSelection | undefined
258
- if (due && this.options.select) {
259
- selection = this.options.select(state, now)
260
- signal.throwIfAborted()
261
- if (selection.agendaRevision !== state.revision)
262
- throw new Error('Resident selector returned a stale agenda revision.')
263
- if (selection.pursuitId === null) due = undefined
264
- else {
265
- const selectedId = selection.pursuitId
266
- due = waiting.find((p) => p.id === selectedId && (p.state.wakeAt ?? 0) <= now)
267
- if (!due) throw new Error('Resident selector chose an ineligible pursuit.')
268
- }
269
- }
270
-
271
- if (due) {
272
- const selected = due
273
- const context: ResidentStepContext = Object.freeze({
274
- agendaRevision: state.revision,
275
- ...(this.options.learning && state.learning
276
- ? { learning: freezeLearning(state.learning) }
277
- : {}),
278
- })
279
- const execution =
280
- this.options.select || this.options.learning
281
- ? this.agenda.executionAt?.(selected.id, state)
282
- : this.agenda.execution(selected.id)
283
- if (!execution) throw new Error('Resident executionAt support was removed.')
284
- const observe = this.options.observe
285
- const prepareMessage = this.options.prepareMessage
286
- const observedExecution =
287
- observe || prepareMessage
288
- ? {
289
- read: () => execution.read(),
290
- claim: (...args: Parameters<typeof execution.claim>) => execution.claim(...args),
291
- settle: async (
292
- current: Parameters<typeof execution.settle>[0],
293
- decision: ResidentDecision,
294
- at: number,
295
- ) => {
296
- const disposition = Object.freeze(residentDecisionSchema.parse(decision))
297
- const observed = await observe?.(
298
- { ...selected, state: current },
299
- disposition,
300
- signal,
301
- )
302
- signal.throwIfAborted()
303
- const observation = observe
304
- ? Object.freeze(residentObservationSchema.parse(observed))
305
- : undefined
306
- const prepared = await prepareMessage?.(
307
- { ...selected, state: current },
308
- disposition,
309
- signal,
310
- )
311
- signal.throwIfAborted()
312
- const message =
313
- prepareMessage && prepared !== null
314
- ? Object.freeze(residentMessageInputSchema.parse(prepared))
315
- : null
316
- if (message !== null) {
317
- if (!this.agenda.settleWithMessage)
318
- throw new Error('Resident settleWithMessage support was removed.')
319
- return this.agenda.settleWithMessage(
320
- selected.id,
321
- current,
322
- disposition,
323
- message,
324
- at,
325
- observation,
326
- )
327
- }
328
- if (observation) {
329
- if (!this.agenda.settleObserved)
330
- throw new Error('Resident settleObserved support was removed.')
331
- return this.agenda.settleObserved(
332
- selected.id,
333
- current,
334
- disposition,
335
- observation,
336
- at,
337
- )
338
- }
339
- return execution.settle(current, disposition, at)
340
- },
341
- }
342
- : execution
343
- const result = await stepResident(
344
- observedExecution,
345
- (current, abort) => this.step({ ...selected, state: current }, abort, context),
346
- signal,
347
- )
348
- if (result.status === 'idle')
349
- return {
350
- status: result.reason === 'unresolved' ? 'unresolved' : 'contended',
351
- stepsSettled,
352
- nextWakeAt: null,
353
- }
354
- stepsSettled++
355
- if (stepsSettled >= maxSteps) return { status: 'limit', stepsSettled, nextWakeAt: null }
356
- continue
357
- }
358
- const scheduled =
359
- selection?.pursuitId === null
360
- ? waiting.filter((p) => (p.state.wakeAt ?? 0) > now)
361
- : waiting
362
- const nextWakeAt =
363
- scheduled.length === 0 ? null : Math.min(...scheduled.map((p) => p.state.wakeAt ?? now))
364
- if (observed !== this.generation) continue
365
- if (!keepAlive && (nextWakeAt === null || nextWakeAt - now > maxIdleMs))
366
- return { status: 'idle', stepsSettled, nextWakeAt, ...(selection ? { selection } : {}) }
367
- const delay =
368
- nextWakeAt === null
369
- ? maxIdleMs
370
- : keepAlive
371
- ? Math.min(maxIdleMs, nextWakeAt - now)
372
- : nextWakeAt - now
373
- const idle = new AbortController()
374
- this.idle = idle
375
- try {
376
- await sleep(Math.max(1, delay), undefined, {
377
- signal: AbortSignal.any([signal, idle.signal]),
378
- })
379
- } catch (error) {
380
- if (!idle.signal.aborted || signal.aborted) throw error
381
- } finally {
382
- if (this.idle === idle) this.idle = undefined
383
- }
384
- }
385
- } catch (error) {
386
- if (!signal.aborted) throw error
387
- return { status: 'cancelled', stepsSettled, nextWakeAt: null }
388
- }
389
- }
390
- }
@@ -1,231 +0,0 @@
1
- import { z } from 'zod'
2
- import type { ResidentAgendaState } from './agenda.js'
3
-
4
- const boundedText = z.string().trim().min(1).max(256)
5
- const cost = z.number().finite().nonnegative()
6
- export const residentObservationSchema = z.object({
7
- evidenceKey: boundedText,
8
- source: boundedText,
9
- progress: z.number().finite().min(0).max(1),
10
- /** All observations and policy costs use the same host-defined resource unit. */
11
- costUnits: cost.nullable(),
12
- })
13
-
14
- /**
15
- * @experimental Host-validated outcome and measured resource use, never model self-confidence.
16
- *
17
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
18
- */
19
- export type ResidentObservation = Readonly<z.infer<typeof residentObservationSchema>>
20
-
21
- export const residentFeedbackSchema = z.object({
22
- bestProgress: z.number().finite().min(0).max(1),
23
- hasUnobservedSteps: z.boolean().default(false),
24
- stagnantSteps: z.number().int().nonnegative().safe(),
25
- observations: z
26
- .array(
27
- residentObservationSchema.extend({
28
- gain: z.number().finite().min(0).max(1),
29
- step: z.number().int().positive().safe(),
30
- }),
31
- )
32
- .min(1)
33
- .max(8),
34
- })
35
-
36
- /**
37
- * @experimental Last eight observations; best progress and stagnation survive eviction.
38
- *
39
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
40
- */
41
- export type ResidentFeedback = Readonly<
42
- Omit<z.infer<typeof residentFeedbackSchema>, 'observations'>
43
- > & {
44
- readonly observations: readonly Readonly<
45
- z.infer<typeof residentFeedbackSchema>['observations'][number]
46
- >[]
47
- }
48
-
49
- export function observeResidentStep(
50
- previous: ResidentFeedback | undefined,
51
- input: ResidentObservation,
52
- step: number,
53
- ): ResidentFeedback {
54
- const observation = residentObservationSchema.parse(input)
55
- const best = previous?.bestProgress ?? 0
56
- const duplicate = previous?.observations.some(
57
- (item) => item.evidenceKey === observation.evidenceKey,
58
- )
59
- // Rewording evidence, regression and recovery to an old best earn no credit.
60
- const gain = duplicate ? 0 : Math.max(0, observation.progress - best)
61
- return freezeResidentFeedback(
62
- residentFeedbackSchema.parse({
63
- bestProgress: best + gain,
64
- hasUnobservedSteps:
65
- (previous?.hasUnobservedSteps ?? false) ||
66
- step !== (previous?.observations.at(-1)?.step ?? 0) + 1,
67
- stagnantSteps: gain > 0 ? 0 : (previous?.stagnantSteps ?? 0) + 1,
68
- observations: [...(previous?.observations ?? []), { ...observation, gain, step }].slice(-8),
69
- }),
70
- )
71
- }
72
-
73
- export function freezeResidentFeedback(value: ResidentFeedback): ResidentFeedback {
74
- return Object.freeze({
75
- ...value,
76
- observations: Object.freeze(value.observations.map((item) => Object.freeze({ ...item }))),
77
- })
78
- }
79
-
80
- /**
81
- * @experimental Policy units are chosen by the host; scores are heuristics, not probabilities.
82
- *
83
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
84
- */
85
- export interface ResidentSelectionConfig {
86
- readonly progressValue: number
87
- readonly initialExpectedProgress: number
88
- readonly initialExpectedCost: number
89
- readonly maxStagnantSteps?: number
90
- }
91
-
92
- /**
93
- * @experimental Explainable inputs for a single selection; unknown cost is not zero.
94
- *
95
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
96
- */
97
- export interface ResidentCandidate {
98
- readonly pursuitId: string
99
- readonly reason:
100
- | 'eligible'
101
- | 'not-due'
102
- | 'missing-observation'
103
- | 'stalled'
104
- | 'unknown-cost'
105
- | 'nonpositive-value'
106
- readonly expectedGain: number | null
107
- readonly expectedCost: number | null
108
- readonly score: number | null
109
- }
110
-
111
- /**
112
- * @experimental Choice is bound to the whole agenda revision used to compute it.
113
- *
114
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
115
- */
116
- export interface ResidentSelection {
117
- readonly agendaRevision: number
118
- readonly pursuitId: string | null
119
- readonly reason: 'selected' | 'paused' | 'unresolved' | 'no-useful-work'
120
- readonly candidates: readonly ResidentCandidate[]
121
- }
122
-
123
- /**
124
- * @experimental Pure local selection; perform inference inside budgeted steps, not here.
125
- *
126
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
127
- */
128
- export type ResidentSelector = (agenda: ResidentAgendaState, now: number) => ResidentSelection
129
-
130
- function meanObservedCost(observations: readonly ResidentObservation[]): number {
131
- // Null costs are rejected before this function. Scale by the largest finite
132
- // observation: the intermediate sum is at most eight, even near MAX_VALUE.
133
- const scale = Math.max(...observations.map((item) => item.costUnits ?? 0))
134
- if (scale === 0) return 0
135
- return (
136
- (observations.reduce((total, item) => total + (item.costUnits ?? 0) / scale, 0) /
137
- observations.length) *
138
- scale
139
- )
140
- }
141
-
142
- /**
143
- * @experimental Cost-aware continuation with an explicit abstention choice.
144
- * This is a measured-progress heuristic, not Bayesian value of computation.
145
- * A finite bootstrap allowance permits delayed payoffs but may stop too early.
146
- *
147
- * @deprecated Residents are deprecated and removed in the next major release. Learning (`runLearningCycle` and the other `Learning*` names) keeps working, but `runLearningCycle` still takes a resident agenda until learning gets its own activation target in the next major release; for long-running work use scheduled tasks (`LocalTaskScheduler`), session goals and background agents.
148
- */
149
- export function createResidentSelector(config: ResidentSelectionConfig): ResidentSelector {
150
- const policy = z
151
- .object({
152
- progressValue: z.number().finite().positive(),
153
- initialExpectedProgress: z.number().finite().positive().max(1),
154
- initialExpectedCost: cost,
155
- maxStagnantSteps: z.number().int().min(1).max(32).default(2),
156
- })
157
- .parse(config)
158
- return (agenda, now) => {
159
- z.number().int().nonnegative().safe().parse(now)
160
- const finish = (
161
- pursuitId: string | null,
162
- reason: ResidentSelection['reason'],
163
- candidates: ResidentCandidate[],
164
- ): ResidentSelection =>
165
- Object.freeze({
166
- agendaRevision: agenda.revision,
167
- pursuitId,
168
- reason,
169
- candidates: Object.freeze(candidates.map((candidate) => Object.freeze(candidate))),
170
- })
171
- if (agenda.paused) return finish(null, 'paused', [])
172
- if (agenda.pursuits.some((p) => p.state.phase === 'running'))
173
- return finish(null, 'unresolved', [])
174
- const candidates = agenda.pursuits.map((p): ResidentCandidate => {
175
- const reject = (reason: ResidentCandidate['reason']): ResidentCandidate => ({
176
- pursuitId: p.id,
177
- reason,
178
- expectedGain: null,
179
- expectedCost: null,
180
- score: null,
181
- })
182
- if (p.state.phase !== 'waiting' || p.state.wakeAt === null || p.state.wakeAt > now)
183
- return reject('not-due')
184
- if (
185
- p.state.stepsAdmitted > 0 &&
186
- (!p.feedback ||
187
- p.feedback.hasUnobservedSteps ||
188
- p.feedback.observations.at(-1)?.step !== p.state.stepsAdmitted)
189
- )
190
- return reject('missing-observation')
191
- const feedback = p.feedback
192
- if (feedback && feedback.stagnantSteps >= policy.maxStagnantSteps) return reject('stalled')
193
- if (feedback?.observations.some((item) => item.costUnits === null))
194
- return reject('unknown-cost')
195
- const recent = feedback?.observations ?? []
196
- const totalGain = recent.reduce((total, item) => total + item.gain, 0)
197
- const bootstrap = p.state.stepsAdmitted < policy.maxStagnantSteps && totalGain === 0
198
- const expectedGain =
199
- recent.length === 0 || bootstrap
200
- ? policy.initialExpectedProgress
201
- : (totalGain + policy.initialExpectedProgress) / (recent.length + 1)
202
- const expectedCost =
203
- recent.length === 0 ? policy.initialExpectedCost : meanObservedCost(recent)
204
- const score = policy.progressValue * expectedGain - expectedCost
205
- return {
206
- pursuitId: p.id,
207
- reason: score > 0 ? 'eligible' : 'nonpositive-value',
208
- expectedGain,
209
- expectedCost,
210
- score,
211
- }
212
- })
213
- const eligible = candidates.filter((candidate) => candidate.reason === 'eligible')
214
- eligible.sort((a, b) => {
215
- const left = agenda.pursuits.find((p) => p.id === a.pursuitId)
216
- const right = agenda.pursuits.find((p) => p.id === b.pursuitId)
217
- if (!left || !right) throw new Error('Resident candidate is missing.')
218
- return (
219
- (b.score ?? 0) - (a.score ?? 0) ||
220
- left.state.stepsAdmitted - right.state.stepsAdmitted ||
221
- (left.state.wakeAt ?? 0) - (right.state.wakeAt ?? 0) ||
222
- a.pursuitId.localeCompare(b.pursuitId)
223
- )
224
- })
225
- return finish(
226
- eligible[0]?.pursuitId ?? null,
227
- eligible.length ? 'selected' : 'no-useful-work',
228
- candidates,
229
- )
230
- }
231
- }