orkeon-code 0.0.0-stage → 1.0.0-rc.1

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 (423) hide show
  1. package/.orkeon-version +1 -0
  2. package/LICENSE.md +21 -0
  3. package/NOTICE.md +17 -0
  4. package/README.fr.md +169 -0
  5. package/README.md +162 -2
  6. package/config/appsettings.anthropic.example.json +77 -0
  7. package/config/appsettings.example.json +71 -0
  8. package/config/appsettings.jev.example.json +128 -0
  9. package/config/appsettings.kev.example.json +130 -0
  10. package/config/appsettings.liquid.example.json +129 -0
  11. package/config/appsettings.ollama-whisper.example.json +92 -0
  12. package/config/appsettings.ollama.example.json +70 -0
  13. package/config/appsettings.whisper.example.json +31 -0
  14. package/mcp/whisper/README.md +293 -0
  15. package/mcp/whisper/pyproject.toml +32 -0
  16. package/mcp/whisper/uv.lock +1641 -0
  17. package/mcp/whisper/whisper_mcp.py +1053 -0
  18. package/orkeon-code +897 -0
  19. package/orkeon-code.mjs +71 -0
  20. package/orkeon-code.ps1 +837 -0
  21. package/package.json +57 -4
  22. package/scripts/install.ps1 +156 -0
  23. package/scripts/install.sh +148 -0
  24. package/scripts/session-start.ork.ts +90 -0
  25. package/scripts/session-start.sh +74 -0
  26. package/scripts/setup-fixture.sh +88 -0
  27. package/src/commands/.orkeon/orkeon-cli.d.ts +562 -0
  28. package/src/commands/_lib/args.ts +193 -0
  29. package/src/commands/_lib/dev/dev-batches.ts +368 -0
  30. package/src/commands/_lib/dev/dev-implement.ts +188 -0
  31. package/src/commands/_lib/dev/dev-source.ts +65 -0
  32. package/src/commands/_lib/dev/dev.ts +344 -0
  33. package/src/commands/_lib/dev-step.ts +142 -0
  34. package/src/commands/_lib/dispatch.ts +231 -0
  35. package/src/commands/_lib/effort.ts +15 -0
  36. package/src/commands/_lib/git/branch.ts +95 -0
  37. package/src/commands/_lib/git/commit.ts +94 -0
  38. package/src/commands/_lib/git/diff.ts +97 -0
  39. package/src/commands/_lib/git/review.ts +109 -0
  40. package/src/commands/_lib/memory/memory-admit.ts +150 -0
  41. package/src/commands/_lib/memory/memory.ts +51 -0
  42. package/src/commands/_lib/pr-context.ts +32 -0
  43. package/src/commands/_lib/project/analyze.ts +24 -0
  44. package/src/commands/_lib/session/export.ts +104 -0
  45. package/src/commands/_lib/session/resume.ts +160 -0
  46. package/src/commands/_lib/session/tasks.ts +184 -0
  47. package/src/commands/_lib/settings/advisor.ts +80 -0
  48. package/src/commands/_lib/settings/agents.ts +147 -0
  49. package/src/commands/_lib/settings/config.ts +141 -0
  50. package/src/commands/_lib/settings/hooks.ts +58 -0
  51. package/src/commands/_lib/settings/mode.ts +91 -0
  52. package/src/commands/_lib/settings/model.ts +146 -0
  53. package/src/commands/_lib/settings/permissions.ts +309 -0
  54. package/src/commands/_lib/settings/session-config.ts +49 -0
  55. package/src/commands/_lib/settings/skills.ts +51 -0
  56. package/src/commands/_lib/speech/say.ts +96 -0
  57. package/src/commands/_lib/speech/transcribe.ts +130 -0
  58. package/src/commands/_lib/speech/voice.ts +146 -0
  59. package/src/commands/_lib/status/cache.ts +31 -0
  60. package/src/commands/_lib/status/context.ts +57 -0
  61. package/src/commands/_lib/status/doctor.ts +186 -0
  62. package/src/commands/_lib/status/meta.ts +45 -0
  63. package/src/commands/_lib/status/status.ts +129 -0
  64. package/src/commands/_lib/status/usage-tools.ts +49 -0
  65. package/src/commands/_lib/status/usage.ts +139 -0
  66. package/src/commands/_lib/view.ts +29 -0
  67. package/src/commands/dev/dev-batches.cmd.ts +108 -0
  68. package/src/commands/dev/dev-learn.cmd.ts +29 -0
  69. package/src/commands/dev/dev-plan.cmd.ts +52 -0
  70. package/src/commands/dev/dev-spec.cmd.ts +55 -0
  71. package/src/commands/dev/dev-status.cmd.ts +16 -0
  72. package/src/commands/git/branch.cmd.ts +27 -0
  73. package/src/commands/git/commit.cmd.ts +48 -0
  74. package/src/commands/git/diff.cmd.ts +26 -0
  75. package/src/commands/git/review.cmd.ts +36 -0
  76. package/src/commands/memory/memory.cmd.ts +48 -0
  77. package/src/commands/project/analyze.cmd.ts +32 -0
  78. package/src/commands/project/debug-tool-call.cmd.ts +67 -0
  79. package/src/commands/project/files.cmd.ts +22 -0
  80. package/src/commands/project/init-verifiers.cmd.ts +14 -0
  81. package/src/commands/project/init.cmd.ts +14 -0
  82. package/src/commands/project/verify.cmd.ts +27 -0
  83. package/src/commands/session/assistant.cmd.ts +40 -0
  84. package/src/commands/session/btw.cmd.ts +18 -0
  85. package/src/commands/session/clear.cmd.ts +19 -0
  86. package/src/commands/session/compact.cmd.ts +16 -0
  87. package/src/commands/session/copy.cmd.ts +44 -0
  88. package/src/commands/session/exit.cmd.ts +9 -0
  89. package/src/commands/session/export.cmd.ts +28 -0
  90. package/src/commands/session/rename.cmd.ts +17 -0
  91. package/src/commands/session/resume.cmd.ts +19 -0
  92. package/src/commands/session/rewind.cmd.ts +26 -0
  93. package/src/commands/session/summary.cmd.ts +27 -0
  94. package/src/commands/session/tasks.cmd.ts +44 -0
  95. package/src/commands/settings/advisor.cmd.ts +38 -0
  96. package/src/commands/settings/agents.cmd.ts +19 -0
  97. package/src/commands/settings/config.cmd.ts +17 -0
  98. package/src/commands/settings/effort.cmd.ts +40 -0
  99. package/src/commands/settings/fast.cmd.ts +17 -0
  100. package/src/commands/settings/hooks.cmd.ts +17 -0
  101. package/src/commands/settings/mode.cmd.ts +20 -0
  102. package/src/commands/settings/model.cmd.ts +20 -0
  103. package/src/commands/settings/output-style.cmd.ts +48 -0
  104. package/src/commands/settings/permissions.cmd.ts +25 -0
  105. package/src/commands/settings/proactive.cmd.ts +15 -0
  106. package/src/commands/settings/skills.cmd.ts +17 -0
  107. package/src/commands/speech/say.cmd.ts +24 -0
  108. package/src/commands/speech/transcribe.cmd.ts +29 -0
  109. package/src/commands/speech/voice.cmd.ts +30 -0
  110. package/src/commands/status/context.cmd.ts +18 -0
  111. package/src/commands/status/doctor.cmd.ts +27 -0
  112. package/src/commands/status/release-notes.cmd.ts +9 -0
  113. package/src/commands/status/status.cmd.ts +25 -0
  114. package/src/commands/status/usage.cmd.ts +21 -0
  115. package/src/crews/.orkeon/orkeon.d.ts +3946 -0
  116. package/src/crews/_probe-shared-memory/domain/probe-verdict.ts +183 -0
  117. package/src/crews/_probe-shared-memory/probe.ork.ts +98 -0
  118. package/src/crews/advisor/application/run-advisor.ts +40 -0
  119. package/src/crews/advisor/crew.ork.ts +43 -0
  120. package/src/crews/advisor/domain/advice.ts +135 -0
  121. package/src/crews/agent-run/application/run-agent-run.ts +42 -0
  122. package/src/crews/agent-run/crew.ork.ts +67 -0
  123. package/src/crews/analyze/application/run-analyze.ts +118 -0
  124. package/src/crews/analyze/crew.ork.ts +40 -0
  125. package/src/crews/analyze/domain/harvest.ts +301 -0
  126. package/src/crews/code-review/application/prompts.ts +133 -0
  127. package/src/crews/code-review/application/review.ts +71 -0
  128. package/src/crews/code-review/application/run-code-review.ts +123 -0
  129. package/src/crews/code-review/crew.ork.ts +51 -0
  130. package/src/crews/code-review/domain/lenses.ts +193 -0
  131. package/src/crews/code-review/domain/report.ts +59 -0
  132. package/src/crews/code-review/domain/scope.ts +112 -0
  133. package/src/crews/dev-batches/application/plan-close.ts +181 -0
  134. package/src/crews/dev-batches/application/run-dev-batches.ts +669 -0
  135. package/src/crews/dev-batches/application/run-wave.ts +450 -0
  136. package/src/crews/dev-batches/application/seed-harvest.ts +162 -0
  137. package/src/crews/dev-batches/crew.ork.ts +143 -0
  138. package/src/crews/dev-batches/domain/batch-waves.ts +70 -0
  139. package/src/crews/dev-batches/domain/batches-budget.ts +52 -0
  140. package/src/crews/dev-batches/domain/batches-log.ts +54 -0
  141. package/src/crews/dev-batches/domain/wave-order.ts +43 -0
  142. package/src/crews/dev-change/application/change-prompt.ts +104 -0
  143. package/src/crews/dev-change/application/evidence.ts +169 -0
  144. package/src/crews/dev-change/application/run-dev-change.ts +315 -0
  145. package/src/crews/dev-change/crew.ork.ts +112 -0
  146. package/src/crews/dev-change/domain/change-answer.ts +159 -0
  147. package/src/crews/dev-change/domain/change-render.ts +79 -0
  148. package/src/crews/dev-implement/application/close.ts +183 -0
  149. package/src/crews/dev-implement/application/count-open-steps.ts +24 -0
  150. package/src/crews/dev-implement/application/locate-sheet.ts +80 -0
  151. package/src/crews/dev-implement/application/observe.ts +50 -0
  152. package/src/crews/dev-implement/application/report-writes.ts +41 -0
  153. package/src/crews/dev-implement/application/run-dev-implement.ts +811 -0
  154. package/src/crews/dev-implement/application/run-role.ts +27 -0
  155. package/src/crews/dev-implement/application/suite-job.ts +118 -0
  156. package/src/crews/dev-implement/application/touched.ts +74 -0
  157. package/src/crews/dev-implement/crew.ork.ts +68 -0
  158. package/src/crews/dev-implement/domain/contracts.ts +256 -0
  159. package/src/crews/dev-implement/domain/correction.ts +102 -0
  160. package/src/crews/dev-implement/domain/cycles.ts +35 -0
  161. package/src/crews/dev-implement/domain/implement-budget.ts +29 -0
  162. package/src/crews/dev-implement/domain/roles.ts +53 -0
  163. package/src/crews/dev-implement/domain/sheet-edits.ts +75 -0
  164. package/src/crews/dev-implement/domain/sheet-ticks.ts +22 -0
  165. package/src/crews/dev-implement/domain/step-checks.ts +136 -0
  166. package/src/crews/dev-implement/domain/step-section.ts +127 -0
  167. package/src/crews/dev-learn/application/learn-backlog.ts +58 -0
  168. package/src/crews/dev-learn/application/learn-prompt.ts +140 -0
  169. package/src/crews/dev-learn/application/run-dev-learn.ts +553 -0
  170. package/src/crews/dev-learn/crew.ork.ts +52 -0
  171. package/src/crews/dev-learn/domain/learn-answer.ts +235 -0
  172. package/src/crews/dev-learn/domain/owner-lines.ts +86 -0
  173. package/src/crews/dev-learn/domain/proposals-render.ts +96 -0
  174. package/src/crews/dev-plan/application/anchor-paths.ts +76 -0
  175. package/src/crews/dev-plan/application/inventory.ts +170 -0
  176. package/src/crews/dev-plan/application/plan-prompt.ts +159 -0
  177. package/src/crews/dev-plan/application/run-dev-plan.ts +455 -0
  178. package/src/crews/dev-plan/crew.ork.ts +109 -0
  179. package/src/crews/dev-plan/domain/inventory-model.ts +95 -0
  180. package/src/crews/dev-plan/domain/plan-answer.ts +738 -0
  181. package/src/crews/dev-plan/domain/plan-render.ts +307 -0
  182. package/src/crews/dev-spec/application/run-dev-spec.ts +206 -0
  183. package/src/crews/dev-spec/application/spec-prompt.ts +98 -0
  184. package/src/crews/dev-spec/crew.ork.ts +108 -0
  185. package/src/crews/dev-spec/domain/spec-answer.ts +253 -0
  186. package/src/crews/dev-spec/domain/spec-render.ts +76 -0
  187. package/src/crews/dev-verify/application/audit.ts +259 -0
  188. package/src/crews/dev-verify/application/auditor-prompt.ts +323 -0
  189. package/src/crews/dev-verify/application/capture.ts +303 -0
  190. package/src/crews/dev-verify/application/run-dev-verify.ts +409 -0
  191. package/src/crews/dev-verify/application/run-gate.ts +202 -0
  192. package/src/crews/dev-verify/crew.ork.ts +103 -0
  193. package/src/crews/dev-verify/domain/audit-answer.ts +150 -0
  194. package/src/crews/dev-verify/domain/auditor-charter.ts +21 -0
  195. package/src/crews/dev-verify/domain/capture-sections.ts +137 -0
  196. package/src/crews/dev-verify/domain/commands.ts +103 -0
  197. package/src/crews/dev-verify/domain/gate.ts +126 -0
  198. package/src/crews/dev-verify/domain/mechanical-table.ts +163 -0
  199. package/src/crews/dev-verify/domain/runtime-cut.ts +13 -0
  200. package/src/crews/dev-verify/domain/sheet-facts.ts +4 -0
  201. package/src/crews/dev-verify/domain/text.ts +20 -0
  202. package/src/crews/dev-verify/domain/verdict.ts +127 -0
  203. package/src/crews/git-commit/application/draft.ts +154 -0
  204. package/src/crews/git-commit/application/run-git-commit.ts +116 -0
  205. package/src/crews/git-commit/crew.ork.ts +52 -0
  206. package/src/crews/git-commit/domain/commit.ts +220 -0
  207. package/src/crews/init-verifiers/application/authoring.ts +89 -0
  208. package/src/crews/init-verifiers/application/prompts.ts +103 -0
  209. package/src/crews/init-verifiers/application/run-init-verifiers.ts +25 -0
  210. package/src/crews/init-verifiers/crew.ork.ts +34 -0
  211. package/src/crews/init-verifiers/domain/commands-section.ts +36 -0
  212. package/src/crews/init-verifiers/domain/readiness.ts +23 -0
  213. package/src/crews/main-loop/application/auto-compact.ts +77 -0
  214. package/src/crews/main-loop/application/context-gather.ts +133 -0
  215. package/src/crews/main-loop/application/run-main-loop.ts +350 -0
  216. package/src/crews/main-loop/application/turn-prompt.ts +112 -0
  217. package/src/crews/main-loop/crew.ork.ts +119 -0
  218. package/src/crews/main-loop/domain/autocompact.ts +27 -0
  219. package/src/crews/main-loop/domain/prompt-assembly.ts +521 -0
  220. package/src/crews/main-loop/domain/turn-chains.ts +129 -0
  221. package/src/crews/project-init/application/detect.ts +122 -0
  222. package/src/crews/project-init/application/prompts.ts +101 -0
  223. package/src/crews/project-init/application/run-project-init.ts +31 -0
  224. package/src/crews/project-init/crew.ork.ts +35 -0
  225. package/src/crews/project-init/domain/conventions.ts +36 -0
  226. package/src/crews/project-init/domain/existing-files.ts +63 -0
  227. package/src/crews/project-init/domain/package-map.ts +73 -0
  228. package/src/crews/session-compact/crew.ork.ts +55 -0
  229. package/src/crews/shared-memory-admit/crew.ork.ts +48 -0
  230. package/src/crews/speech/application/run-speech.ts +25 -0
  231. package/src/crews/speech/crew.ork.ts +37 -0
  232. package/src/shared/application/agents/child-agent.ts +255 -0
  233. package/src/shared/application/agents/run-sub-agent.ts +96 -0
  234. package/src/shared/application/answer-language.ts +14 -0
  235. package/src/shared/application/attached-skills.ts +36 -0
  236. package/src/shared/application/compaction/compact-session.ts +237 -0
  237. package/src/shared/application/compaction/extract-memories.ts +38 -0
  238. package/src/shared/application/compaction/restore-context.ts +78 -0
  239. package/src/shared/application/config-store.ts +123 -0
  240. package/src/shared/application/dev/brief-inventory.ts +113 -0
  241. package/src/shared/application/dev/close-batch.ts +83 -0
  242. package/src/shared/application/dev/find-repo-pack.ts +77 -0
  243. package/src/shared/application/dev/learn-decision.ts +252 -0
  244. package/src/shared/application/dev/load-dev-context.ts +266 -0
  245. package/src/shared/application/dev/measure-access-cost.ts +68 -0
  246. package/src/shared/application/dev/plan-source.ts +112 -0
  247. package/src/shared/application/dev/preflight.ts +71 -0
  248. package/src/shared/application/dev/project-files.ts +17 -0
  249. package/src/shared/application/dev/question-round.ts +52 -0
  250. package/src/shared/application/dev/resolve-work-folder.ts +133 -0
  251. package/src/shared/application/dev/script-tool-slot.ts +27 -0
  252. package/src/shared/application/dev/settle-questions.ts +55 -0
  253. package/src/shared/application/dev/source-review.ts +63 -0
  254. package/src/shared/application/dev/source-step.ts +150 -0
  255. package/src/shared/application/dev/spend.ts +42 -0
  256. package/src/shared/application/dev/step-precedents.ts +89 -0
  257. package/src/shared/application/dev/tool-call-policy.ts +89 -0
  258. package/src/shared/application/dev/tool-callbacks.ts +215 -0
  259. package/src/shared/application/dev/tool-trace-recorder.ts +45 -0
  260. package/src/shared/application/dev/verdict-sources.ts +48 -0
  261. package/src/shared/application/dev/wrapped-tools.ts +145 -0
  262. package/src/shared/application/extra-tools.ts +70 -0
  263. package/src/shared/application/git/batch-worktree.ts +97 -0
  264. package/src/shared/application/git/commit-files.ts +186 -0
  265. package/src/shared/application/git/merge-batch.ts +63 -0
  266. package/src/shared/application/git/open-pull-request.ts +51 -0
  267. package/src/shared/application/instructions-file.ts +19 -0
  268. package/src/shared/application/json-file.ts +34 -0
  269. package/src/shared/application/llm-profile.ts +35 -0
  270. package/src/shared/application/permission-rules.ts +159 -0
  271. package/src/shared/application/ports/approvals.ts +20 -0
  272. package/src/shared/application/ports/clock.ts +5 -0
  273. package/src/shared/application/ports/code-index.ts +93 -0
  274. package/src/shared/application/ports/crew.ts +60 -0
  275. package/src/shared/application/ports/files.ts +21 -0
  276. package/src/shared/application/ports/human.ts +13 -0
  277. package/src/shared/application/ports/llm.ts +54 -0
  278. package/src/shared/application/ports/memory.ts +30 -0
  279. package/src/shared/application/ports/progress.ts +23 -0
  280. package/src/shared/application/ports/runtime.ts +15 -0
  281. package/src/shared/application/ports/session.ts +74 -0
  282. package/src/shared/application/ports/shared-memory.ts +26 -0
  283. package/src/shared/application/ports/shell.ts +40 -0
  284. package/src/shared/application/ports/telemetry.ts +45 -0
  285. package/src/shared/application/ports/tools.ts +46 -0
  286. package/src/shared/application/ports/usage.ts +45 -0
  287. package/src/shared/application/ports.ts +27 -0
  288. package/src/shared/application/project-manifests.ts +106 -0
  289. package/src/shared/application/session-io.ts +84 -0
  290. package/src/shared/application/session-state.ts +36 -0
  291. package/src/shared/application/shared-memory/admit-entries.ts +177 -0
  292. package/src/shared/application/shared-memory/harvest-after-gaps.ts +72 -0
  293. package/src/shared/application/shared-memory/harvest-mistakes.ts +44 -0
  294. package/src/shared/application/shared-memory/import-agent-memory.ts +117 -0
  295. package/src/shared/application/shared-memory/memory-files.ts +110 -0
  296. package/src/shared/application/shared-memory/memory-settings.ts +93 -0
  297. package/src/shared/application/shared-memory/push-candidate.ts +146 -0
  298. package/src/shared/application/shared-memory/recall-precedents.ts +69 -0
  299. package/src/shared/application/state-snapshot.ts +38 -0
  300. package/src/shared/application/workflow/workflow-state.ts +135 -0
  301. package/src/shared/domain/agent-policy/behavior-flags.ts +168 -0
  302. package/src/shared/domain/agent-policy/extra-tools.ts +69 -0
  303. package/src/shared/domain/agent-policy/memory-categories.ts +6 -0
  304. package/src/shared/domain/agent-policy/mode-policy.ts +51 -0
  305. package/src/shared/domain/agent-policy/output-styles.ts +11 -0
  306. package/src/shared/domain/agent-policy/permission.ts +623 -0
  307. package/src/shared/domain/agent-policy/rule-sets.ts +412 -0
  308. package/src/shared/domain/agent-policy/tool-access.ts +77 -0
  309. package/src/shared/domain/agent-registry.ts +142 -0
  310. package/src/shared/domain/agents/built-in-charters.ts +43 -0
  311. package/src/shared/domain/agents/chain.ts +30 -0
  312. package/src/shared/domain/agents/charter.ts +61 -0
  313. package/src/shared/domain/agents/exclusive.ts +24 -0
  314. package/src/shared/domain/agents/instances.ts +249 -0
  315. package/src/shared/domain/code-intel-contract.ts +356 -0
  316. package/src/shared/domain/code-intel-routing.ts +113 -0
  317. package/src/shared/domain/compact-outcome.ts +44 -0
  318. package/src/shared/domain/compaction-thresholds.ts +161 -0
  319. package/src/shared/domain/compaction.ts +379 -0
  320. package/src/shared/domain/config-schema.ts +421 -0
  321. package/src/shared/domain/dev/access-cost.ts +226 -0
  322. package/src/shared/domain/dev/artefacts.ts +50 -0
  323. package/src/shared/domain/dev/batches-concurrency.ts +36 -0
  324. package/src/shared/domain/dev/batches-state.ts +49 -0
  325. package/src/shared/domain/dev/build-commands.ts +44 -0
  326. package/src/shared/domain/dev/call-guard.ts +341 -0
  327. package/src/shared/domain/dev/carried-text.ts +49 -0
  328. package/src/shared/domain/dev/design-rules.ts +100 -0
  329. package/src/shared/domain/dev/learn-proposals.ts +175 -0
  330. package/src/shared/domain/dev/learn-state.ts +93 -0
  331. package/src/shared/domain/dev/path-args.ts +42 -0
  332. package/src/shared/domain/dev/path-rebase.ts +93 -0
  333. package/src/shared/domain/dev/plan-checks.ts +190 -0
  334. package/src/shared/domain/dev/plan-format.ts +180 -0
  335. package/src/shared/domain/dev/project-files.ts +43 -0
  336. package/src/shared/domain/dev/questions.ts +249 -0
  337. package/src/shared/domain/dev/reading-rule.ts +41 -0
  338. package/src/shared/domain/dev/repo-pack.ts +237 -0
  339. package/src/shared/domain/dev/review-answer.ts +150 -0
  340. package/src/shared/domain/dev/review-prompt.ts +221 -0
  341. package/src/shared/domain/dev/reviewer-charter.ts +31 -0
  342. package/src/shared/domain/dev/sheet-facts.ts +83 -0
  343. package/src/shared/domain/dev/spec-format.ts +183 -0
  344. package/src/shared/domain/dev/step-budget.ts +72 -0
  345. package/src/shared/domain/dev/step-rules.ts +110 -0
  346. package/src/shared/domain/dev/test-commands.ts +90 -0
  347. package/src/shared/domain/dev/test-output.ts +33 -0
  348. package/src/shared/domain/dev/test-paths.ts +40 -0
  349. package/src/shared/domain/dev/tool-guards.ts +64 -0
  350. package/src/shared/domain/dev/trait-pattern.ts +83 -0
  351. package/src/shared/domain/dev/verdict-format.ts +169 -0
  352. package/src/shared/domain/dev/whitespace.ts +34 -0
  353. package/src/shared/domain/dev/work-folder.ts +67 -0
  354. package/src/shared/domain/dev/yaml-subset.ts +403 -0
  355. package/src/shared/domain/git/close.ts +273 -0
  356. package/src/shared/domain/git/pull-request.ts +96 -0
  357. package/src/shared/domain/git/worktree.ts +46 -0
  358. package/src/shared/domain/index-languages.ts +16 -0
  359. package/src/shared/domain/instructions-file.ts +18 -0
  360. package/src/shared/domain/iso-day.ts +4 -0
  361. package/src/shared/domain/llm-failure.ts +106 -0
  362. package/src/shared/domain/llm-profile.ts +25 -0
  363. package/src/shared/domain/marked-message.ts +33 -0
  364. package/src/shared/domain/model-catalog.ts +86 -0
  365. package/src/shared/domain/permission-modes.ts +103 -0
  366. package/src/shared/domain/prelude.ts +92 -0
  367. package/src/shared/domain/project-manifests.ts +83 -0
  368. package/src/shared/domain/search-routing.ts +85 -0
  369. package/src/shared/domain/secret-patterns.ts +45 -0
  370. package/src/shared/domain/session-keys.ts +85 -0
  371. package/src/shared/domain/session-start.ts +60 -0
  372. package/src/shared/domain/session-summary.ts +13 -0
  373. package/src/shared/domain/severity.ts +72 -0
  374. package/src/shared/domain/sha1.ts +61 -0
  375. package/src/shared/domain/shared-memory/agent-memory-import.ts +143 -0
  376. package/src/shared/domain/shared-memory/candidates.ts +41 -0
  377. package/src/shared/domain/shared-memory/entry.ts +145 -0
  378. package/src/shared/domain/shared-memory/front-matter.ts +183 -0
  379. package/src/shared/domain/shared-memory/gate.ts +44 -0
  380. package/src/shared/domain/shared-memory/harvest.ts +61 -0
  381. package/src/shared/domain/shared-memory/layout.ts +187 -0
  382. package/src/shared/domain/shared-memory/precedents-block.ts +93 -0
  383. package/src/shared/domain/shared-memory/refused.ts +84 -0
  384. package/src/shared/domain/shared-memory/verdict-rows.ts +134 -0
  385. package/src/shared/domain/snip-turns.ts +45 -0
  386. package/src/shared/domain/speech.ts +20 -0
  387. package/src/shared/domain/strip.ts +88 -0
  388. package/src/shared/domain/tool-trace.ts +122 -0
  389. package/src/shared/domain/types.ts +67 -0
  390. package/src/shared/domain/verifiers.ts +37 -0
  391. package/src/shared/domain/vfs.ts +9 -0
  392. package/src/shared/domain/workflow/state-file.ts +140 -0
  393. package/src/shared/infrastructure/globals.ts +52 -0
  394. package/src/shared/infrastructure/orkeon/approvals.ts +24 -0
  395. package/src/shared/infrastructure/orkeon/child-agents.ts +127 -0
  396. package/src/shared/infrastructure/orkeon/code-index.ts +120 -0
  397. package/src/shared/infrastructure/orkeon/crew-host.ts +27 -0
  398. package/src/shared/infrastructure/orkeon/crew-memory.ts +12 -0
  399. package/src/shared/infrastructure/orkeon/dev-deps.ts +172 -0
  400. package/src/shared/infrastructure/orkeon/files.ts +40 -0
  401. package/src/shared/infrastructure/orkeon/github-pull-requests.ts +29 -0
  402. package/src/shared/infrastructure/orkeon/host-provider.ts +22 -0
  403. package/src/shared/infrastructure/orkeon/human-input.ts +59 -0
  404. package/src/shared/infrastructure/orkeon/llm-profile.ts +38 -0
  405. package/src/shared/infrastructure/orkeon/llm.ts +109 -0
  406. package/src/shared/infrastructure/orkeon/memory-store.ts +41 -0
  407. package/src/shared/infrastructure/orkeon/memory-tools.ts +131 -0
  408. package/src/shared/infrastructure/orkeon/permission-rules.ts +42 -0
  409. package/src/shared/infrastructure/orkeon/progress.ts +24 -0
  410. package/src/shared/infrastructure/orkeon/run-state.ts +17 -0
  411. package/src/shared/infrastructure/orkeon/runtime-info.ts +30 -0
  412. package/src/shared/infrastructure/orkeon/runtime-tools.ts +60 -0
  413. package/src/shared/infrastructure/orkeon/script-tools.ts +134 -0
  414. package/src/shared/infrastructure/orkeon/session-store.ts +138 -0
  415. package/src/shared/infrastructure/orkeon/session-switch.ts +23 -0
  416. package/src/shared/infrastructure/orkeon/shared-memory.ts +61 -0
  417. package/src/shared/infrastructure/orkeon/shell-jobs.ts +75 -0
  418. package/src/shared/infrastructure/orkeon/shell.ts +31 -0
  419. package/src/shared/infrastructure/orkeon/telemetry.ts +63 -0
  420. package/src/shared/infrastructure/orkeon/tool-catalogue.ts +75 -0
  421. package/src/shared/infrastructure/orkeon/tool-results.ts +120 -0
  422. package/src/shared/infrastructure/orkeon/usage.ts +74 -0
  423. package/src/shared/infrastructure/orkeon/wiring.ts +118 -0
@@ -0,0 +1,837 @@
1
+ #!/usr/bin/env pwsh
2
+ <#
3
+ .SYNOPSIS
4
+ Start the Orkeon Code REPL on a project (Windows / PowerShell twin of ./orkeon-code).
5
+
6
+ .EXAMPLE
7
+ .\orkeon-code.ps1 # the current directory is the project
8
+ .\orkeon-code.ps1 -Workspace C:\src\app
9
+ .\orkeon-code.ps1 -Mode docker -Settings .\config\appsettings.local.json
10
+ .\orkeon-code.ps1 -Trust # this run only, without asking (nothing stored)
11
+ .\orkeon-code.ps1 -Continue # the last session of this project (--continue, -c)
12
+ .\orkeon-code.ps1 --resume [<n> | <id>] # list the saved sessions of this project and pick one
13
+ .\orkeon-code.ps1 trust list | add <path> | remove <path> | check <path> [--trust]
14
+ .\orkeon-code.ps1 setup # write %USERPROFILE%\.orkeon-code\appsettings.json (never the key)
15
+
16
+ .NOTES
17
+ Modes: tool (orkeon-repl on PATH, from the full Orkeon release .zip (the .msi has no orkeon-repl), the
18
+ Debian package or the dotnet tool, or $env:ORKEON_REPL) and docker
19
+ (ghcr.io/orkeon/orkeon-runners:latest, the last release, not the pin). The source mode is only in the
20
+ bash launcher. Folder trust, per-project state, sessions, settings, API key, model and $env:ORKEON_CODE_AUDIO_DIR (speech-to-text,
21
+ tool mode): see the header of ./orkeon-code.
22
+ #>
23
+ # No positional binding: a bare word (trust, setup, a REPL argument) lands in $Extra, never in -Mode.
24
+ [CmdletBinding(PositionalBinding = $false)]
25
+ param(
26
+ [ValidateSet('', 'docker', 'tool')] [string] $Mode = $env:ORKEON_CODE_MODE,
27
+ [string] $Workspace = (Get-Location).Path,
28
+ [string] $Settings = $env:ORKEON_CODE_SETTINGS,
29
+ [switch] $Version,
30
+ [switch] $Trust,
31
+ [switch] $Continue,
32
+ [switch] $Resume,
33
+ [Parameter(ValueFromRemainingArguments = $true)] [string[]] $Extra = @()
34
+ )
35
+ $ErrorActionPreference = 'Stop'
36
+
37
+ # A subcommand of ./orkeon-code (trust, setup) is the first argument, and takes the rest as its own.
38
+ $Sub = $null
39
+ $SubArgs = @()
40
+ if ($Extra.Count -gt 0 -and $Extra[0] -cin @('trust', 'setup')) {
41
+ $Sub = $Extra[0]
42
+ $SubArgs = @($Extra | Select-Object -Skip 1)
43
+ $Extra = @()
44
+ }
45
+
46
+ $resumeChoice = ''
47
+ $Help = $false
48
+ # The long options of ./orkeon-code, as a .cmd wrapper passes them (%*): --settings x, --settings=x, --workspace,
49
+ # --mode, --version and --trust bind the parameters above; a -- left in the arguments is dropped, and what follows
50
+ # it goes to the REPL as is.
51
+ $rest = @()
52
+ for ($i = 0; $i -lt $Extra.Count; $i++) {
53
+ $a = $Extra[$i]
54
+ if ($a -eq '--') {
55
+ if ($i + 1 -lt $Extra.Count) { $rest += $Extra[($i + 1)..($Extra.Count - 1)] }
56
+ break
57
+ }
58
+ $name = $a; $value = $null
59
+ if ($a -match '^(--(?:settings|workspace|mode))=(.*)$') { $name = $Matches[1]; $value = $Matches[2] }
60
+ if ($name -eq '--version') { $Version = [switch] $true }
61
+ elseif ($name -cin @('-h', '--help')) { $Help = $true }
62
+ elseif ($name -eq '--demo') { throw '--demo is only in the bash launcher (./orkeon-code --demo): it builds its fixture with scripts/setup-fixture.sh.' }
63
+ elseif ($name -eq '--trust') { $Trust = [switch] $true }
64
+ elseif ($name -cin @('--continue', '-c')) { $Continue = [switch] $true }
65
+ elseif ($name -match '^--resume(=(.*))?$') {
66
+ $Resume = [switch] $true
67
+ if ($Matches[1]) { $resumeChoice = $Matches[2] }
68
+ elseif ($i + 1 -lt $Extra.Count -and -not $Extra[$i + 1].StartsWith('-')) { $i++; $resumeChoice = $Extra[$i] }
69
+ }
70
+ elseif ($name -in @('--settings', '--workspace', '--mode')) {
71
+ if ($null -eq $value) {
72
+ if ($i + 1 -ge $Extra.Count) { throw "$name needs a value." }
73
+ $i++; $value = $Extra[$i]
74
+ }
75
+ if ($name -eq '--settings') { $Settings = $value }
76
+ elseif ($name -eq '--workspace') { $Workspace = $value }
77
+ elseif ($value -notin @('docker', 'tool')) {
78
+ # Checked before the assignment: -Mode's ValidateSet would refuse it with its own message.
79
+ throw "Unknown mode '$value' (--mode): docker or tool. The source mode is only in the bash launcher."
80
+ }
81
+ else { $Mode = $value }
82
+ } else { $rest += $a }
83
+ }
84
+ $Extra = $rest
85
+ # -h / --help: this file's help, as ./orkeon-code prints its header.
86
+ if ($Help) { Get-Help $PSCommandPath -Detailed; exit 0 }
87
+ # ValidateSet does not check its default ($env:ORKEON_CODE_MODE): an unknown mode is refused
88
+ # here rather than run as another one (./orkeon-code's source mode is not in this launcher).
89
+ if (-not $Sub -and $Mode -and $Mode -notin @('docker', 'tool')) {
90
+ throw "Unknown mode '$Mode' (-Mode, --mode or `$env:ORKEON_CODE_MODE): docker or tool. The source mode is only in the bash launcher."
91
+ }
92
+
93
+ # ── Folder trust (as ./orkeon-code: the same store, the same layout, the same answers) ──
94
+ # Windows compares paths without case; elsewhere as they are.
95
+ $onWindows = [Environment]::OSVersion.Platform -eq 'Win32NT'
96
+
97
+ function Get-TrustFile { Join-Path $CodeHome 'trusted-folders.json' }
98
+
99
+ # The stored folders, as { Path; TrustedAt }; throws, naming the file, on a store it cannot read. The layout is
100
+ # the one Write-TrustStore gives, checked line by line as ./orkeon-code's awk does (no ConvertFrom-Json: pwsh 7 would
101
+ # turn the dates into DateTime, and would take a layout the bash launcher refuses).
102
+ function Get-TrustEntries {
103
+ $file = Get-TrustFile
104
+ if (-not (Test-Path -LiteralPath $file) -or (Get-Item -LiteralPath $file).Length -eq 0) { return }
105
+ $bad = "$file is not a trust store this launcher wrote: nothing is trusted, and the file is kept as it is. " +
106
+ 'Fix it, or move it away and trust your folders again (orkeon-code trust add <path>).'
107
+ $str = '"((?:[^"\\\x00-\x1f]|\\["\\/])*)"'
108
+ $entry = '^[ \t]*\{[ \t]*"path"[ \t]*:[ \t]*' + $str + '[ \t]*,[ \t]*"trustedAt"[ \t]*:[ \t]*' + $str + '[ \t]*\}[ \t]*(,?)[ \t]*$'
109
+ $unescape = { param($v) [regex]::Replace($v, '\\(["\\/])', '$1') }
110
+ $lines = @([System.IO.File]::ReadAllLines($file) | ForEach-Object { $_ -replace "`r$", '' } | Where-Object { $_ -notmatch '^[ \t]*$' })
111
+ $out = @()
112
+ $step = 0; $comma = $false
113
+ foreach ($line in $lines) {
114
+ switch ($step) {
115
+ 0 { if ($line -cnotmatch '^[ \t]*\{[ \t]*$') { throw $bad }; $step = 1 }
116
+ 1 { if ($line -cnotmatch '^[ \t]*"version"[ \t]*:[ \t]*1[ \t]*,[ \t]*$') { throw $bad }; $step = 2 }
117
+ 2 {
118
+ if ($line -cmatch '^[ \t]*"folders"[ \t]*:[ \t]*\[[ \t]*\][ \t]*$') { $step = 4 }
119
+ elseif ($line -cmatch '^[ \t]*"folders"[ \t]*:[ \t]*\[[ \t]*$') { $step = 3 }
120
+ else { throw $bad }
121
+ }
122
+ 3 {
123
+ if ($line -cmatch '^[ \t]*\][ \t]*$') { if ($out.Count -gt 0 -and $comma) { throw $bad }; $step = 4 }
124
+ else {
125
+ if ($out.Count -gt 0 -and -not $comma) { throw $bad }
126
+ $m = [regex]::Match($line, $entry)
127
+ if (-not $m.Success -or -not $m.Groups[1].Value) { throw $bad }
128
+ $out += [pscustomobject]@{ Path = (& $unescape $m.Groups[1].Value); TrustedAt = (& $unescape $m.Groups[2].Value) }
129
+ $comma = $m.Groups[3].Value -eq ','
130
+ }
131
+ }
132
+ 4 { if ($line -cnotmatch '^[ \t]*\}[ \t]*$') { throw $bad }; $step = 5 }
133
+ default { throw $bad }
134
+ }
135
+ }
136
+ if ($step -ne 5) { throw $bad }
137
+ $out
138
+ }
139
+
140
+ # Readable and writable by the user alone where modes exist: SetUnixFileMode from .NET 7 (PowerShell 7.3), else chmod.
141
+ function Set-OwnerOnly([string] $path, [string] $mode) {
142
+ if ($onWindows) { return }
143
+ try { [System.IO.File]::SetUnixFileMode($path, $(if ($mode -eq '700') { 'UserRead, UserWrite, UserExecute' } else { 'UserRead, UserWrite' })) }
144
+ catch { & chmod $mode -- $path 2>$null }
145
+ }
146
+
147
+ # Writes the store in ./orkeon-code's layout, one folder per line: a temporary file, then a rename.
148
+ function Write-TrustStore($entries) {
149
+ $file = Get-TrustFile
150
+ if (-not (Test-Path -LiteralPath $CodeHome)) { New-Item -ItemType Directory -Force -Path $CodeHome | Out-Null; Set-OwnerOnly $CodeHome '700' }
151
+ $escape = { param($s) ($s -replace '\\', '\\') -replace '"', '\"' }
152
+ $lines = @($entries | ForEach-Object { ' { "path": "' + (& $escape $_.Path) + '", "trustedAt": "' + (& $escape $_.TrustedAt) + '" }' })
153
+ $folders = if ($lines.Count -eq 0) { " `"folders`": []`n" } else { " `"folders`": [`n" + ($lines -join ",`n") + "`n ]`n" }
154
+ $tmp = "$file.tmp.$PID"
155
+ [System.IO.File]::WriteAllText($tmp, "{`n `"version`": 1,`n$folders}`n")
156
+ Set-OwnerOnly $tmp '600'
157
+ Move-Item -LiteralPath $tmp -Destination $file -Force
158
+ }
159
+
160
+ # The folder, full and with every link on its path resolved (bash's `pwd -P`), or $null when it is not a folder
161
+ # or a link on its path cannot be resolved.
162
+ function Get-CanonicalDir([string] $path) {
163
+ $item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
164
+ if (-not $item -or -not $item.PSIsContainer) { return $null }
165
+ $full = $item.FullName
166
+ if (-not $onWindows) {
167
+ $real = & sh -c 'cd -- "$1" && pwd -P' sh $full 2>$null
168
+ if ($LASTEXITCODE -ne 0 -or -not $real) { return $null }
169
+ return "$real"
170
+ }
171
+ # Windows: each component in turn; a link (symbolic link, junction) replaces the path up to it by its target.
172
+ for ($n = 0; $n -lt 40; $n++) {
173
+ $full = [System.IO.Path]::GetFullPath($full)
174
+ $root = [System.IO.Path]::GetPathRoot($full)
175
+ $parts = @($full.Substring($root.Length).Split([char[]] @('\', '/'), [StringSplitOptions]::RemoveEmptyEntries))
176
+ $cur = $root
177
+ $changed = $false
178
+ for ($i = 0; $i -lt $parts.Count; $i++) {
179
+ $cur = Join-Path $cur $parts[$i]
180
+ $link = Get-Item -LiteralPath $cur -Force -ErrorAction SilentlyContinue
181
+ if ($link -and $link.LinkType) {
182
+ $target = "$(@($link.Target)[0])" -replace '^\\\\\?\\', ''
183
+ if (-not $target) { return $null }
184
+ if (-not [System.IO.Path]::IsPathRooted($target)) { $target = Join-Path (Split-Path $cur -Parent) $target }
185
+ $full = if ($i + 1 -lt $parts.Count) { Join-Path $target ($parts[($i + 1)..($parts.Count - 1)] -join '\') } else { $target }
186
+ $changed = $true
187
+ break
188
+ }
189
+ }
190
+ if (-not $changed) {
191
+ if ($full.Length -gt $root.Length) { $full = $full.TrimEnd('\', '/') }
192
+ return $full
193
+ }
194
+ }
195
+ $null
196
+ }
197
+
198
+ # The stored folder that covers <folder> (itself or an ancestor), or $null.
199
+ function Get-TrustedBy([string] $folder) {
200
+ $cmp = if ($onWindows) { [StringComparison]::OrdinalIgnoreCase } else { [StringComparison]::Ordinal }
201
+ $sep = [string] [System.IO.Path]::DirectorySeparatorChar
202
+ foreach ($e in @(Get-TrustEntries)) {
203
+ if ([string]::Equals($e.Path, $folder, $cmp)) { return $e.Path }
204
+ $prefix = if ($e.Path.EndsWith($sep)) { $e.Path } else { $e.Path + $sep } # a root (/, C:\) ends with one already
205
+ if ($folder.StartsWith($prefix, $cmp)) { return $e.Path }
206
+ }
207
+ $null
208
+ }
209
+
210
+ function Add-TrustedFolder([string] $folder) {
211
+ if ($folder -match '[\x00-\x1f]') { throw "A folder whose path holds a control character cannot be trusted: $folder" }
212
+ $entries = @(Get-TrustEntries)
213
+ Write-TrustStore ($entries + [pscustomobject]@{ Path = $folder; TrustedAt = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') })
214
+ }
215
+
216
+ # Returns when <folder> may start: trusted, -Trust or CI, or trusted now in a terminal; exits otherwise
217
+ # (<declined> on a decline, 3 without a terminal). Nothing of the folder is read here.
218
+ function Confirm-Trusted([string] $folder, [bool] $given, [int] $declined) {
219
+ if ($given -or ($env:ORKEON_CODE_TRUST -eq '1' -and $env:CI -ceq 'true')) { return }
220
+ if (Get-TrustedBy $folder) { return }
221
+ if ([Console]::IsInputRedirected) {
222
+ [Console]::Error.WriteLine("orkeon-code: $folder is not a trusted folder, and there is no terminal to ask in. Trust it once with " +
223
+ "'orkeon-code trust add $folder', or pass --trust for this run only.")
224
+ exit 3
225
+ }
226
+ [Console]::Error.WriteLine('orkeon-code: do you trust the files in this folder?')
227
+ [Console]::Error.WriteLine(" $folder")
228
+ [Console]::Error.WriteLine(' The agent reads its AGENTS.md, .orkeon/config.json and .orkeon/repo.yaml, may run the commands')
229
+ [Console]::Error.WriteLine(" .orkeon/repo.yaml names, and git runs the folder's hooks through the shell.")
230
+ if ([System.IO.Path]::GetPathRoot($folder) -eq $folder -or $folder -eq (Get-CanonicalDir $HOME)) {
231
+ [Console]::Error.WriteLine(' This trusts every folder below it.')
232
+ }
233
+ [Console]::Error.Write('[y] trust [n] quit: ')
234
+ $answer = [Console]::In.ReadLine()
235
+ if ("$answer".Trim().ToLowerInvariant() -in @('y', 'yes')) {
236
+ Add-TrustedFolder $folder
237
+ [Console]::Error.WriteLine("orkeon-code: trusted $folder (orkeon-code trust remove $folder takes it back).")
238
+ } else {
239
+ [Console]::Error.WriteLine('orkeon-code: not trusted, nothing started.')
240
+ exit $declined
241
+ }
242
+ }
243
+
244
+ # ── Per-project state and sessions (as ./orkeon-code) ──
245
+ # The runtime's folder name for a project (ProjectKey.Slug, Orkeon.Infrastructure/Session/ProjectKey.cs): the last
246
+ # segment, each UTF-16 unit an ASCII letter or digit lowercased, else '-', then '-' and the first 12 hex of the
247
+ # SHA-256 of the whole path, in UTF-8.
248
+ function Get-ProjectSlug([string] $path) {
249
+ $name = ($path.TrimEnd('/', '\') -split '[/\\]')[-1]
250
+ $out = -join @(foreach ($c in $name.ToCharArray()) {
251
+ $n = [int] $c
252
+ if (($n -ge 48 -and $n -le 57) -or ($n -ge 65 -and $n -le 90) -or ($n -ge 97 -and $n -le 122)) { [char]::ToLowerInvariant($c) } else { '-' }
253
+ })
254
+ $sha = [System.Security.Cryptography.SHA256]::Create()
255
+ try { $bytes = $sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($path)) } finally { $sha.Dispose() }
256
+ "$out-" + (-join @($bytes | ForEach-Object { $_.ToString('x2') })).Substring(0, 12)
257
+ }
258
+
259
+ # A string field of a JSON file as stored (its escapes unread), or $null.
260
+ function Get-JsonField([string] $file, [string] $field) {
261
+ $text = Get-Content -LiteralPath $file -Raw -Encoding UTF8 -ErrorAction SilentlyContinue
262
+ if ($text -match ('"' + $field + '"\s*:\s*"((?:[^"\\]|\\.)*)"')) { $Matches[1] } else { $null }
263
+ }
264
+
265
+ # Removes from history/ every file of the session $rawId (as stored, never the file name), before its new file lands
266
+ # there: a session /resume loaded in place goes on under its id, so its new file replaces the one it was loaded
267
+ # from, under its own name (no collision suffix). Nothing for an empty id.
268
+ function Remove-HistoryDuplicates([string] $history, [string] $rawId) {
269
+ if (-not $rawId) { return }
270
+ foreach ($other in @(Get-ChildItem -LiteralPath $history -File -Filter '*.json' -ErrorAction SilentlyContinue)) {
271
+ if ("$(Get-JsonField $other.FullName 'SessionId')" -eq $rawId) { Remove-Item -LiteralPath $other.FullName -Force }
272
+ }
273
+ }
274
+
275
+ # Moves every session file the runtime saved into history/, under <UTC time>-<session id>.json: the last.json of
276
+ # sessions/ and the archives /resume left beside it (<stamp>-archived.json, moved first so last.json is the newest),
277
+ # unless $sideOnly, and always those of side/<pid>/ (a start beside an open one, now ended). A session without a
278
+ # message (a start and a quit) is dropped, so it never pushes a real one out of the history; a session that goes on
279
+ # under the id of one already in the history replaces it there (Remove-HistoryDuplicates).
280
+ function Move-SessionsToHistory([string] $sessions, [string] $history, [string] $side, [bool] $sideOnly) {
281
+ $folders = @()
282
+ if (-not $sideOnly) { $folders += @(Get-ChildItem -LiteralPath $sessions -Directory -ErrorAction SilentlyContinue) }
283
+ foreach ($pidDir in @(Get-ChildItem -LiteralPath $side -Directory -ErrorAction SilentlyContinue)) {
284
+ $folders += @(Get-ChildItem -LiteralPath $pidDir.FullName -Directory -ErrorAction SilentlyContinue)
285
+ }
286
+ $files = @($folders | ForEach-Object { Get-ChildItem -LiteralPath $_.FullName -File -Filter '*.json' -ErrorAction SilentlyContinue })
287
+ $ordered = @($files | Where-Object { $_.Name -ne 'last.json' }) + @($files | Where-Object { $_.Name -eq 'last.json' })
288
+ foreach ($file in $ordered) {
289
+ $last = $file.FullName
290
+ if ((Get-Content -LiteralPath $last -Raw -Encoding UTF8 -ErrorAction SilentlyContinue) -match '"Messages"\s*:\s*\[\s*\]') {
291
+ Remove-Item -LiteralPath $last -Force; continue
292
+ }
293
+ $rawId = "$(Get-JsonField $last 'SessionId')"
294
+ $id = $rawId -replace '[^A-Za-z0-9._-]', '_'
295
+ if (-not $id) { $id = 'session' }
296
+ Remove-HistoryDuplicates $history $rawId
297
+ $stamp = [DateTime]::UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'", [System.Globalization.CultureInfo]::InvariantCulture)
298
+ $target = Join-Path $history "$stamp-$id.json"; $n = 2
299
+ while (Test-Path -LiteralPath $target) { $target = Join-Path $history "$stamp-$id-$n.json"; $n++ }
300
+ Move-Item -LiteralPath $last -Destination $target -Force
301
+ }
302
+ Get-ChildItem -LiteralPath $side -Directory -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force
303
+ }
304
+
305
+ # The history, newest first.
306
+ function Get-HistoryFiles([string] $history) {
307
+ @(Get-ChildItem -LiteralPath $history -File -Filter '*.json' -ErrorAction SilentlyContinue |
308
+ Sort-Object -Property Name -Descending -CaseSensitive)
309
+ }
310
+
311
+ # ── Settings: setup (as ./orkeon-code setup; the key is never asked) ──
312
+ # One line asked on the terminal: the answer, trimmed, or <default> when empty; $null at the end of input.
313
+ function Read-Answer([string] $question, [string] $default) {
314
+ [Console]::Error.Write($question)
315
+ $answer = [Console]::In.ReadLine()
316
+ if ($null -eq $answer) { return $null }
317
+ $answer = $answer.Trim()
318
+ if ($answer) { $answer } else { $default }
319
+ }
320
+
321
+ # Writes <target> from one of the examples, with the model and the name of the key's variable; $false when the
322
+ # user stops or keeps the existing file.
323
+ function Invoke-Setup([string] $target) {
324
+ if ([Console]::IsInputRedirected) { throw "setup asks its questions in a terminal: run 'orkeon-code setup' in one." }
325
+ if (Test-Path -LiteralPath $target) {
326
+ $answer = Read-Answer "orkeon-code: $target exists. Replace it? [y/N] " 'n'
327
+ if ("$answer".ToLowerInvariant() -notin @('y', 'yes')) { [Console]::Error.WriteLine("orkeon-code: $target kept."); return $false }
328
+ }
329
+ [Console]::Error.WriteLine("orkeon-code setup: the settings go to $target. The API key never does: only the name of the")
330
+ [Console]::Error.WriteLine('environment variable that holds it.')
331
+ [Console]::Error.WriteLine(' [1] a hosted, OpenAI-compatible endpoint (config/appsettings.example.json: DeepSeek)')
332
+ [Console]::Error.WriteLine(' [2] Ollama on this machine, no key (config/appsettings.ollama.example.json)')
333
+ while ($true) {
334
+ $answer = Read-Answer 'Provider [1]: ' '1'
335
+ if ($null -eq $answer) { return $false }
336
+ if ($answer -eq '1') { $example = Join-Path $Root 'config/appsettings.example.json'; break }
337
+ if ($answer -eq '2') { $example = Join-Path $Root 'config/appsettings.ollama.example.json'; break }
338
+ [Console]::Error.WriteLine('orkeon-code: answer 1 or 2.')
339
+ }
340
+ $settings = Get-Content -LiteralPath $example -Raw -Encoding UTF8 | ConvertFrom-Json
341
+ $defaultVar = $settings.Llm.ApiKeyEnvVar
342
+ while ($true) {
343
+ $model = Read-Answer "Model [$($settings.Llm.Model)]: " $settings.Llm.Model
344
+ if ($null -eq $model) { return $false }
345
+ # Never said back, and refused when it looks like a key: a key pasted at the wrong question.
346
+ if ($model -cmatch '^[A-Za-z0-9._:/@+-]+$' -and $model -cnotmatch '^sk-' -and $model -cnotmatch '^[A-Za-z0-9_-]{32,}$') { break }
347
+ [Console]::Error.WriteLine('orkeon-code: that is not a model id (letters, digits and . _ : / @ + -, not a key).')
348
+ }
349
+ $var = $null
350
+ if ($defaultVar) {
351
+ while ($true) {
352
+ $var = Read-Answer "Name of the environment variable that holds the API key [$defaultVar]: " $defaultVar
353
+ if ($null -eq $var) { return $false }
354
+ if ($var -cmatch '^[A-Z_][A-Z0-9_]{0,63}$') { break }
355
+ # Never said back: what was typed may be the key itself.
356
+ [Console]::Error.WriteLine('orkeon-code: that is not a variable name (capitals, digits and _). Type the name of the variable, never the key.')
357
+ }
358
+ $settings.Llm.ApiKeyEnvVar = $var
359
+ }
360
+ $settings.Llm.Model = $model
361
+ $settings._comment = 'Written by orkeon-code setup. The API key never goes in this file: ApiKeyEnvVar names the environment ' +
362
+ 'variable that holds it, and ORKEON_Llm__ApiKey, when set, wins over everything. Every key is explained in docs/configuration.md.'
363
+ if (-not (Test-Path -LiteralPath $CodeHome)) { New-Item -ItemType Directory -Force -Path $CodeHome | Out-Null; Set-OwnerOnly $CodeHome '700' }
364
+ $tmp = "$target.tmp.$PID"
365
+ [System.IO.File]::WriteAllText($tmp, ($settings | ConvertTo-Json -Depth 20) + "`n")
366
+ Set-OwnerOnly $tmp '600'
367
+ Move-Item -LiteralPath $tmp -Destination $target -Force
368
+ [Console]::Error.WriteLine("orkeon-code: wrote $target (model $model).")
369
+ if ($var) { [Console]::Error.WriteLine("orkeon-code: set the key before you start: `$env:$var = '<your key>'") }
370
+ $true
371
+ }
372
+
373
+ # The variables set below for the REPL are put back as they were when the script ends, so that none of them stays
374
+ # in the PowerShell session that ran it.
375
+ $savedEnv = @{}
376
+ foreach ($name in @('ORKEON_Llm__Model', 'Orkeon__Security__PermissionGate__Enabled', 'Orkeon__Cli__Session__StartScript',
377
+ 'Orkeon__Cli__Session__Persist', 'ORKEON_Orkeon__Cli__Session__SessionsDirectory',
378
+ 'ORKEON_Orkeon__Cli__Memory__RootDirectory',
379
+ 'ORKEON_ESBUILD_PATH',
380
+ 'ORKEON_ALLOW_EXTERNAL_MOUNTS', 'WHISPER_AUDIO_DIR', 'WHISPER_OUT_DIR',
381
+ 'ORKEON_MCP__Servers__whisper__Transport', 'ORKEON_MCP__Servers__whisper__Command',
382
+ 'ORKEON_MCP__Servers__whisper__TrustAnnotations',
383
+ 'ORKEON_MCP__Servers__whisper__Args__0', 'ORKEON_MCP__Servers__whisper__Args__1',
384
+ 'ORKEON_MCP__Servers__whisper__Args__2', 'ORKEON_MCP__Servers__whisper__Args__3',
385
+ 'ORKEON_MCP__Servers__whisper__Args__4', 'ORKEON_MCP__Servers__whisper__Args__5',
386
+ 'ORKEON_MCP__Servers__whisper__Args__6', 'ORKEON_MCP__Servers__whisper__Args__7',
387
+ 'ORKEON_MCP__Servers__whisper__Args__8', 'ORKEON_MCP__Servers__whisper__Args__9',
388
+ 'ORKEON_MCP__Servers__whisper__Args__10', 'ORKEON_MCP__Servers__whisper__Args__11',
389
+ 'ORKEON_MCP__Servers__whisper__Args__12',
390
+ 'WHISPER_MICROPHONE', 'WHISPER_SPEAKER', 'UV_PROJECT_ENVIRONMENT')) {
391
+ $savedEnv[$name] = [Environment]::GetEnvironmentVariable($name)
392
+ }
393
+ try {
394
+ $Root = $PSScriptRoot
395
+ # The pin is a commit of Orkeon's main (.orkeon-version, ADR 0013): the tool and docker modes run a release.
396
+ $OrkeonRef = (Get-Content (Join-Path $Root '.orkeon-version') -Raw).Trim()
397
+ $OrkeonPin = $OrkeonRef.Substring(0, 7)
398
+ $Image = if ($env:ORKEON_CODE_IMAGE) { $env:ORKEON_CODE_IMAGE } else { 'ghcr.io/orkeon/orkeon-runners:latest' }
399
+ $codeVersion = (Get-Content (Join-Path $Root 'package.json') -Raw | ConvertFrom-Json).version
400
+ # A clone (a .git, or the tests of an unpacked source archive) or an install, whose folder is never written to:
401
+ # an install's state goes under ORKEON_CODE_HOME (%USERPROFILE%\.orkeon-code).
402
+ $IsClone = Test-Path (Join-Path $Root '.git')
403
+ if (-not $IsClone) { $IsClone = Test-Path (Join-Path $Root 'tests') -PathType Container }
404
+ $CodeHome = if ($env:ORKEON_CODE_HOME) { $env:ORKEON_CODE_HOME } else { Join-Path $HOME '.orkeon-code' }
405
+ # Where the settings are looked for: %APPDATA% on Windows; elsewhere the XDG base the runtime uses (an absolute
406
+ # XDG_CONFIG_HOME, else ~/.config), as ./orkeon-code does.
407
+ $configBase = if ($env:APPDATA) { $env:APPDATA }
408
+ elseif ($env:XDG_CONFIG_HOME -and [System.IO.Path]::IsPathRooted($env:XDG_CONFIG_HOME)) { $env:XDG_CONFIG_HOME }
409
+ else { Join-Path $HOME '.config' }
410
+ $homeSettings = Join-Path $CodeHome 'appsettings.json'
411
+ $legacySettings = Join-Path $configBase 'orkeon-code/appsettings.json'
412
+ # What `orkeon init` writes and the REPL reads when no --settings is given (RunnerSettings.GetGlobalSettingsPath).
413
+ $runtimeSettings = Join-Path $configBase 'Orkeon/appsettings.json'
414
+
415
+ if ($Sub -eq 'setup') { if (Invoke-Setup $homeSettings) { exit 0 } else { exit 1 } }
416
+ if ($Sub -eq 'trust') {
417
+ $verb = if ($SubArgs.Count -gt 0) { $SubArgs[0] } else { '' }
418
+ $arg = if ($SubArgs.Count -gt 1) { $SubArgs[1] } else { $null }
419
+ $usage = 'usage: orkeon-code trust list | add <path> | remove <path> | check <path> [--trust]'
420
+ switch -CaseSensitive ($verb) {
421
+ 'list' {
422
+ foreach ($e in @(Get-TrustEntries)) { Write-Output "$($e.Path) (trusted $($e.TrustedAt))" }
423
+ exit 0
424
+ }
425
+ 'add' {
426
+ if (-not $arg) { throw 'trust add needs a folder.' }
427
+ $folder = Get-CanonicalDir $arg
428
+ if (-not $folder) { throw "Not a folder: $arg" }
429
+ $by = Get-TrustedBy $folder
430
+ if ($by -eq $folder) { Write-Output "orkeon-code: $folder is already trusted."; exit 0 }
431
+ if ($by) { Write-Output "orkeon-code: $folder is already trusted, through $by."; exit 0 }
432
+ Add-TrustedFolder $folder
433
+ Write-Output "orkeon-code: trusted $folder."
434
+ exit 0
435
+ }
436
+ 'remove' {
437
+ if (-not $arg) { throw 'trust remove needs a folder.' }
438
+ $target = Get-CanonicalDir $arg
439
+ if (-not $target) { $target = if ($arg.Length -gt [System.IO.Path]::GetPathRoot($arg).Length) { $arg.TrimEnd('\', '/') } else { $arg } }
440
+ $cmp = if ($onWindows) { [StringComparison]::OrdinalIgnoreCase } else { [StringComparison]::Ordinal }
441
+ $entries = @(Get-TrustEntries)
442
+ $kept = @($entries | Where-Object { -not [string]::Equals($_.Path, $target, $cmp) })
443
+ if ($kept.Count -eq $entries.Count) {
444
+ $by = Get-TrustedBy $target
445
+ if ($by) { throw "$target is not in the store: it is trusted through $by." }
446
+ throw "$target is not a trusted folder."
447
+ }
448
+ Write-TrustStore $kept
449
+ Write-Output "orkeon-code: $target is no longer trusted."
450
+ exit 0
451
+ }
452
+ 'check' {
453
+ # 0: it may start; 3: refused, no terminal; 4: declined in the terminal.
454
+ if (-not $arg) { throw 'trust check needs a folder.' }
455
+ $folder = Get-CanonicalDir $arg
456
+ if (-not $folder) { throw "Not a folder: $arg" }
457
+ Confirm-Trusted $folder ($Trust.IsPresent -or (($SubArgs.Count -gt 2) -and $SubArgs[2] -eq '--trust')) 4
458
+ exit 0
459
+ }
460
+ default { throw $usage }
461
+ }
462
+ }
463
+
464
+ if ($Version -or ($Extra -contains '--version')) {
465
+ # The Orkeon found, said without starting anything: the REPL has no --version flag, and docker pulls nothing.
466
+ $replName = if ($env:ORKEON_REPL) { ($env:ORKEON_REPL -split ' ')[0] } else { 'orkeon-repl' }
467
+ $replFound = Get-Command $replName -ErrorAction SilentlyContinue | Select-Object -First 1
468
+ # A mode forced by -Mode or ORKEON_CODE_MODE names its runtime; otherwise the auto-detection order speaks.
469
+ $found = if ($Mode -eq 'docker') { "image $Image (docker mode, not pulled)" }
470
+ elseif ($replFound -and $replFound.Source) {
471
+ $replPath = (Get-Item -LiteralPath $replFound.Source).FullName
472
+ $target = (Get-Item -LiteralPath $replPath).Target
473
+ if ($target) { $replPath = [IO.Path]::GetFullPath((Join-Path (Split-Path $replPath -Parent) "$target")) }
474
+ # An Orkeon release archive installs bin/orkeon-repl beside its VERSION file.
475
+ $versionFile = Join-Path (Split-Path (Split-Path $replPath -Parent) -Parent) 'VERSION'
476
+ if (Test-Path -LiteralPath $versionFile) { "$((Get-Content -LiteralPath $versionFile -Raw).Trim()) ($replName, $versionFile)" }
477
+ else { "unknown ($replPath)" }
478
+ } elseif (Get-Command docker -ErrorAction SilentlyContinue) { "image $Image (docker mode, not pulled)" }
479
+ else { 'none (see docs/getting-started.md)' }
480
+ $kind = if ($IsClone) { 'clone' } else { 'install' }
481
+ Write-Output "orkeon-code $codeVersion ($kind`: $Root)"
482
+ Write-Output "Orkeon $OrkeonPin expected, found: $found"
483
+ exit 0
484
+ }
485
+
486
+ # Full, its link resolved: the folder checked, stored and mounted is the same one.
487
+ $given = $Workspace
488
+ $Workspace = Get-CanonicalDir $Workspace
489
+ if (-not $Workspace) { throw "Workspace not found: $given" }
490
+ # Before anything of the project is read or mounted.
491
+ Confirm-Trusted $Workspace $Trust.IsPresent 0
492
+
493
+ # $runtimeOwn: Orkeon's own file, which the REPL reads itself when no --settings is passed.
494
+ $runtimeOwn = $false
495
+ if (-not $Settings) {
496
+ $candidates = @($homeSettings, $legacySettings)
497
+ if ($IsClone) { $candidates = @((Join-Path $Root 'config/appsettings.local.json')) + $candidates }
498
+ $Settings = $candidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
499
+ if (-not $Settings -and (Test-Path -LiteralPath $runtimeSettings)) { $Settings = $runtimeSettings; $runtimeOwn = $true }
500
+ if ($Settings -eq $legacySettings) { Write-Warning "$legacySettings is the old place of the settings: move it to $homeSettings." }
501
+ if (-not $Settings -and -not [Console]::IsInputRedirected) {
502
+ [Console]::Error.WriteLine('orkeon-code: no settings file yet.')
503
+ if (Invoke-Setup $homeSettings) { $Settings = $homeSettings }
504
+ }
505
+ }
506
+ if (-not $Settings -or -not (Test-Path $Settings)) {
507
+ if ($IsClone) { throw "No settings file. Run 'orkeon-code setup' in a terminal, copy config/appsettings.example.json to config/appsettings.local.json, or pass -Settings." }
508
+ throw "No settings file. Run 'orkeon-code setup' in a terminal, copy $(Join-Path $Root 'config/appsettings.example.json') to $homeSettings, or pass -Settings."
509
+ }
510
+ $Settings = (Resolve-Path $Settings).Path
511
+
512
+ $settingsText = Get-Content $Settings -Raw -Encoding UTF8 # Windows PowerShell 5.1 reads ANSI otherwise
513
+ $keyVar = if ($settingsText -match '"ApiKeyEnvVar"\s*:\s*"([A-Za-z_][A-Za-z0-9_]*)"') { $Matches[1] } else { $null }
514
+ if ($settingsText -notmatch '"Llm"') {
515
+ Write-Warning "$Settings has no `"Llm`" section: every turn would be empty."
516
+ } elseif (-not $env:ORKEON_Llm__ApiKey -and $keyVar -and -not [Environment]::GetEnvironmentVariable($keyVar)) {
517
+ Write-Warning "No API key: set `$env:$keyVar (named by Llm:ApiKeyEnvVar) or `$env:ORKEON_Llm__ApiKey."
518
+ }
519
+ if ($env:ORKEON_CODE_MODEL) { $env:ORKEON_Llm__Model = $env:ORKEON_CODE_MODEL }
520
+ # The host's permission gate checks every tool call against the session's rules (/permissions), then the
521
+ # mode, and asks you when the mode says so; off, no call is checked. On by default here; a settings file
522
+ # can still turn it off.
523
+ if (-not $env:Orkeon__Security__PermissionGate__Enabled) { $env:Orkeon__Security__PermissionGate__Enabled = 'true' }
524
+
525
+ if ($Continue -and $Resume) { throw '--continue and --resume do not go together: one brings the last session back, the other the one you pick.' }
526
+
527
+ if (-not $Mode) {
528
+ if ($env:ORKEON_REPL -or (Get-Command orkeon-repl -ErrorAction SilentlyContinue)) { $Mode = 'tool' }
529
+ elseif (Get-Command docker -ErrorAction SilentlyContinue) { $Mode = 'docker' }
530
+ else { throw 'No Orkeon runtime found: install Docker or the orkeon-repl tool (docs/getting-started.md).' }
531
+ }
532
+
533
+ # An install keeps one folder per project, ~/.orkeon-code/projects/<slug>; a clone's .crew-output and an
534
+ # ORKEON_CODE_STATE may serve several projects, so their per-project part goes under projects/<slug>. Either way
535
+ # $projectState lies inside $State, which docker mode mounts on /work/state.
536
+ $slug = Get-ProjectSlug $Workspace
537
+ $projectRel = "projects/$slug"
538
+ if ($env:ORKEON_CODE_STATE) { $State = $env:ORKEON_CODE_STATE }
539
+ elseif ($IsClone) { $State = Join-Path $Root '.crew-output' }
540
+ else { $State = Join-Path $CodeHome $projectRel; $projectRel = '' }
541
+ New-Item -ItemType Directory -Force -Path (Join-Path $State 'output'), (Join-Path $State 'tmp') | Out-Null
542
+ $State = (Resolve-Path $State).Path
543
+ $projectState = if ($projectRel) { Join-Path $State $projectRel } else { $State }
544
+ # The runtime saves the session in <SessionsDirectory>/<its slug of the project>/last.json when the REPL ends, and
545
+ # reloads it at the next start. The folder is the /sessions mount, outside the project; the launcher keeps its own
546
+ # files beside it: history/ and project.json.
547
+ $sessions = Join-Path $projectState 'sessions'
548
+ $history = Join-Path $projectState 'history'
549
+ # The typed memory (Orkeon #286) is kept beside them, in <RootDirectory>/<its slug>/memory.json on the /memory
550
+ # mount, outside the project so that neither git nor the file tools see it.
551
+ $memory = Join-Path $projectState 'memory'
552
+ New-Item -ItemType Directory -Force -Path $sessions, $history, $memory | Out-Null
553
+ $runtimeSlug = if ($Mode -eq 'docker') { Get-ProjectSlug '/work/project' } else { $slug }
554
+ $projectFile = Join-Path $projectState 'project.json'
555
+ $now = [DateTime]::UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", [System.Globalization.CultureInfo]::InvariantCulture)
556
+ $firstSeen = Get-JsonField $projectFile 'firstSeen'
557
+ if (-not $firstSeen) { $firstSeen = $now }
558
+ $escapedPath = ($Workspace -replace '\\', '\\') -replace '"', '\"'
559
+ [System.IO.File]::WriteAllText("$projectFile.tmp.$PID",
560
+ "{`n `"path`": `"$escapedPath`",`n `"slug`": `"$slug`",`n `"runtimeSlug`": `"$runtimeSlug`",`n" +
561
+ " `"firstSeen`": `"$firstSeen`",`n `"lastSeen`": `"$now`"`n}`n")
562
+ Move-Item -LiteralPath "$projectFile.tmp.$PID" -Destination $projectFile -Force
563
+
564
+ # The starts open on this project, one pid a line (a launcher waits for its REPL). Another one still running: its
565
+ # session is left where it is, and this one is kept beside it, in side/<pid>/, archived at the next start that
566
+ # finds none open.
567
+ $lock = Join-Path $projectState '.lock'
568
+ $side = Join-Path $projectState 'side'
569
+ $other = $null
570
+ $livePids = @()
571
+ foreach ($line in @(Get-Content -LiteralPath $lock -ErrorAction SilentlyContinue)) {
572
+ $otherPid = "$line".Trim()
573
+ if ($otherPid -match '^[0-9]{1,9}$' -and [int] $otherPid -ne $PID -and (Get-Process -Id ([int] $otherPid) -ErrorAction SilentlyContinue)) {
574
+ if (-not $other) { $other = $otherPid }
575
+ $livePids += $otherPid
576
+ }
577
+ }
578
+ # Left when the REPL ends, as ./orkeon-code leaves it: a pid that no longer runs is a stale lock.
579
+ [System.IO.File]::WriteAllText($lock, ((@($livePids) + "$PID") -join "`n") + "`n")
580
+ $sessionsMount = $sessions
581
+ $sessionsSub = 'sessions'
582
+
583
+ # Fresh unless --continue (the runtime reloads the last itself) or --resume (the chosen one is put back).
584
+ $sessionNote = 'fresh; --continue brings the last back, --resume lists them'
585
+ if ($other) {
586
+ Write-Warning "another session is open on this project (pid $other): it is left as it is, and this one is kept beside it, in the history from the next start."
587
+ $sessionNote = 'beside the open one'
588
+ $sessionsMount = Join-Path $side "$PID"
589
+ $sessionsSub = "side/$PID"
590
+ New-Item -ItemType Directory -Force -Path $sessionsMount | Out-Null
591
+ } elseif ($Continue) { $sessionNote = 'continued'; Move-SessionsToHistory $sessions $history $side $true }
592
+ else { Move-SessionsToHistory $sessions $history $side $false }
593
+ $keep = 50
594
+ if ($null -ne $env:ORKEON_CODE_SESSIONS_KEEP) {
595
+ if ($env:ORKEON_CODE_SESSIONS_KEEP -match '^[0-9]{1,4}$' -and [int] $env:ORKEON_CODE_SESSIONS_KEEP -gt 0) { $keep = [int] $env:ORKEON_CODE_SESSIONS_KEEP }
596
+ else { Write-Warning "ORKEON_CODE_SESSIONS_KEEP=$($env:ORKEON_CODE_SESSIONS_KEEP) is not a whole number from 1 to 9999: 50 sessions are kept." }
597
+ }
598
+ Get-HistoryFiles $history | Select-Object -Skip $keep | Remove-Item -Force
599
+
600
+ if ($Resume) {
601
+ $files = @(Get-HistoryFiles $history)
602
+ if ($files.Count -eq 0) { throw "No saved session for $Workspace yet (they are kept in $history)." }
603
+ if (-not $resumeChoice) {
604
+ [Console]::Error.WriteLine("orkeon-code: sessions of $Workspace, newest first:")
605
+ for ($i = 0; $i -lt $files.Count; $i++) {
606
+ $saved = try { Get-Content -LiteralPath $files[$i].FullName -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $null }
607
+ $title = if ($saved -and $saved.Title) { $saved.Title } else { '(untitled)' }
608
+ $count = if ($saved -and $saved.Messages) { @($saved.Messages).Count } else { 0 }
609
+ $stem = $files[$i].BaseName
610
+ [Console]::Error.WriteLine(('{0,3} {1} {2} ({3} messages) {4}' -f ($i + 1), $stem.Substring(0, [Math]::Min(16, $stem.Length)), $title, $count, $(if ($stem.Length -gt 17) { $stem.Substring(17) } else { '' })))
611
+ }
612
+ if ([Console]::IsInputRedirected) {
613
+ [Console]::Error.WriteLine('orkeon-code: no terminal to choose in: pass --resume <number or id>.')
614
+ exit 2
615
+ }
616
+ $resumeChoice = Read-Answer 'Session to resume [1]: ' '1'
617
+ if ($null -eq $resumeChoice) { $resumeChoice = '1' }
618
+ }
619
+ $chosen = $null
620
+ # A number of the list first (up to four digits), else the start of an id.
621
+ if ($resumeChoice -match '^[1-9][0-9]{0,3}$' -and [int] $resumeChoice -le $files.Count) { $chosen = $files[[int] $resumeChoice - 1] }
622
+ if (-not $chosen -and $resumeChoice) {
623
+ $matching = @($files | Where-Object { $_.BaseName.Length -gt 17 -and $_.BaseName.Substring(17).StartsWith($resumeChoice, [StringComparison]::Ordinal) })
624
+ if ($matching.Count -gt 1) { throw "More than one session starts with '$resumeChoice': give more of its id." }
625
+ if ($matching.Count -eq 1) { $chosen = $matching[0] }
626
+ }
627
+ if (-not $chosen) { throw "No saved session '$resumeChoice' (orkeon-code --resume lists them)." }
628
+ if ($other) { throw "Another session is open on this project (pid $other): end it before you resume one." }
629
+ # The chosen session lives in one place: back in sessions/, the history losing it (the last one was archived above).
630
+ $target = Join-Path $sessions $runtimeSlug
631
+ New-Item -ItemType Directory -Force -Path $target | Out-Null
632
+ Move-Item -LiteralPath $chosen.FullName -Destination (Join-Path $target 'last.json') -Force
633
+ $sessionNote = "resumed $($chosen.BaseName.Substring([Math]::Min(17, $chosen.BaseName.Length)))"
634
+ }
635
+
636
+ # The session's start script (scripts/session-start.ork.ts), copied fresh into the agent's /tmp at every start:
637
+ # the runtime runs it once at the REPL's start, through its script host, and puts what it prints before the
638
+ # first free-text turn.
639
+ $startDir = Join-Path $State 'tmp/orkeon-code'
640
+ New-Item -ItemType Directory -Force -Path $startDir | Out-Null
641
+ Copy-Item -Force (Join-Path $Root 'scripts/session-start.ork.ts') (Join-Path $startDir 'session-start.ork.ts')
642
+ if ($null -eq [Environment]::GetEnvironmentVariable('Orkeon__Cli__Session__StartScript')) {
643
+ $env:Orkeon__Cli__Session__StartScript = '/tmp/orkeon-code/session-start.ork.ts'
644
+ }
645
+ # The session persists (the runtime's default in the REPL, said here; a settings file may still turn it off), in
646
+ # /sessions: the prefixed form wins over the settings file, since the archiving above reads that folder alone.
647
+ if (-not $env:Orkeon__Cli__Session__Persist) { $env:Orkeon__Cli__Session__Persist = 'true' }
648
+ $env:ORKEON_Orkeon__Cli__Session__SessionsDirectory = '/sessions'
649
+ $env:ORKEON_Orkeon__Cli__Memory__RootDirectory = '/memory'
650
+
651
+ # Speech-to-text (optional): $env:ORKEON_CODE_AUDIO_DIR names the folder of audio and video files. The
652
+ # Whisper MCP server (mcp/whisper), started by the REPL over stdio, reads it and writes into
653
+ # <state>/transcripts, which the agents see as /audio and /transcripts. It is declared through the
654
+ # environment (ORKEON_MCP__Servers__whisper__*), so no settings file names this checkout; a settings file,
655
+ # or the environment, that declares a "whisper" server keeps it, and this block stays out.
656
+ $audio = $null
657
+ $audioArgs = @()
658
+ if ($env:ORKEON_CODE_AUDIO_DIR) {
659
+ $uv = Get-Command uv -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
660
+ if ($Mode -eq 'docker') {
661
+ Write-Warning 'ORKEON_CODE_AUDIO_DIR is ignored in docker mode: the Whisper server runs in tool mode (mcp/whisper/README.md).'
662
+ } elseif ($settingsText -match '"whisper"\s*:') {
663
+ Write-Warning "$Settings declares a `"whisper`" MCP server: ORKEON_CODE_AUDIO_DIR is ignored, the settings file wins."
664
+ } elseif (Get-ChildItem env: | Where-Object { $_.Name -like 'ORKEON_MCP__Servers__whisper__*' }) {
665
+ Write-Warning 'the environment declares a "whisper" MCP server (ORKEON_MCP__Servers__whisper__*): ORKEON_CODE_AUDIO_DIR is ignored, that declaration wins.'
666
+ } elseif (-not $uv) {
667
+ Write-Warning "ORKEON_CODE_AUDIO_DIR is set but uv is not on PATH: speech-to-text is off (mcp/whisper/README.md, 'Install')."
668
+ } else {
669
+ if (-not (Test-Path -LiteralPath $env:ORKEON_CODE_AUDIO_DIR -PathType Container)) {
670
+ throw "ORKEON_CODE_AUDIO_DIR=$($env:ORKEON_CODE_AUDIO_DIR) is not a folder."
671
+ }
672
+ $audio = (Resolve-Path -LiteralPath $env:ORKEON_CODE_AUDIO_DIR).Path
673
+ $transcripts = Join-Path $State 'transcripts'
674
+ New-Item -ItemType Directory -Force -Path $transcripts | Out-Null
675
+ $env:WHISPER_AUDIO_DIR = $audio
676
+ $env:WHISPER_OUT_DIR = $transcripts
677
+ $env:ORKEON_MCP__Servers__whisper__Transport = 'Stdio'
678
+ $env:ORKEON_MCP__Servers__whisper__Command = $uv.Source
679
+ # The gate reads the server's annotations (readOnlyHint) only when the server is trusted (Orkeon #223).
680
+ $env:ORKEON_MCP__Servers__whisper__TrustAnnotations = 'true'
681
+ $whisperArgs = @('run', '--project', (Join-Path $Root 'mcp/whisper'))
682
+ # An install's folder is never written to: uv keeps the server's environment under ORKEON_CODE_HOME and
683
+ # reads uv.lock as shipped.
684
+ if (-not $IsClone) {
685
+ $whisperArgs += @('--frozen')
686
+ if (-not $env:UV_PROJECT_ENVIRONMENT) { $env:UV_PROJECT_ENVIRONMENT = Join-Path $CodeHome 'whisper\.venv' }
687
+ }
688
+ # The values are read as the server reads them: case and spaces aside.
689
+ $ttsBackend = "$env:TTS_BACKEND".Trim().ToLowerInvariant()
690
+ $sttBackend = "$env:WHISPER_BACKEND".Trim().ToLowerInvariant()
691
+ if ($env:ORKEON_CODE_VOICE -eq '1') {
692
+ # The microphone (/voice) and the speaker (/say, voice.reply): the `voice` extra (sounddevice),
693
+ # WHISPER_MICROPHONE and WHISPER_SPEAKER.
694
+ $whisperArgs += @('--extra', 'voice')
695
+ $env:WHISPER_MICROPHONE = '1'
696
+ $env:WHISPER_SPEAKER = '1'
697
+ }
698
+ # Piper, the default speech backend, is the `tts` extra: it writes what it would say without the speaker too.
699
+ if ($ttsBackend -in @('', 'piper')) { $whisperArgs += @('--extra', 'tts') }
700
+ # A backend on OpenAI's API or a compatible server needs the `openai` extra, once.
701
+ if (@($ttsBackend, $sttBackend) | Where-Object { $_ -in @('openai', 'http') }) { $whisperArgs += @('--extra', 'openai') }
702
+ # WHISPER_DEVICE=cuda: the cuBLAS and cuDNN wheels, which the server preloads.
703
+ if ("$env:WHISPER_DEVICE".Trim() -eq 'cuda') { $whisperArgs += @('--extra', 'cuda') }
704
+ $whisperArgs += (Join-Path $Root 'mcp/whisper/whisper_mcp.py')
705
+ # Args__0 to Args__12 (13 at most: run, --project, the folder, --frozen, four --extra pairs, the script), each
706
+ # saved above and put back when the script ends.
707
+ for ($i = 0; $i -lt $whisperArgs.Count; $i++) {
708
+ [Environment]::SetEnvironmentVariable("ORKEON_MCP__Servers__whisper__Args__$i", $whisperArgs[$i])
709
+ }
710
+ $audioArgs = @('--mount', "${audio}:/audio:ro", '--mount', "${transcripts}:/transcripts:ro")
711
+ }
712
+ }
713
+
714
+ Write-Host "orkeon-code on Orkeon ($Mode`: a release, the pin is $OrkeonPin)"
715
+ Write-Host " project : $Workspace -> /workspace"
716
+ if ($runtimeOwn) { Write-Host " settings : $Settings (Orkeon's own, read by the REPL)" } else { Write-Host " settings : $Settings" }
717
+ Write-Host " sessions : $sessionsMount ($sessionNote)"
718
+ if ($audio) {
719
+ $model = if ($env:WHISPER_MODEL) { $env:WHISPER_MODEL } elseif ($sttBackend -eq 'openai') { 'whisper-1' } else { 'small' }
720
+ $gpu = if ("$env:WHISPER_DEVICE".Trim() -eq 'cuda') { ' on the GPU' } else { '' }
721
+ $mic = if ($env:ORKEON_CODE_VOICE -eq '1') { ', microphone and speaker on' } else { '' }
722
+ Write-Host " audio : $audio -> /audio (transcripts: $(Join-Path $State 'transcripts'), model $model$gpu$mic)"
723
+ }
724
+
725
+ # The user's orkeonCode block, handed to the scripts as a read-only file: they read no settings and no
726
+ # environment (V-04). Written afresh at each start; no block leaves the folder empty, and no user setting applies.
727
+ $userConfigDir = Join-Path $State 'user-config'
728
+ New-Item -ItemType Directory -Force -Path $userConfigDir | Out-Null
729
+ $userConfigFile = Join-Path $userConfigDir 'config.json'
730
+ Remove-Item $userConfigFile -Force -ErrorAction SilentlyContinue
731
+ try {
732
+ # The key case for case, as ./orkeon-code reads it (a property name is matched without case otherwise).
733
+ $block = (($settingsText | ConvertFrom-Json -ErrorAction Stop).PSObject.Properties |
734
+ Where-Object { $_.Name -ceq 'orkeonCode' } | Select-Object -First 1).Value
735
+ if ($block -is [System.Management.Automation.PSCustomObject]) {
736
+ [System.IO.File]::WriteAllText($userConfigFile, ($block | ConvertTo-Json -Depth 10) + "`n")
737
+ }
738
+ } catch {
739
+ Write-Warning "The orkeonCode block of $Settings could not be read: no user setting applies."
740
+ }
741
+
742
+ # An empty <settings> passes none: the REPL then reads Orkeon's own file. <projectState> as the REPL sees it: its
743
+ # sessions/ on /sessions, its history/ on /session-history (read-only, for /resume), its memory/ on /memory.
744
+ function Get-ReplArgs($commands, $crews, $settings, $workspace, $output, $tmp, $userConfig, $projectState) {
745
+ @('--runner=scripted-commands', '--commands-dir', $commands, '--crews-dir', $crews)
746
+ if ($settings) { @('--settings', $settings) }
747
+ @('--mount', "${workspace}:/workspace:rw", '--mount', "${output}:/output:rw", '--mount', "${tmp}:/tmp:rw",
748
+ '--mount', "${userConfig}:/user-config:ro",
749
+ '--mount', "${projectState}/${sessionsSub}:/sessions:rw", '--mount', "${projectState}/history:/session-history:ro",
750
+ '--mount', "${projectState}/memory:/memory:rw")
751
+ }
752
+
753
+ # The exchange log (--llm-log) would land in ./llm-logs, the project: a bare --llm-log among the REPL's arguments
754
+ # is sent to <projectState>/llm-logs instead; an explicit --llm-log-path is passed as given.
755
+ function Get-LlmLogArgs($projectState) {
756
+ # An explicit --llm-log-path wins: a bare --llm-log beside it is dropped (the runtime keeps the last path it reads).
757
+ $named = @($Extra | Where-Object { "$_" -ceq '--llm-log-path' -or "$_".StartsWith('--llm-log-path=', [StringComparison]::Ordinal) }).Count -gt 0
758
+ foreach ($a in $Extra) { if ($a -ceq '--llm-log') { if (-not $named) { '--llm-log-path'; "$projectState/llm-logs" } } else { $a } }
759
+ }
760
+
761
+ if ($Mode -eq 'docker') {
762
+ # Everything under the working directory /work. The image is multi-arch (linux/amd64, linux/arm64).
763
+ $envArgs = @('-e', 'ORKEON_RUNNER=repl', '-e', 'HOME=/tmp', '-e', 'DOTNET_CLI_HOME=/tmp',
764
+ '-e', "Orkeon__Security__PermissionGate__Enabled=$env:Orkeon__Security__PermissionGate__Enabled",
765
+ '-e', "Orkeon__Cli__Session__StartScript=$env:Orkeon__Cli__Session__StartScript",
766
+ '-e', "Orkeon__Cli__Session__Persist=$env:Orkeon__Cli__Session__Persist",
767
+ '-e', 'ORKEON_Orkeon__Cli__Session__SessionsDirectory=/sessions',
768
+ '-e', 'ORKEON_Orkeon__Cli__Memory__RootDirectory=/memory')
769
+ # The github tool's token (Orkeon #222): GITHUB_TOKEN, GH_TOKEN, or the variable Orkeon__Tools__GitHub__TokenVariable
770
+ # names, each handed over only when set, with the setting itself so the runtime reads the same variable.
771
+ $tokenVar = [Environment]::GetEnvironmentVariable('Orkeon__Tools__GitHub__TokenVariable')
772
+ foreach ($v in @('ORKEON_Llm__ApiKey', 'ORKEON_Llm__Model', $keyVar, 'GITHUB_TOKEN', 'GH_TOKEN', 'Orkeon__Tools__GitHub__TokenVariable', $tokenVar)) {
773
+ if ($v -and [Environment]::GetEnvironmentVariable($v)) { $envArgs += @('-e', $v) }
774
+ }
775
+ $inState = if ($projectRel) { "/work/state/$projectRel" } else { '/work/state' }
776
+ $replArgs = Get-ReplArgs '/work/agent/commands' '/work/agent/crews' '/work/settings.json' `
777
+ '/work/project' '/work/state/output' '/work/state/tmp' '/work/state/user-config' $inState
778
+ $Extra = @(Get-LlmLogArgs $inState)
779
+ # -t only on a terminal, as ./orkeon-code: with stdin or stdout redirected docker refuses it ("not a TTY").
780
+ $ttyArgs = if ([Console]::IsInputRedirected -or [Console]::IsOutputRedirected) { @('-i') } else { @('-it') }
781
+ # Files the agent writes in the project belong to the caller, not to root (Linux; Docker Desktop maps them itself).
782
+ $userArgs = @()
783
+ if ($IsLinux) { $userArgs = @('--user', "$(& id -u):$(& id -g)") }
784
+ & docker run --rm @ttyArgs @userArgs @envArgs -w /work `
785
+ -v "${Workspace}:/work/project" -v "$(Join-Path $Root 'src'):/work/agent:ro" `
786
+ -v "${Settings}:/work/settings.json:ro" -v "${State}:/work/state" `
787
+ $Image @replArgs @Extra
788
+ exit $LASTEXITCODE
789
+ }
790
+
791
+ # tool mode: a release-archive install carries its own esbuild (libexec\esbuild-bin, used by
792
+ # its orkeon-repl wrapper), and so does the Debian package (/usr/bin/orkeon-repl, a script that
793
+ # points the runtime at /usr/lib/orkeon/esbuild-bin); otherwise esbuild comes from this
794
+ # checkout's node_modules.
795
+ $repl = @(if ($env:ORKEON_REPL) { $env:ORKEON_REPL -split ' ' } else { 'orkeon-repl' }) # @(): one word stays an array
796
+ $replCmd = Get-Command $repl[0] -ErrorAction SilentlyContinue
797
+ if (-not $replCmd) { throw "$($repl[0]) not found (docs/getting-started.md, 'Tool mode')." }
798
+ $bundled = $false
799
+ if ($replCmd.Source) {
800
+ $installRoot = Split-Path (Split-Path $replCmd.Source -Parent) -Parent
801
+ $bundled = (Test-Path (Join-Path $installRoot 'libexec/esbuild-bin/esbuild.exe')) -or
802
+ (Test-Path (Join-Path $installRoot 'libexec/esbuild-bin/esbuild'))
803
+ # A launcher script that sets ORKEON_ESBUILD_PATH itself (the Debian package's).
804
+ $firstLine = Get-Content $replCmd.Source -TotalCount 1 -ErrorAction SilentlyContinue
805
+ if (-not $bundled -and "$firstLine".StartsWith('#!') -and
806
+ (Select-String -Path $replCmd.Source -Pattern 'ORKEON_ESBUILD_PATH' -SimpleMatch -Quiet)) { $bundled = $true }
807
+ }
808
+ if (-not $bundled -and -not $env:ORKEON_ESBUILD_PATH -and -not (Get-Command esbuild -ErrorAction SilentlyContinue)) {
809
+ $found = Get-ChildItem (Join-Path $Root 'node_modules/@esbuild') -Recurse -Include 'esbuild.exe', 'esbuild' -File -ErrorAction SilentlyContinue |
810
+ Select-Object -First 1
811
+ if (-not $found -and $IsClone) { throw "esbuild not found: run 'npm ci' in $Root, or set ORKEON_ESBUILD_PATH." }
812
+ if (-not $found) { throw 'esbuild not found: install Orkeon from its package or archive (it carries esbuild), or set ORKEON_ESBUILD_PATH.' }
813
+ $env:ORKEON_ESBUILD_PATH = $found.FullName
814
+ }
815
+ $replArgs = Get-ReplArgs (Join-Path $Root 'src/commands') (Join-Path $Root 'src/crews') $(if ($runtimeOwn) { '' } else { $Settings }) `
816
+ $Workspace (Join-Path $State 'output') (Join-Path $State 'tmp') $userConfigDir $projectState
817
+ $Extra = @(Get-LlmLogArgs $projectState)
818
+ # The REPL runs from the project. It reads its --commands-dir and --crews-dir wherever they are, and
819
+ # a --mount outside its working directory (/output, /tmp, /user-config, /sessions, /session-history and /memory, in
820
+ # the state directory, and an --llm-log-path there) under ORKEON_ALLOW_EXTERNAL_MOUNTS (Orkeon GAP-49). The seven roots
821
+ # are distinct, and none is one the REPL keeps (/sandbox, /credentials, /llm-logs, /cli-commands..., /crews...).
822
+ $env:ORKEON_ALLOW_EXTERNAL_MOUNTS = '1'
823
+ Push-Location $Workspace
824
+ try {
825
+ $exe = $repl[0]
826
+ $rest = @($repl | Select-Object -Skip 1) # @(): a single argument stays an array (an if statement would unroll it)
827
+ & $exe @rest @replArgs @audioArgs @Extra
828
+ exit $LASTEXITCODE
829
+ } finally { Pop-Location }
830
+ } finally {
831
+ # A variable that was not set is removed: $null passed to SetEnvironmentVariable from PowerShell
832
+ # arrives as '', which would leave it set, and empty, for the next run.
833
+ foreach ($name in $savedEnv.Keys) {
834
+ if ($null -eq $savedEnv[$name]) { Remove-Item "env:$name" -ErrorAction SilentlyContinue }
835
+ else { [Environment]::SetEnvironmentVariable($name, $savedEnv[$name]) }
836
+ }
837
+ }