@zhivex-ai/harness 1.6.3 → 1.8.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.
- package/CHANGELOG.md +16 -3
- package/README.md +17 -5
- package/SECURITY.md +1 -1
- package/SUPPORT.md +2 -2
- package/benchmarks/README.md +98 -0
- package/contracts/engine-api.json +1587 -0
- package/contracts/public-api.json +114 -0
- package/contracts/stable-api-signatures.json +17 -17
- package/dist/acp-cli.js +37 -1090
- package/dist/application/agenda.d.ts +10 -0
- package/dist/application/approval-review.d.ts +61 -0
- package/dist/application/assistant/automation/scheduler.d.ts +21 -0
- package/dist/application/assistant/automation/summary.d.ts +29 -0
- package/dist/application/assistant/automation/time.d.ts +10 -0
- package/dist/application/assistant/calendar/calendar.d.ts +238 -0
- package/dist/application/assistant/calendar/connection.d.ts +50 -0
- package/dist/application/assistant/calendar/create-event.d.ts +75 -0
- package/dist/application/assistant/calendar/environment.d.ts +2 -0
- package/dist/application/assistant/calendar/http.d.ts +6 -0
- package/dist/application/assistant/calendar/oauth.d.ts +68 -0
- package/dist/application/assistant/calendar/store.d.ts +11 -0
- package/dist/application/assistant/calendar/tools.d.ts +78 -0
- package/dist/application/assistant/client.d.ts +10 -0
- package/dist/application/assistant/config.d.ts +9 -0
- package/dist/application/assistant/contracts.d.ts +77 -0
- package/dist/application/assistant/daily/service.d.ts +181 -0
- package/dist/application/assistant/doctor.d.ts +22 -0
- package/dist/application/assistant/evaluation.d.ts +81 -0
- package/dist/application/assistant/host.d.ts +399 -0
- package/dist/application/assistant/integrations/google.d.ts +117 -0
- package/dist/application/assistant/integrations/public-web.d.ts +16 -0
- package/dist/application/assistant/managed/secrets.d.ts +10 -0
- package/dist/application/assistant/managed/setup-state.d.ts +346 -0
- package/dist/application/assistant/managed/setup.d.ts +492 -0
- package/dist/application/assistant/microsoft/connection.d.ts +73 -0
- package/dist/application/assistant/microsoft/tools.d.ts +78 -0
- package/dist/application/assistant/modules/calendar.d.ts +3 -0
- package/dist/application/assistant/modules/catalog.d.ts +38 -0
- package/dist/application/assistant/modules/daily.d.ts +5 -0
- package/dist/application/assistant/modules/github.d.ts +5 -0
- package/dist/application/assistant/modules/google.d.ts +3 -0
- package/dist/application/assistant/modules/mcp.d.ts +11 -0
- package/dist/application/assistant/modules/microsoft.d.ts +3 -0
- package/dist/application/assistant/modules/module.d.ts +224 -0
- package/dist/application/assistant/modules/tools.d.ts +11 -0
- package/dist/application/assistant/modules/web.d.ts +7 -0
- package/dist/application/assistant/private-directory.d.ts +3 -0
- package/dist/application/assistant/proactive/service.d.ts +142 -0
- package/dist/application/assistant/providers/openai-compatible.d.ts +66 -0
- package/dist/application/assistant/providers/provider.d.ts +141 -0
- package/dist/application/assistant/providers/web-citations.d.ts +2 -0
- package/dist/application/assistant/runtime.d.ts +16 -0
- package/dist/application/assistant/task-metrics.d.ts +304 -0
- package/dist/application/assistant/telegram/api.d.ts +47 -0
- package/dist/application/assistant/telegram/bridge.d.ts +69 -0
- package/dist/application/assistant/telegram/store.d.ts +10 -0
- package/dist/application/automation.d.ts +5 -0
- package/dist/application/calendar-review.d.ts +5 -0
- package/dist/application/checkpoint-review.d.ts +30 -0
- package/dist/application/client.d.ts +18 -0
- package/dist/application/code/context.d.ts +5 -0
- package/dist/application/code/delivery.d.ts +6 -0
- package/dist/application/code/git-delivery.d.ts +54 -0
- package/dist/application/code/github-git-transport.d.ts +15 -0
- package/dist/application/code/github-pr-transport.d.ts +6 -0
- package/dist/application/code/host.d.ts +25 -0
- package/dist/application/code/pr-delivery.d.ts +79 -0
- package/dist/application/code/projects.d.ts +90 -0
- package/dist/application/code/remote-delivery.d.ts +80 -0
- package/dist/application/code/repository.d.ts +9 -0
- package/dist/application/code/worktrees.d.ts +123 -0
- package/dist/application/contracts.d.ts +288 -0
- package/dist/application/coordinator-client.d.ts +33 -0
- package/dist/application/coordinator-discovery.d.ts +17 -0
- package/dist/application/coordinator-launcher.d.ts +2 -0
- package/dist/application/coordinator.d.ts +27 -0
- package/dist/application/credential-process.d.ts +13 -0
- package/dist/application/host.d.ts +7 -0
- package/dist/application/management.d.ts +68 -0
- package/dist/application/notes.d.ts +5 -0
- package/dist/application/offline-migration.d.ts +16 -0
- package/dist/application/personal-state.d.ts +5 -0
- package/dist/application/review-channel.d.ts +23 -0
- package/dist/application/review-tickets.d.ts +29 -0
- package/dist/application/runtime-binding.d.ts +4 -0
- package/dist/application-cli-wfh08g41.js +184 -0
- package/dist/application-cli-z3f9pvcf.js +209 -0
- package/dist/arguments-75r85mvc.js +27 -0
- package/dist/arguments-x24bbqvd.js +22 -0
- package/dist/audit/index.js +16 -472
- package/dist/audit-pack-1gnych0m.js +93 -0
- package/dist/{audit-pack-s9n693by.js → audit-pack-h44kjkbj.js} +17 -11
- package/dist/calendar-2xw0rr7b.js +49 -0
- package/dist/cli/application-cli.d.ts +2 -0
- package/dist/cli/arguments.d.ts +14 -1
- package/dist/cli/auto-approve-setup.d.ts +13 -0
- package/dist/cli/configured-harness.d.ts +1 -2
- package/dist/cli/console/console-budget.d.ts +16 -2
- package/dist/cli/console/console-checkpoints.d.ts +12 -0
- package/dist/cli/console/console-commands.d.ts +3 -3
- package/dist/cli/console/console-compaction.d.ts +1 -1
- package/dist/cli/console/console-diff.d.ts +2 -0
- package/dist/cli/console/console-input.d.ts +29 -1
- package/dist/cli/console/console-navigation.d.ts +2 -2
- package/dist/cli/console/console-outcome.d.ts +10 -0
- package/dist/cli/console/console-presentation.d.ts +17 -2
- package/dist/cli/console/console-pricing.d.ts +14 -0
- package/dist/cli/console/console-reasoning.d.ts +1 -1
- package/dist/cli/console/console-recovery.d.ts +2 -0
- package/dist/cli/console/console-review.d.ts +34 -0
- package/dist/cli/console/console-run-policy.d.ts +5 -0
- package/dist/cli/console/console-run-view.d.ts +28 -0
- package/dist/cli/console/console-task.d.ts +30 -0
- package/dist/cli/console/console-welcome.d.ts +13 -3
- package/dist/cli/console/review-diff.d.ts +20 -0
- package/dist/cli/presentation.d.ts +8 -6
- package/dist/cli/service-checkpoints.d.ts +234 -0
- package/dist/cli/terminal/activity-history.d.ts +4 -2
- package/dist/cli/terminal/activity-stream.d.ts +33 -0
- package/dist/cli/terminal/file-diff.d.ts +11 -0
- package/dist/cli/terminal/terminal-theme.d.ts +9 -0
- package/dist/cli/terminal/terminal-ui.d.ts +44 -2
- package/dist/cli/terminal/tool-activity.d.ts +6 -2
- package/dist/{cli-entry-hdtfef27.js → cli-entry-68kqraj7.js} +95 -43
- package/dist/{cli-entry-1epvek01.js → cli-entry-86rcbmwh.js} +294 -14
- package/dist/cli-entry-btkpb4h1.js +3627 -0
- package/dist/cli-entry-bxjbs6qq.js +200 -0
- package/dist/cli-entry-cpm89r9q.js +624 -0
- package/dist/{cli-entry-mbcq96nx.js → cli-entry-dksm56sj.js} +39 -293
- package/dist/{cli-entry-rsx0wpvs.js → cli-entry-eka68ttb.js} +4087 -4625
- package/dist/cli-entry-h7dcah4p.js +137 -0
- package/dist/cli-entry-kwk23ktq.js +33 -0
- package/dist/{cli-entry-nyzyvf24.js → cli-entry-vmce694z.js} +1286 -3142
- package/dist/cli-entry-wanv05db.js +1113 -0
- package/dist/{cli-yxvq8qf1.js → cli-z7vhm1rk.js} +1767 -380
- package/dist/cli.js +8 -6
- package/dist/client/json-contracts.d.ts +153 -0
- package/dist/client/local-service.d.ts +7 -12
- package/dist/client/local-transport.d.ts +14 -0
- package/dist/client/protocol.d.ts +43 -1
- package/dist/compat/cli-options.d.ts +7 -1
- package/dist/compat/cli.d.ts +2 -0
- package/dist/compat/cli.js +4043 -0
- package/dist/compat/code-support.d.ts +4 -0
- package/dist/compat/code-support.js +50 -28
- package/dist/{config-r9fdhce6.js → config-hw78440t.js} +5 -5
- package/dist/{config-vyajmksy.js → config-v7s8hp37.js} +1 -1
- package/dist/context/adaptive-compaction.d.ts +1 -0
- package/dist/context/lossless-lines.d.ts +13 -0
- package/dist/context/numbered-read-lines.d.ts +15 -0
- package/dist/context/read-attempts.d.ts +21 -0
- package/dist/context/request-projection.d.ts +32 -4
- package/dist/context/scoped-context.d.ts +31 -5
- package/dist/context/working-read-replay.d.ts +12 -0
- package/dist/coordinator-client-nzysqxf0.js +10 -0
- package/dist/engine/acp.js +27 -21
- package/dist/engine/application-client.d.ts +11 -0
- package/dist/engine/application-client.js +18 -0
- package/dist/engine/application-protocol.d.ts +5 -0
- package/dist/engine/application-protocol.js +7 -0
- package/dist/engine/application.d.ts +43 -0
- package/dist/engine/application.js +206 -0
- package/dist/engine/assistant/automation/scheduler.d.ts +2 -0
- package/dist/engine/assistant/automation/scheduler.js +11 -0
- package/dist/engine/assistant/automation/summary.d.ts +3 -0
- package/dist/engine/assistant/automation/summary.js +8 -0
- package/dist/engine/assistant/automation/time.d.ts +5 -0
- package/dist/engine/assistant/automation/time.js +15 -0
- package/dist/engine/assistant/calendar/calendar.d.ts +5 -0
- package/dist/engine/assistant/calendar/calendar.js +12 -0
- package/dist/engine/assistant/calendar/connection.d.ts +2 -0
- package/dist/engine/assistant/calendar/connection.js +11 -0
- package/dist/engine/assistant/calendar/environment.d.ts +1 -0
- package/dist/engine/assistant/calendar/environment.js +7 -0
- package/dist/engine/assistant/calendar/http.d.ts +3 -0
- package/dist/engine/assistant/calendar/http.js +9 -0
- package/dist/engine/assistant/calendar/oauth.d.ts +5 -0
- package/dist/engine/assistant/calendar/oauth.js +12 -0
- package/dist/engine/assistant/calendar/store.d.ts +2 -0
- package/dist/engine/assistant/calendar/store.js +8 -0
- package/dist/engine/assistant/calendar/tools.d.ts +2 -0
- package/dist/engine/assistant/calendar/tools.js +46 -0
- package/dist/engine/assistant/client.d.ts +2 -0
- package/dist/engine/assistant/client.js +33 -0
- package/dist/engine/assistant/config.d.ts +1 -0
- package/dist/engine/assistant/config.js +102 -0
- package/dist/engine/assistant/contracts.d.ts +10 -0
- package/dist/engine/assistant/contracts.js +78 -0
- package/dist/engine/assistant/daily/service.d.ts +12 -0
- package/dist/engine/assistant/daily/service.js +27 -0
- package/dist/engine/assistant/doctor.d.ts +1 -0
- package/dist/engine/assistant/doctor.js +116 -0
- package/dist/engine/assistant/evaluation.d.ts +2 -0
- package/dist/engine/assistant/evaluation.js +76 -0
- package/dist/engine/assistant/host.d.ts +2 -0
- package/dist/engine/assistant/host.js +63 -0
- package/dist/engine/assistant/integrations/google.d.ts +9 -0
- package/dist/engine/assistant/integrations/google.js +30 -0
- package/dist/engine/assistant/integrations/public-web.d.ts +3 -0
- package/dist/engine/assistant/integrations/public-web.js +11 -0
- package/dist/engine/assistant/managed/secrets.d.ts +1 -0
- package/dist/engine/assistant/managed/secrets.js +0 -0
- package/dist/engine/assistant/managed/setup-state.d.ts +11 -0
- package/dist/engine/assistant/managed/setup-state.js +84 -0
- package/dist/engine/assistant/managed/setup.d.ts +3 -0
- package/dist/engine/assistant/managed/setup.js +85 -0
- package/dist/engine/assistant/microsoft/connection.d.ts +7 -0
- package/dist/engine/assistant/microsoft/connection.js +21 -0
- package/dist/engine/assistant/microsoft/tools.d.ts +8 -0
- package/dist/engine/assistant/microsoft/tools.js +30 -0
- package/dist/engine/assistant/modules/calendar.d.ts +1 -0
- package/dist/engine/assistant/modules/calendar.js +49 -0
- package/dist/engine/assistant/modules/catalog.d.ts +3 -0
- package/dist/engine/assistant/modules/catalog.js +67 -0
- package/dist/engine/assistant/modules/daily.d.ts +1 -0
- package/dist/engine/assistant/modules/daily.js +48 -0
- package/dist/engine/assistant/modules/github.d.ts +1 -0
- package/dist/engine/assistant/modules/github.js +43 -0
- package/dist/engine/assistant/modules/google.d.ts +1 -0
- package/dist/engine/assistant/modules/google.js +53 -0
- package/dist/engine/assistant/modules/mcp.d.ts +1 -0
- package/dist/engine/assistant/modules/mcp.js +42 -0
- package/dist/engine/assistant/modules/microsoft.d.ts +1 -0
- package/dist/engine/assistant/modules/microsoft.js +53 -0
- package/dist/engine/assistant/modules/module.d.ts +5 -0
- package/dist/engine/assistant/modules/module.js +42 -0
- package/dist/engine/assistant/modules/tools.d.ts +2 -0
- package/dist/engine/assistant/modules/tools.js +42 -0
- package/dist/engine/assistant/modules/web.d.ts +1 -0
- package/dist/engine/assistant/modules/web.js +45 -0
- package/dist/engine/assistant/private-directory.d.ts +1 -0
- package/dist/engine/assistant/private-directory.js +7 -0
- package/dist/engine/assistant/proactive/service.d.ts +6 -0
- package/dist/engine/assistant/proactive/service.js +16 -0
- package/dist/engine/assistant/providers/openai-compatible.d.ts +4 -0
- package/dist/engine/assistant/providers/openai-compatible.js +12 -0
- package/dist/engine/assistant/providers/provider.d.ts +7 -0
- package/dist/engine/assistant/providers/provider.js +54 -0
- package/dist/engine/assistant/providers/web-citations.d.ts +1 -0
- package/dist/engine/assistant/providers/web-citations.js +7 -0
- package/dist/engine/assistant/runtime.d.ts +2 -0
- package/dist/engine/assistant/runtime.js +73 -0
- package/dist/engine/assistant/task-metrics.d.ts +8 -0
- package/dist/engine/assistant/task-metrics.js +17 -0
- package/dist/engine/assistant/telegram/api.d.ts +5 -0
- package/dist/engine/assistant/telegram/api.js +11 -0
- package/dist/engine/assistant/telegram/bridge.d.ts +2 -0
- package/dist/engine/assistant/telegram/bridge.js +40 -0
- package/dist/engine/assistant/telegram/store.d.ts +2 -0
- package/dist/engine/assistant/telegram/store.js +8 -0
- package/dist/engine/client.js +26 -18
- package/dist/engine/desktop-providers-v1.js +4 -4
- package/dist/engine/desktop-state-v1.js +16 -13
- package/dist/engine/index.d.ts +4 -0
- package/dist/engine/index.js +117 -159
- package/dist/engine/mcp-stdio-v1.js +13 -12
- package/dist/engine/models.js +65 -23
- package/dist/engine/protocol.js +10 -6
- package/dist/engine/service.js +32 -21
- package/dist/hostile-repository-demo.js +2329 -1096
- package/dist/index-09rsdr2d.js +1744 -0
- package/dist/index-0csc5sc7.js +139 -0
- package/dist/{index-4mn6m3bq.js → index-0dkty795.js} +8 -6
- package/dist/index-0kkgqvg7.js +0 -0
- package/dist/index-0mzz9axm.js +58 -0
- package/dist/index-1e69ar8r.js +38 -0
- package/dist/index-1z0xhkh9.js +18 -0
- package/dist/index-2cef1k92.js +356 -0
- package/dist/{index-rgqzdgv6.js → index-2j0v1xwr.js} +17 -13
- package/dist/index-2jw9jd7h.js +116 -0
- package/dist/index-2n9qx4km.js +0 -0
- package/dist/index-3rvk23e8.js +877 -0
- package/dist/index-3wa4j0yk.js +71 -0
- package/dist/index-41q1k17x.js +210 -0
- package/dist/index-4vz4bqqw.js +33 -0
- package/dist/index-5jxm2wy5.js +123 -0
- package/dist/index-5rk6ss42.js +216 -0
- package/dist/index-5v1skxf7.js +1852 -0
- package/dist/{index-fqqz1yt8.js → index-6ehtssyz.js} +369 -335
- package/dist/index-76kpdbpw.js +80 -0
- package/dist/{index-5nmm0642.js → index-7nbmhmw5.js} +10 -10
- package/dist/index-8mx0yrkz.js +31 -0
- package/dist/index-8tjev5ds.js +11 -0
- package/dist/index-91n5wr6s.js +163 -0
- package/dist/index-91trs3ew.js +151 -0
- package/dist/index-9y8p5vy5.js +222 -0
- package/dist/index-abxahprd.js +55 -0
- package/dist/index-aptyr511.js +84 -0
- package/dist/{index-8sm2a1wa.js → index-ay26xfxt.js} +28 -20
- package/dist/index-b4yed1s3.js +657 -0
- package/dist/index-bb7phvtg.js +23 -0
- package/dist/index-bk5tn9b8.js +236 -0
- package/dist/index-bw34861c.js +292 -0
- package/dist/index-c6fnjhgv.js +55 -0
- package/dist/{index-qfsrrnz6.js → index-cjevq9s8.js} +2 -2
- package/dist/{index-c39197wq.js → index-ctcwrkrc.js} +4 -4
- package/dist/{index-yx52bt4a.js → index-cztmcesv.js} +2 -2
- package/dist/index-dpbmxnrf.js +564 -0
- package/dist/index-ekxdcy36.js +134 -0
- package/dist/index-f8zpcsx3.js +289 -0
- package/dist/{index-6dxrbnxm.js → index-f970qtb4.js} +7 -143
- package/dist/index-fatcn6fp.js +2791 -0
- package/dist/index-fbzykqxy.js +105 -0
- package/dist/{index-1265j7t2.js → index-fwf274vc.js} +24 -14
- package/dist/index-fy4w0a7v.js +0 -0
- package/dist/index-gvva3e5x.js +76 -0
- package/dist/index-h7dcah4p.js +137 -0
- package/dist/index-hm9r120s.js +42 -0
- package/dist/index-j3d2tw97.js +328 -0
- package/dist/index-jfqj20x8.js +41 -0
- package/dist/{index-hhrnrqfc.js → index-k529a278.js} +6 -6
- package/dist/{index-bt2p8x7r.js → index-kbrf5bx7.js} +110 -106
- package/dist/index-kwk23ktq.js +33 -0
- package/dist/index-kz857p1j.js +557 -0
- package/dist/{index-j466sekf.js → index-mkt5yrax.js} +31 -105
- package/dist/{index-nxmk6re7.js → index-ndgnvjez.js} +18 -18
- package/dist/index-nemn4epv.js +43 -0
- package/dist/index-nkwy5bjr.js +1225 -0
- package/dist/index-nvvzr4ny.js +136 -0
- package/dist/index-pkspzsfs.js +78 -0
- package/dist/{index-fm84men1.js → index-px1tnqgt.js} +2 -2
- package/dist/index-q7qdw883.js +79 -0
- package/dist/{index-mzydbzp8.js → index-qvbg6tx1.js} +65 -23
- package/dist/index-r3mwr5fb.js +0 -0
- package/dist/index-rdr78m0k.js +91 -0
- package/dist/index-rtamqsfs.js +59 -0
- package/dist/index-s125ss45.js +38 -0
- package/dist/{index-vn91b9z1.js → index-sx1t6dnd.js} +3721 -2382
- package/dist/index-tar0ngkm.js +359 -0
- package/dist/index-tn58cr6w.js +471 -0
- package/dist/{index-w0m1nckc.js → index-v79s9bf9.js} +118 -45
- package/dist/index-vk3rq21m.js +17 -0
- package/dist/index-vmvnr28y.js +72 -0
- package/dist/index-vz629cg8.js +49 -0
- package/dist/{index-eps3c3g6.js → index-w292hdpz.js} +197 -960
- package/dist/{index-amjttjaj.js → index-w9eqg6p9.js} +24 -302
- package/dist/index-wj96kdw2.js +57 -0
- package/dist/index-wyck5yhd.js +141 -0
- package/dist/index-xvtk8pxs.js +674 -0
- package/dist/{index-bpc596v3.js → index-xwb691v9.js} +2 -2
- package/dist/index-ym69x168.js +518 -0
- package/dist/index-yprdjk9v.js +65 -0
- package/dist/index-z2a81ccr.js +35 -0
- package/dist/{index-3ah1f369.js → index-z69cqk74.js} +3 -3
- package/dist/index-zaakvmzq.js +62 -0
- package/dist/index-zk3m4mzg.js +232 -0
- package/dist/index-zx3wgvx4.js +218 -0
- package/dist/index.js +102 -83
- package/dist/persistence/migration-guard.d.ts +3 -0
- package/dist/runtime/agent-profile.d.ts +12 -0
- package/dist/runtime/harness.d.ts +13 -0
- package/dist/runtime/known-file-preload.d.ts +35 -0
- package/dist/service-cli.js +130 -40
- package/dist/service-client-cli-2rzxy5mj.js +1166 -0
- package/dist/service-client-cli-5ne8q5ej.js +543 -0
- package/dist/tools/ooxml-zip.d.ts +21 -0
- package/dist/tools/presentations.d.ts +47 -0
- package/dist/tools/tabular-data.d.ts +114 -0
- package/dist/tools/workspace.d.ts +76 -0
- package/dist/verify-historical-migrations.js +2249 -1016
- package/dist/workspace/workspace.d.ts +13 -1
- package/dist/zhx.js +8 -6
- package/docs/APPLICATION_MIGRATION.md +32 -0
- package/docs/CLI.md +166 -2
- package/docs/CODE_RELEASE.md +11 -5
- package/docs/CODE_WEB_TASKS.md +3 -114
- package/docs/CONTEXT_ENGINEERING.md +93 -0
- package/docs/ENGINE_API.md +9 -2
- package/docs/EXTENSIBILITY.md +1 -1
- package/docs/FIRST_USE.md +6 -6
- package/docs/INTERNAL_ARCHIVE.md +43 -0
- package/docs/LOCAL_SERVICE.md +1 -1
- package/docs/MODEL_CATALOG.md +14 -0
- package/docs/PROJECT_MEMORY.md +1 -1
- package/docs/README.md +23 -4
- package/evaluations/representative-assembly-matrix.json +19 -1
- package/examples/README.md +4 -4
- package/examples/assistant/compatible-calendar.json +17 -0
- package/examples/assistant/composed-modules.json +23 -0
- package/examples/assistant/connected-tools.json +9 -0
- package/examples/assistant/daily-tools.json +6 -0
- package/examples/assistant/offline.mjs +24 -0
- package/fixtures/cli-compatibility/README.md +10 -0
- package/fixtures/cli-compatibility/inventory.json +7858 -0
- package/package.json +232 -26
- package/dist/cli/console/console-model-catalog.d.ts +0 -8
- package/dist/index-2yyfg69h.js +0 -619
- package/dist/index-3wwfn5n6.js +0 -270
- package/dist/index-4gt045j0.js +0 -288
- package/dist/index-4jw3tvy8.js +0 -301
- package/dist/service-client-cli-xbj7j5kj.js +0 -1251
|
@@ -4,135 +4,174 @@ import {
|
|
|
4
4
|
CliCredentials,
|
|
5
5
|
ConsoleInput,
|
|
6
6
|
CredentialSetupError,
|
|
7
|
-
DEFAULT_HARNESS_CONTEXT_MANIFEST,
|
|
8
7
|
HARNESS_RESUME_METADATA_KEY,
|
|
9
8
|
HARNESS_RESUME_METADATA_SCHEMA_VERSION,
|
|
10
|
-
|
|
11
|
-
MAX_HARNESS_CONTEXT_TOTAL_BYTES,
|
|
9
|
+
TerminalMarkdown,
|
|
12
10
|
annotateCliStreamError,
|
|
13
|
-
appendUserMessage,
|
|
14
11
|
approvalResponses,
|
|
15
12
|
assertRoutePricingIsSafe,
|
|
16
13
|
chooseReasoning,
|
|
17
14
|
cliStreamErrorSequence,
|
|
18
|
-
|
|
15
|
+
consoleLabel,
|
|
16
|
+
consoleStateLines,
|
|
17
|
+
consoleWidth,
|
|
19
18
|
createConfiguredHarness,
|
|
20
|
-
createHarness,
|
|
21
19
|
createHarnessResumeMetadata,
|
|
22
20
|
credentialModel,
|
|
23
|
-
decodeProjectMemory,
|
|
24
|
-
estimateMessages,
|
|
25
21
|
flushToolActivity,
|
|
26
|
-
formatAppliedFiles,
|
|
27
22
|
formatConsoleHelp,
|
|
28
23
|
formatConsoleWelcome,
|
|
29
|
-
|
|
24
|
+
handleConsoleBudget,
|
|
30
25
|
harnessConfigInput,
|
|
31
26
|
inspectCliPolicy,
|
|
32
|
-
issueAutomaticApprovalResponses,
|
|
33
|
-
issueObservedApprovalResponses,
|
|
34
|
-
loadHarnessMcpConfiguration,
|
|
35
|
-
loadHarnessProjectContext,
|
|
36
|
-
loadModelCatalog,
|
|
37
27
|
navigateConsole,
|
|
38
28
|
observeCliPolicy,
|
|
39
|
-
openHarnessProjectMemory,
|
|
40
|
-
openWorkspaceCheckpointStore,
|
|
41
29
|
orchestrationObserver,
|
|
42
30
|
persistedCliOptions,
|
|
43
31
|
printTerminalResult,
|
|
44
|
-
projectMemoryRecordKey,
|
|
45
32
|
readHarnessResumeConfig,
|
|
46
33
|
readHarnessResumeRoutes,
|
|
47
|
-
requiresExplicitHostReview,
|
|
48
34
|
resolvedRouting,
|
|
49
35
|
resumeCommand,
|
|
50
|
-
runHarness,
|
|
51
|
-
runHarnessReviewGroup,
|
|
52
36
|
runResultDocument,
|
|
53
|
-
sanitizeTerminalText,
|
|
54
37
|
streamSink,
|
|
55
38
|
summarizeApproval,
|
|
56
39
|
terminalApprovalResolver,
|
|
57
|
-
terminalContinuationMessages,
|
|
58
40
|
terminalErrorMessage,
|
|
41
|
+
withTemporaryHarnessProfiles
|
|
42
|
+
} from "./cli-entry-btkpb4h1.js";
|
|
43
|
+
import {
|
|
44
|
+
DEFAULT_HARNESS_CONTEXT_MANIFEST,
|
|
45
|
+
MAX_HARNESS_CONTEXT_FILE_BYTES,
|
|
46
|
+
MAX_HARNESS_CONTEXT_TOTAL_BYTES,
|
|
47
|
+
appendUserMessage,
|
|
48
|
+
compactHarnessMessages,
|
|
49
|
+
createHarness,
|
|
50
|
+
createTaskTelemetry,
|
|
51
|
+
decodeProjectMemory,
|
|
52
|
+
estimateMessages,
|
|
53
|
+
initializeHarnessTaskBudget,
|
|
54
|
+
inspectHarnessTaskBudget,
|
|
55
|
+
inspectHarnessTaskContinuity,
|
|
56
|
+
issueAutomaticApprovalResponses,
|
|
57
|
+
loadApprovalConfig,
|
|
58
|
+
loadHarnessMcpConfiguration,
|
|
59
|
+
loadHarnessProjectContext,
|
|
60
|
+
loadModelCatalog,
|
|
61
|
+
nativeTaskSnapshot,
|
|
62
|
+
openHarnessProjectMemory,
|
|
63
|
+
paintTerminal,
|
|
64
|
+
persistHarnessTaskDraft,
|
|
65
|
+
projectMemoryRecordKey,
|
|
66
|
+
publicAutoApproval,
|
|
67
|
+
readAutoApprovals,
|
|
68
|
+
readHarnessTaskDraft,
|
|
69
|
+
readWorkspaceSnapshot,
|
|
70
|
+
requiresExplicitHostReview,
|
|
71
|
+
resolveAutoApprovePolicy,
|
|
72
|
+
revealInvisible,
|
|
73
|
+
revertAutoApproval,
|
|
74
|
+
reviseHarnessTaskAcceptance,
|
|
75
|
+
runHarness,
|
|
76
|
+
runHarnessReviewGroup,
|
|
77
|
+
runHarnessTask,
|
|
78
|
+
sanitizeTerminalText,
|
|
59
79
|
terminalRunFailure,
|
|
60
80
|
terminalSupportsColor,
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
} from "./cli-entry-
|
|
81
|
+
terminalThemeCommand,
|
|
82
|
+
verificationCounts,
|
|
83
|
+
writeApprovalConfig
|
|
84
|
+
} from "./cli-entry-eka68ttb.js";
|
|
65
85
|
import {
|
|
66
86
|
exportHarnessGovernanceReport,
|
|
87
|
+
openHarnessActivityStore,
|
|
67
88
|
renderHarnessGovernanceMarkdown
|
|
68
|
-
} from "./cli-entry-
|
|
89
|
+
} from "./cli-entry-86rcbmwh.js";
|
|
90
|
+
import {
|
|
91
|
+
CLI_JSON_SCHEMA_VERSION,
|
|
92
|
+
canonicalizeChangeEnvelope,
|
|
93
|
+
changeEnvelopePreconditionsSchema,
|
|
94
|
+
createChangeEnvelope,
|
|
95
|
+
digestChangeEnvelopeArtifact,
|
|
96
|
+
verifyChangeEnvelope
|
|
97
|
+
} from "./cli-entry-cpm89r9q.js";
|
|
69
98
|
import {
|
|
70
|
-
BUDGET_LEDGER_NAMESPACE,
|
|
71
|
-
BUDGET_OWNER_NAMESPACE_KEY,
|
|
72
99
|
CLI_CHANGES_COMMANDS,
|
|
73
100
|
CLI_COMMANDS,
|
|
74
|
-
CLI_JSON_SCHEMA_VERSION,
|
|
75
101
|
CLI_RUNS_COMMANDS,
|
|
76
102
|
CLI_SESSIONS_COMMANDS,
|
|
77
103
|
CLI_STATE_COMMANDS,
|
|
78
|
-
CliOciRuntimeAdapter,
|
|
79
104
|
CliUsageError,
|
|
80
|
-
|
|
81
|
-
|
|
105
|
+
applyCliProfile,
|
|
106
|
+
createCliProfile,
|
|
107
|
+
createHarnessRouteModels,
|
|
108
|
+
loadCliProfile,
|
|
109
|
+
parseCliArgs,
|
|
110
|
+
parseHarnessModelRoute,
|
|
111
|
+
resolveCliDefaults,
|
|
112
|
+
resolveHarnessModelRoutes,
|
|
113
|
+
serializeHarnessModelRoutes,
|
|
114
|
+
updateCliProfile
|
|
115
|
+
} from "./cli-entry-wanv05db.js";
|
|
116
|
+
import {
|
|
117
|
+
formatCliHelp,
|
|
118
|
+
shortCliHelp
|
|
119
|
+
} from "./cli-entry-dksm56sj.js";
|
|
120
|
+
import {
|
|
121
|
+
BUDGET_LEDGER_NAMESPACE,
|
|
122
|
+
BUDGET_OWNER_NAMESPACE_KEY,
|
|
123
|
+
CliOciRuntimeAdapter,
|
|
82
124
|
HARNESS_OPERATIONS_SCHEMA_VERSION,
|
|
83
125
|
HARNESS_SESSION_SCHEMA_VERSION,
|
|
84
126
|
HARNESS_SQLITE_FILE,
|
|
85
127
|
SqliteDatabase,
|
|
128
|
+
TASK_ACCEPTANCE_EVIDENCE_KEY,
|
|
129
|
+
TASK_BUDGET_KEY,
|
|
86
130
|
TASK_SOURCE_KEY,
|
|
131
|
+
TERMINAL_SESSION_RUN_STATUSES,
|
|
87
132
|
USAGE_LEDGER_KEY,
|
|
88
|
-
UnsafeFileTypeError,
|
|
89
133
|
Workspace,
|
|
90
|
-
applyCliProfile,
|
|
91
134
|
assertTaskBudgetBackupLinks,
|
|
92
135
|
budgetLedgerNamespace,
|
|
93
136
|
cancelHarnessRun,
|
|
94
|
-
canonicalizeChangeEnvelope,
|
|
95
|
-
changeEnvelopePreconditionsSchema,
|
|
96
137
|
cleanupHarnessExecutionArtifacts,
|
|
97
138
|
cleanupHarnessRuns,
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
digestChangeEnvelopeArtifact,
|
|
139
|
+
compileTaskAcceptanceContract,
|
|
140
|
+
createEditProposal,
|
|
141
|
+
editChangesSchema,
|
|
102
142
|
fileDigestSchema,
|
|
103
143
|
formatUsageLedger,
|
|
104
144
|
harnessToolExecution,
|
|
105
145
|
inspectHarnessRun,
|
|
106
146
|
inspectRuntimeDiagnostics,
|
|
147
|
+
inspectTaskBudgetSummary,
|
|
107
148
|
inspectUsageLedger,
|
|
108
149
|
listHarnessRuns,
|
|
109
|
-
loadCliProfile,
|
|
110
150
|
openCliSessionStore,
|
|
111
|
-
openHarnessActivityStore,
|
|
112
151
|
openHarnessPersistence,
|
|
113
|
-
parseCliArgs,
|
|
114
|
-
parseHarnessModelRoute,
|
|
115
152
|
publishPendingPolicyDecision,
|
|
116
|
-
|
|
117
|
-
readRegularFileNoFollow,
|
|
118
|
-
resolveCliDefaults,
|
|
119
|
-
resolveHarnessModelRoutes,
|
|
153
|
+
resolvePackageCheckCommand,
|
|
120
154
|
resolvePackageManager,
|
|
121
155
|
runPortableProcess,
|
|
122
|
-
serializeHarnessModelRoutes,
|
|
123
156
|
sqliteAdapter,
|
|
124
157
|
taskSources,
|
|
125
|
-
updateCliProfile,
|
|
126
158
|
validateStateDirectory,
|
|
127
|
-
|
|
128
|
-
|
|
159
|
+
withWorkspaceMutation,
|
|
160
|
+
workspaceFilePathSchema
|
|
161
|
+
} from "./cli-entry-vmce694z.js";
|
|
129
162
|
import {
|
|
130
163
|
BUN_ENGINE_RANGE,
|
|
131
164
|
HARNESS_VERSION,
|
|
132
|
-
NODE_ENGINE_RANGE
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
165
|
+
NODE_ENGINE_RANGE
|
|
166
|
+
} from "./cli-entry-kwk23ktq.js";
|
|
167
|
+
import {
|
|
168
|
+
FileChangedWhileReadingError,
|
|
169
|
+
FileSizeLimitError,
|
|
170
|
+
UnsafeFileTypeError,
|
|
171
|
+
readRegularFileChunksNoFollow,
|
|
172
|
+
readRegularFileNoFollow,
|
|
173
|
+
statRegularFileNoFollow
|
|
174
|
+
} from "./cli-entry-h7dcah4p.js";
|
|
136
175
|
import {
|
|
137
176
|
DEFAULT_PROVIDER_REGISTRY,
|
|
138
177
|
HARNESS_SUBAGENT_PROFILES,
|
|
@@ -148,16 +187,16 @@ import {
|
|
|
148
187
|
providerDescriptor,
|
|
149
188
|
reasoningEffortSchema,
|
|
150
189
|
resolveHarnessConfig
|
|
151
|
-
} from "./cli-entry-
|
|
190
|
+
} from "./cli-entry-68kqraj7.js";
|
|
152
191
|
import {
|
|
153
192
|
__require
|
|
154
193
|
} from "./cli-entry-1bx83sw4.js";
|
|
155
194
|
|
|
156
|
-
// src/cli.ts
|
|
195
|
+
// packages/core/src/cli.ts
|
|
157
196
|
import { realpathSync } from "node:fs";
|
|
158
197
|
import { fileURLToPath } from "node:url";
|
|
159
198
|
|
|
160
|
-
// src/cli/setup.ts
|
|
199
|
+
// packages/core/src/cli/setup.ts
|
|
161
200
|
var providersDocument = (env = process.env) => ({
|
|
162
201
|
schemaVersion: CLI_JSON_SCHEMA_VERSION,
|
|
163
202
|
kind: "providers",
|
|
@@ -286,7 +325,7 @@ var listProviders = (json) => {
|
|
|
286
325
|
}
|
|
287
326
|
};
|
|
288
327
|
|
|
289
|
-
// src/cli/help-text.ts
|
|
328
|
+
// packages/core/src/cli/help-text.ts
|
|
290
329
|
var CLI_HELP_TEXT = shortCliHelp(HARNESS_VERSION);
|
|
291
330
|
var CLI_FULL_HELP_TEXT = `Zhivex Harness v${HARNESS_VERSION}
|
|
292
331
|
|
|
@@ -304,6 +343,13 @@ Everyday commands:
|
|
|
304
343
|
zhx policy [options] [--json]
|
|
305
344
|
|
|
306
345
|
Advanced operations and automation:
|
|
346
|
+
zhx automations status|apply - --yes [--json]
|
|
347
|
+
zhx personal tasks [offset]|reminders [--json]
|
|
348
|
+
zhx agents list|create <name>|tools -|start|select <id>|rename <id> <name>
|
|
349
|
+
zhx connections list|configure -|use <id>
|
|
350
|
+
zhx projects list|context|open <Git root> <connectionId>|select <id>|connection <id> <connectionId>
|
|
351
|
+
zhx application status|start [--application-directory <dir>] [--json]
|
|
352
|
+
zhx application stop --yes [--application-directory <dir>] [--json]
|
|
307
353
|
zhx resume [options] <runId> --approve|--deny
|
|
308
354
|
zhx runs list [--status <status>] [--limit <n>] [--json]
|
|
309
355
|
zhx sessions list|inspect|rename|fork|archive
|
|
@@ -343,6 +389,8 @@ Options (automation and advanced configuration):
|
|
|
343
389
|
--continue Open the latest durable interactive session
|
|
344
390
|
--workspace <path> Target workspace (default: cwd)
|
|
345
391
|
--service <credentials.json> Use the private local runtime (run/resume/chat/sessions)
|
|
392
|
+
--application-directory <dir> Discover/start the shared application host
|
|
393
|
+
--area <assistant|code> Use the shared Assistant or selected Code project
|
|
346
394
|
--state-dir <path> Durable run-state directory
|
|
347
395
|
--mcp-config <path> Declarative governed MCP JSON configuration
|
|
348
396
|
--context-config <path> Project context/rules/skills manifest (default: .zhivex/harness.json)
|
|
@@ -396,6 +444,8 @@ Options (automation and advanced configuration):
|
|
|
396
444
|
--subagent-timeout-ms <n> Independent child timeout (default: 300000)
|
|
397
445
|
--reviewer <profile> Read-only review group member; repeatable
|
|
398
446
|
--max-parallel-reviews <1-4> Review group concurrency ceiling (default: 2)
|
|
447
|
+
--auto-approve <mode> Direct terminal: manual, auto-edits, auto-limits; cannot override shared-host review
|
|
448
|
+
--auto-approve-allow <tool> Allow an exact tool under the opt-in direct-terminal policy
|
|
399
449
|
--approval-mode <mode> ask (default), auto, or restricted (deny approvals)
|
|
400
450
|
--yes Alias for automatic approvals within existing permissions
|
|
401
451
|
--json Emit structured final output
|
|
@@ -423,12 +473,12 @@ Credentials:
|
|
|
423
473
|
Qwen: DASHSCOPE_API_KEY or QWEN_API_KEY
|
|
424
474
|
Gemini: GEMINI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY`;
|
|
425
475
|
|
|
426
|
-
// src/cli/doctor.ts
|
|
476
|
+
// packages/core/src/cli/doctor.ts
|
|
427
477
|
import { constants as fsConstants } from "node:fs";
|
|
428
478
|
import { access, lstat, stat } from "node:fs/promises";
|
|
429
479
|
import path from "node:path";
|
|
430
480
|
|
|
431
|
-
// src/cli/errors.ts
|
|
481
|
+
// packages/core/src/cli/errors.ts
|
|
432
482
|
var cliRecoveryHint = (error, argv) => {
|
|
433
483
|
if (error instanceof CredentialSetupError)
|
|
434
484
|
return "Run zhx again to retry key setup or choose temporary use. For automation, configure the selected provider environment key.";
|
|
@@ -460,7 +510,7 @@ var CLI_EXIT_CODES = {
|
|
|
460
510
|
};
|
|
461
511
|
var cliExitCodeForError = (error) => error instanceof CliUsageError || error instanceof HarnessConfigError ? CLI_EXIT_CODES.usageError : CLI_EXIT_CODES.runtimeError;
|
|
462
512
|
|
|
463
|
-
// src/cli/doctor.ts
|
|
513
|
+
// packages/core/src/cli/doctor.ts
|
|
464
514
|
var sensitiveStateSegments = new Set([
|
|
465
515
|
".git",
|
|
466
516
|
".env",
|
|
@@ -972,37 +1022,555 @@ var doctor = async (options) => {
|
|
|
972
1022
|
process.exitCode = CLI_EXIT_CODES.doctorFailed;
|
|
973
1023
|
}
|
|
974
1024
|
};
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
const
|
|
979
|
-
const
|
|
980
|
-
let
|
|
1025
|
+
|
|
1026
|
+
// packages/core/src/cli/terminal/file-diff.ts
|
|
1027
|
+
var formatFileDiff = ({ path: path2, before, after }, context = 3) => {
|
|
1028
|
+
const lines = (text) => text === null || text === "" ? [] : text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
1029
|
+
const old = lines(before), next = lines(after);
|
|
1030
|
+
let prefix = 0, suffix = 0;
|
|
1031
|
+
while (prefix < old.length && prefix < next.length && old[prefix] === next[prefix])
|
|
1032
|
+
prefix++;
|
|
1033
|
+
while (suffix < old.length - prefix && suffix < next.length - prefix && old[old.length - suffix - 1] === next[next.length - suffix - 1])
|
|
1034
|
+
suffix++;
|
|
1035
|
+
const name = sanitizeTerminalText(JSON.stringify(path2));
|
|
1036
|
+
if (before === after)
|
|
1037
|
+
return `File ${name}: unchanged
|
|
1038
|
+
`;
|
|
1039
|
+
const finite = Number.isFinite(context) ? Math.max(0, context) : Number.MAX_SAFE_INTEGER;
|
|
1040
|
+
const lead = Math.min(finite, prefix);
|
|
1041
|
+
const trail = Math.min(finite, suffix);
|
|
1042
|
+
const start = prefix - lead;
|
|
1043
|
+
const oldEnd = old.length - suffix + trail;
|
|
1044
|
+
const newEnd = next.length - suffix + trail;
|
|
1045
|
+
const render = (mark, line) => mark + revealInvisible(line.endsWith(`
|
|
1046
|
+
`) ? line.slice(0, -1) : line) + `
|
|
1047
|
+
` + (line.endsWith(`
|
|
1048
|
+
`) ? "" : `\
|
|
1049
|
+
`);
|
|
1050
|
+
const banner = (count) => count > 0 ? `··· ${count} unchanged line${count === 1 ? "" : "s"}
|
|
1051
|
+
` : "";
|
|
1052
|
+
const oldCount = old.length ? oldEnd - start : 0;
|
|
1053
|
+
const newCount = next.length ? newEnd - start : 0;
|
|
1054
|
+
return `--- ${before === null ? "/dev/null" : name}
|
|
1055
|
+
+++ ${after === null ? "/dev/null" : name}
|
|
1056
|
+
` + banner(start) + `@@ -${old.length ? start + 1 : 0},${oldCount} +${next.length ? start + 1 : 0},${newCount} @@
|
|
1057
|
+
` + old.slice(start, prefix).map((line) => render(" ", line)).join("") + old.slice(prefix, old.length - suffix).map((line) => render("-", line)).join("") + next.slice(prefix, next.length - suffix).map((line) => render("+", line)).join("") + next.slice(next.length - suffix, newEnd).map((line) => render(" ", line)).join("") + banner(Math.max(0, suffix - trail));
|
|
1058
|
+
};
|
|
1059
|
+
var approvalFileDiff = async (workspace, approval, context = 3) => {
|
|
1060
|
+
if (approval.kind !== "local-tool")
|
|
1061
|
+
return;
|
|
1062
|
+
if (!["apply_patch", "apply_reviewed_edits", "verify_and_apply_reviewed_edits", "apply_reviewed_replacement"].includes(approval.name))
|
|
1063
|
+
return;
|
|
1064
|
+
try {
|
|
1065
|
+
const args = JSON.parse(approval.arguments);
|
|
1066
|
+
let preview;
|
|
1067
|
+
if (approval.name === "apply_reviewed_replacement")
|
|
1068
|
+
preview = await workspace.previewReplacement(args);
|
|
1069
|
+
else {
|
|
1070
|
+
const changes = editChangesSchema.parse(args.changes);
|
|
1071
|
+
const proposalId = approval.name === "apply_patch" ? args.proposalId : createEditProposal({ changes }).proposalId;
|
|
1072
|
+
preview = await workspace.previewPatch({ proposalId, changes });
|
|
1073
|
+
}
|
|
1074
|
+
const diff = preview.files.map((file) => formatFileDiff(file, context)).join(`
|
|
1075
|
+
`);
|
|
1076
|
+
if (Buffer.byteLength(diff) > 128 * 1024)
|
|
1077
|
+
return `File diff unavailable: exceeds terminal preview limit. Review the complete payload below.
|
|
1078
|
+
`;
|
|
1079
|
+
return `Reviewed file diff · ${preview.proposalId}
|
|
1080
|
+
${diff}`;
|
|
1081
|
+
} catch {
|
|
1082
|
+
return `File diff unavailable: preconditions or text preview could not be validated. Review the complete payload below; engine checks still apply.
|
|
1083
|
+
`;
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
// packages/core/src/cli/auto-approve-setup.ts
|
|
1088
|
+
var createAutoApproveController = (workspace, options, file) => {
|
|
1089
|
+
let stored = file;
|
|
1090
|
+
let sessionMode;
|
|
1091
|
+
let sessionAllow;
|
|
981
1092
|
return {
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
const { id, ...request } = event.toolCall;
|
|
986
|
-
calls.set(id, createHash("sha256").update(JSON.stringify(request)).digest("hex"));
|
|
1093
|
+
policy(overLimit = false) {
|
|
1094
|
+
if (options.approvalMode === "ask") {
|
|
1095
|
+
return resolveAutoApprovePolicy({ rootDir: workspace, overLimit });
|
|
987
1096
|
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1097
|
+
return resolveAutoApprovePolicy({
|
|
1098
|
+
rootDir: workspace,
|
|
1099
|
+
file: stored,
|
|
1100
|
+
...options.autoApproveMode ? { cliMode: options.autoApproveMode } : {},
|
|
1101
|
+
...options.autoApproveAllow?.length ? { cliAllow: options.autoApproveAllow } : {},
|
|
1102
|
+
...sessionMode ? { sessionMode } : {},
|
|
1103
|
+
...sessionAllow ? { sessionAllow } : {},
|
|
1104
|
+
...overLimit ? { overLimit: true } : {}
|
|
1105
|
+
});
|
|
1106
|
+
},
|
|
1107
|
+
setSession(mode) {
|
|
1108
|
+
sessionMode = mode;
|
|
1109
|
+
},
|
|
1110
|
+
async saveWorkspace(mode) {
|
|
1111
|
+
stored = { mode, commandAllowlist: stored.commandAllowlist };
|
|
1112
|
+
sessionMode = mode;
|
|
1113
|
+
await writeApprovalConfig(workspace, stored);
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
};
|
|
1117
|
+
var openAutoApproveController = async (workspace, options) => {
|
|
1118
|
+
let file = { mode: "manual", commandAllowlist: [] };
|
|
1119
|
+
try {
|
|
1120
|
+
file = await loadApprovalConfig(workspace);
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
process.stderr.write(`Approval config was not loaded (${error instanceof Error ? error.message : "invalid"}). Approvals stay manual.
|
|
1123
|
+
`);
|
|
1124
|
+
}
|
|
1125
|
+
return createAutoApproveController(workspace, options, file);
|
|
1126
|
+
};
|
|
1127
|
+
|
|
1128
|
+
// packages/core/src/persistence/workspace-checkpoints.ts
|
|
1129
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
1130
|
+
import path2 from "node:path";
|
|
1131
|
+
import { z } from "zod";
|
|
1132
|
+
var fileSchema = z.strictObject({
|
|
1133
|
+
path: workspaceFilePathSchema,
|
|
1134
|
+
digest: fileDigestSchema,
|
|
1135
|
+
content: z.string().max(65536),
|
|
1136
|
+
mode: z.number().int().min(0).max(511)
|
|
1137
|
+
}).refine((file) => Buffer.byteLength(file.content) <= 65536 && !file.content.includes("\x00") && file.digest === `sha256:${createHash("sha256").update(file.content).digest("hex")}`, "Invalid checkpoint content identity.");
|
|
1138
|
+
var workspaceCheckpointSchema = z.strictObject({
|
|
1139
|
+
id: z.string().uuid(),
|
|
1140
|
+
sessionId: z.string(),
|
|
1141
|
+
turnId: z.string(),
|
|
1142
|
+
files: z.array(fileSchema).min(1).max(20)
|
|
1143
|
+
});
|
|
1144
|
+
var workspaceRestoreOperationSchema = z.strictObject({
|
|
1145
|
+
id: z.string().uuid(),
|
|
1146
|
+
checkpoint: workspaceCheckpointSchema,
|
|
1147
|
+
proposalId: fileDigestSchema,
|
|
1148
|
+
expected: z.record(z.string(), fileDigestSchema),
|
|
1149
|
+
stage: z.enum(["prepared", "forking", "forked", "applying", "applied", "completed"]),
|
|
1150
|
+
forkSessionId: z.string().optional()
|
|
1151
|
+
});
|
|
1152
|
+
var digest = (content) => `sha256:${createHash("sha256").update(content).digest("hex")}`;
|
|
1153
|
+
var retentionSelection = z.object({ checkpointIds: z.array(z.string().uuid()).max(100), completedRestoreIds: z.array(z.string().uuid()).max(100) }).strict().refine((value) => value.checkpointIds.length + value.completedRestoreIds.length > 0 && new Set([...value.checkpointIds, ...value.completedRestoreIds]).size === value.checkpointIds.length + value.completedRestoreIds.length, "Select unique checkpoint and completed restore IDs.");
|
|
1154
|
+
var openWorkspaceCheckpointStore = async (workspace, sessions) => {
|
|
1155
|
+
const key = createHash("sha256").update("workspace\x00").update(workspace.root).digest("hex");
|
|
1156
|
+
if (key !== sessions.workspaceKey)
|
|
1157
|
+
throw new Error("Checkpoint session store belongs to a different workspace.");
|
|
1158
|
+
const before = await statRegularFileNoFollow(sessions.databasePath, { label: "Checkpoint database", requireSingleLink: true });
|
|
1159
|
+
if (before.uid !== process.getuid?.() || before.mode & 63)
|
|
1160
|
+
throw new Error("Checkpoint database must be private.");
|
|
1161
|
+
const db = new SqliteDatabase(sessions.databasePath, { create: false });
|
|
1162
|
+
const after = await statRegularFileNoFollow(sessions.databasePath, { label: "Checkpoint database", requireSingleLink: true });
|
|
1163
|
+
if (before.dev !== after.dev || before.ino !== after.ino) {
|
|
1164
|
+
db.close();
|
|
1165
|
+
throw new Error("Checkpoint database changed.");
|
|
1166
|
+
}
|
|
1167
|
+
db.exec("CREATE TABLE IF NOT EXISTS zhivex_workspace_checkpoints (id TEXT PRIMARY KEY, workspace_key TEXT NOT NULL, scope_key TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL)");
|
|
1168
|
+
const save = (kind, value) => {
|
|
1169
|
+
const existing = db.query("SELECT id FROM zhivex_workspace_checkpoints WHERE id=?").get(value.id);
|
|
1170
|
+
const count = db.query("SELECT COUNT(*) AS count FROM zhivex_workspace_checkpoints WHERE workspace_key=? AND scope_key=?").get(sessions.workspaceKey, sessions.scopeKey)?.count ?? 0;
|
|
1171
|
+
if (!existing && count >= 100)
|
|
1172
|
+
throw new Error("Checkpoint scope storage limit reached (100 records).");
|
|
1173
|
+
const body = JSON.stringify(value);
|
|
1174
|
+
if (Buffer.byteLength(body) > 2 * 1024 * 1024)
|
|
1175
|
+
throw new Error("Checkpoint exceeds storage limit.");
|
|
1176
|
+
db.query("INSERT INTO zhivex_workspace_checkpoints(id, workspace_key, scope_key, kind, body) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET body=excluded.body WHERE workspace_key=excluded.workspace_key AND scope_key=excluded.scope_key AND kind=excluded.kind").run(value.id, sessions.workspaceKey, sessions.scopeKey, kind, body);
|
|
1177
|
+
};
|
|
1178
|
+
const load = (kind, id) => {
|
|
1179
|
+
const row = db.query("SELECT body FROM zhivex_workspace_checkpoints WHERE id=? AND workspace_key=? AND scope_key=? AND kind=?").get(id, sessions.workspaceKey, sessions.scopeKey, kind);
|
|
1180
|
+
if (!row)
|
|
1181
|
+
throw new Error("Unknown checkpoint or restore operation in this scope.");
|
|
1182
|
+
return JSON.parse(row.body);
|
|
1183
|
+
};
|
|
1184
|
+
const read = async (target) => {
|
|
1185
|
+
const authorized = await workspace.readFile(target, 1, 1);
|
|
1186
|
+
const { contents, stat: stat2 } = await readRegularFileNoFollow(path2.join(workspace.root, target), {
|
|
1187
|
+
label: "Checkpoint target",
|
|
1188
|
+
maxBytes: 65536,
|
|
1189
|
+
requireSingleLink: true
|
|
1190
|
+
});
|
|
1191
|
+
const content = new TextDecoder("utf-8", { fatal: true }).decode(contents);
|
|
1192
|
+
if (contents.includes(0) || digest(contents) !== authorized.digest)
|
|
1193
|
+
throw new Error("Checkpoint file changed while reading.");
|
|
1194
|
+
return fileSchema.parse({ path: target, digest: digest(contents), content, mode: stat2.mode & 511 });
|
|
1195
|
+
};
|
|
1196
|
+
const validateTurn = async (checkpoint) => {
|
|
1197
|
+
const session = await sessions.get(checkpoint.sessionId);
|
|
1198
|
+
const run = session?.runs.find((entry) => entry.turnId === checkpoint.turnId);
|
|
1199
|
+
if (!session || !run || !TERMINAL_SESSION_RUN_STATUSES.includes(run.status)) {
|
|
1200
|
+
throw new Error("Checkpoint requires an existing terminal conversation turn.");
|
|
1201
|
+
}
|
|
1202
|
+
return session;
|
|
1203
|
+
};
|
|
1204
|
+
const proposal = (operation) => {
|
|
1205
|
+
if (new Set(operation.checkpoint.files.map((file) => file.path)).size !== operation.checkpoint.files.length || operation.checkpoint.files.some((file) => digest(file.content) !== file.digest))
|
|
1206
|
+
throw new Error("Checkpoint content identity is corrupt.");
|
|
1207
|
+
const changes = operation.checkpoint.files.map((file) => ({ path: file.path, expectedDigest: operation.expected[file.path], content: file.content }));
|
|
1208
|
+
const result = createEditProposal({ changes });
|
|
1209
|
+
if (result.proposalId !== operation.proposalId)
|
|
1210
|
+
throw new Error("Restore proposal identity is corrupt.");
|
|
1211
|
+
return { proposalId: result.proposalId, changes };
|
|
1212
|
+
};
|
|
1213
|
+
const getOperation = (id) => workspaceRestoreOperationSchema.parse(load("restore", id));
|
|
1214
|
+
const list = (kind) => db.query("SELECT body FROM zhivex_workspace_checkpoints WHERE workspace_key=? AND scope_key=? AND kind=? ORDER BY id").all(sessions.workspaceKey, sessions.scopeKey, kind).map((row) => JSON.parse(row.body));
|
|
1215
|
+
const summary = (checkpoint) => ({
|
|
1216
|
+
id: checkpoint.id,
|
|
1217
|
+
sessionId: checkpoint.sessionId,
|
|
1218
|
+
turnId: checkpoint.turnId,
|
|
1219
|
+
files: checkpoint.files.map((file) => ({
|
|
1220
|
+
path: file.path,
|
|
1221
|
+
digest: file.digest,
|
|
1222
|
+
bytes: Buffer.byteLength(file.content),
|
|
1223
|
+
mode: file.mode
|
|
1224
|
+
}))
|
|
1225
|
+
});
|
|
1226
|
+
const inventory = () => db.query("SELECT id,kind,body FROM zhivex_workspace_checkpoints WHERE workspace_key=? AND scope_key=? ORDER BY id").all(sessions.workspaceKey, sessions.scopeKey).map((row) => {
|
|
1227
|
+
const value = row.kind === "checkpoint" ? workspaceCheckpointSchema.parse(JSON.parse(row.body)) : row.kind === "restore" ? workspaceRestoreOperationSchema.parse(JSON.parse(row.body)) : undefined;
|
|
1228
|
+
if (!value || value.id !== row.id)
|
|
1229
|
+
throw new Error("Invalid checkpoint inventory.");
|
|
1230
|
+
return { ...row, value };
|
|
1231
|
+
});
|
|
1232
|
+
const retentionPlan = (input) => {
|
|
1233
|
+
const selection = retentionSelection.parse(input);
|
|
1234
|
+
const rows = inventory();
|
|
1235
|
+
const selected = new Set([...selection.checkpointIds, ...selection.completedRestoreIds]);
|
|
1236
|
+
for (const id of selection.checkpointIds) {
|
|
1237
|
+
if (!rows.some((row) => row.id === id && row.kind === "checkpoint"))
|
|
1238
|
+
throw new Error("Unknown checkpoint selection in this scope.");
|
|
1239
|
+
}
|
|
1240
|
+
for (const id of selection.completedRestoreIds) {
|
|
1241
|
+
const row = rows.find((row2) => row2.id === id && row2.kind === "restore");
|
|
1242
|
+
if (!row || !("stage" in row.value) || row.value.stage !== "completed")
|
|
1243
|
+
throw new Error("Retention cannot remove pending or unknown restore evidence.");
|
|
1244
|
+
}
|
|
1245
|
+
for (const row of rows) {
|
|
1246
|
+
if ("checkpoint" in row.value && selection.checkpointIds.includes(row.value.checkpoint.id) && !selected.has(row.id)) {
|
|
1247
|
+
throw new Error("Checkpoint is still referenced by a retained restore operation.");
|
|
996
1248
|
}
|
|
997
|
-
repeated = key === previous ? repeated + 1 : 1;
|
|
998
|
-
previous = key;
|
|
999
|
-
if (repeated === 3)
|
|
1000
|
-
controller.abort(new Error("Repeated identical tool failures. Inspect /status and correct the cause before /continue."));
|
|
1001
1249
|
}
|
|
1250
|
+
const records = rows.filter((row) => selected.has(row.id)).map((row) => ({
|
|
1251
|
+
id: row.id,
|
|
1252
|
+
kind: row.kind,
|
|
1253
|
+
sessionId: "checkpoint" in row.value ? row.value.checkpoint.sessionId : row.value.sessionId,
|
|
1254
|
+
bytes: Buffer.byteLength(row.body)
|
|
1255
|
+
}));
|
|
1256
|
+
const planId = digest(JSON.stringify({
|
|
1257
|
+
workspace: sessions.workspaceKey,
|
|
1258
|
+
scope: sessions.scopeKey,
|
|
1259
|
+
selection: [...selected].sort(),
|
|
1260
|
+
inventory: rows.map((row) => [row.id, row.kind, digest(row.body)])
|
|
1261
|
+
}));
|
|
1262
|
+
return {
|
|
1263
|
+
planId,
|
|
1264
|
+
selection: { checkpointIds: [...selection.checkpointIds].sort(), completedRestoreIds: [...selection.completedRestoreIds].sort() },
|
|
1265
|
+
records,
|
|
1266
|
+
recordsBefore: rows.length,
|
|
1267
|
+
recordsAfter: rows.length - records.length,
|
|
1268
|
+
bytesRemoved: records.reduce((sum, row) => sum + row.bytes, 0),
|
|
1269
|
+
workspaceFilesChanged: false,
|
|
1270
|
+
conversationsChanged: false
|
|
1271
|
+
};
|
|
1002
1272
|
};
|
|
1003
|
-
|
|
1273
|
+
return {
|
|
1274
|
+
close: () => db.close(),
|
|
1275
|
+
getCheckpoint: (id) => workspaceCheckpointSchema.parse(load("checkpoint", id)),
|
|
1276
|
+
getOperation,
|
|
1277
|
+
storageStatus: () => {
|
|
1278
|
+
const rows = inventory();
|
|
1279
|
+
const operations = rows.filter((row) => ("stage" in row.value));
|
|
1280
|
+
const referenced = new Set(operations.map((row) => row.value.checkpoint.id));
|
|
1281
|
+
return {
|
|
1282
|
+
policy: "explicit-reviewed-removal",
|
|
1283
|
+
automaticEviction: false,
|
|
1284
|
+
maxRecords: 100,
|
|
1285
|
+
maxRecordBytes: 2 * 1024 * 1024,
|
|
1286
|
+
maxFilesPerCheckpoint: 20,
|
|
1287
|
+
maxFileBytes: 65536,
|
|
1288
|
+
records: rows.length,
|
|
1289
|
+
availableRecords: Math.max(0, 100 - rows.length),
|
|
1290
|
+
serializedBytes: rows.reduce((sum, row) => sum + Buffer.byteLength(row.body), 0),
|
|
1291
|
+
pendingRestores: operations.filter((row) => row.value.stage !== "completed").length,
|
|
1292
|
+
checkpoints: rows.filter((row) => row.kind === "checkpoint").map((row) => ({ id: row.id, referenced: referenced.has(row.id) }))
|
|
1293
|
+
};
|
|
1294
|
+
},
|
|
1295
|
+
prepareRetention: retentionPlan,
|
|
1296
|
+
applyRetention: async (selection, reviewedPlanId) => withWorkspaceMutation(workspace.root, async () => {
|
|
1297
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1298
|
+
try {
|
|
1299
|
+
const plan = retentionPlan(selection);
|
|
1300
|
+
if (plan.planId !== reviewedPlanId)
|
|
1301
|
+
throw new Error("Retention inventory changed or was not reviewed.");
|
|
1302
|
+
for (const row of plan.records)
|
|
1303
|
+
db.query("DELETE FROM zhivex_workspace_checkpoints WHERE id=? AND workspace_key=? AND scope_key=? AND kind=?").run(row.id, sessions.workspaceKey, sessions.scopeKey, row.kind);
|
|
1304
|
+
db.exec("COMMIT");
|
|
1305
|
+
return plan;
|
|
1306
|
+
} catch (error) {
|
|
1307
|
+
db.exec("ROLLBACK");
|
|
1308
|
+
throw error;
|
|
1309
|
+
}
|
|
1310
|
+
}),
|
|
1311
|
+
listCheckpoints: (sessionId) => list("checkpoint").map((value) => workspaceCheckpointSchema.parse(value)).filter((checkpoint) => checkpoint.sessionId === sessionId).map(summary),
|
|
1312
|
+
listRestores: (sessionId) => list("restore").map((value) => workspaceRestoreOperationSchema.parse(value)).filter((operation) => operation.checkpoint.sessionId === sessionId).map((operation) => ({
|
|
1313
|
+
id: operation.id,
|
|
1314
|
+
checkpointId: operation.checkpoint.id,
|
|
1315
|
+
proposalId: operation.proposalId,
|
|
1316
|
+
stage: operation.stage,
|
|
1317
|
+
...operation.forkSessionId ? { forkSessionId: operation.forkSessionId } : {}
|
|
1318
|
+
})),
|
|
1319
|
+
inspectCheckpoint: async (id) => {
|
|
1320
|
+
const checkpoint = workspaceCheckpointSchema.parse(load("checkpoint", id));
|
|
1321
|
+
const files = await Promise.all(checkpoint.files.map(async (file) => {
|
|
1322
|
+
try {
|
|
1323
|
+
const current = await read(file.path);
|
|
1324
|
+
if (current.mode !== file.mode)
|
|
1325
|
+
return { path: file.path, status: "mode-conflict" };
|
|
1326
|
+
return {
|
|
1327
|
+
path: file.path,
|
|
1328
|
+
status: "available",
|
|
1329
|
+
before: current.content,
|
|
1330
|
+
after: file.content,
|
|
1331
|
+
expectedDigest: current.digest,
|
|
1332
|
+
afterDigest: file.digest,
|
|
1333
|
+
mode: file.mode
|
|
1334
|
+
};
|
|
1335
|
+
} catch {
|
|
1336
|
+
return { path: file.path, status: "unavailable" };
|
|
1337
|
+
}
|
|
1338
|
+
}));
|
|
1339
|
+
return {
|
|
1340
|
+
checkpoint: summary(checkpoint),
|
|
1341
|
+
files,
|
|
1342
|
+
coverage: {
|
|
1343
|
+
existingTextOnly: true,
|
|
1344
|
+
maxFiles: 20,
|
|
1345
|
+
maxFileBytes: 65536,
|
|
1346
|
+
creation: false,
|
|
1347
|
+
deletion: false,
|
|
1348
|
+
binary: false,
|
|
1349
|
+
modeRollback: false,
|
|
1350
|
+
fullWorkspaceSnapshot: false
|
|
1351
|
+
}
|
|
1352
|
+
};
|
|
1353
|
+
},
|
|
1354
|
+
previewRestore: async (id) => {
|
|
1355
|
+
const operation = getOperation(id);
|
|
1356
|
+
for (const file of operation.checkpoint.files) {
|
|
1357
|
+
if ((await read(file.path)).mode !== file.mode)
|
|
1358
|
+
throw new Error(`Restore mode conflict: ${file.path}.`);
|
|
1359
|
+
}
|
|
1360
|
+
return workspace.previewPatch(proposal(operation));
|
|
1361
|
+
},
|
|
1362
|
+
capture: async (input) => withWorkspaceMutation(workspace.root, async () => {
|
|
1363
|
+
await validateTurn(input);
|
|
1364
|
+
if (input.paths.length === 0 || input.paths.length > 20 || new Set(input.paths).size !== input.paths.length)
|
|
1365
|
+
throw new Error("Capture requires 1 to 20 unique existing text files.");
|
|
1366
|
+
const files = [];
|
|
1367
|
+
for (const target of input.paths)
|
|
1368
|
+
files.push(await read(target));
|
|
1369
|
+
const checkpoint = workspaceCheckpointSchema.parse({ id: randomUUID(), sessionId: input.sessionId, turnId: input.turnId, files });
|
|
1370
|
+
save("checkpoint", checkpoint);
|
|
1371
|
+
return checkpoint;
|
|
1372
|
+
}),
|
|
1373
|
+
prepareRestore: async (checkpointId, expectedCurrent) => withWorkspaceMutation(workspace.root, async () => {
|
|
1374
|
+
const checkpoint = workspaceCheckpointSchema.parse(load("checkpoint", checkpointId));
|
|
1375
|
+
await validateTurn(checkpoint);
|
|
1376
|
+
if (Object.keys(expectedCurrent).length !== checkpoint.files.length)
|
|
1377
|
+
throw new Error("Provide exact post-agent digests for every captured file.");
|
|
1378
|
+
for (const file of checkpoint.files) {
|
|
1379
|
+
const current = await read(file.path);
|
|
1380
|
+
if (current.digest !== expectedCurrent[file.path] || current.mode !== file.mode)
|
|
1381
|
+
throw new Error(`Restore conflicts with current content or mode: ${file.path}.`);
|
|
1382
|
+
}
|
|
1383
|
+
const changes = checkpoint.files.map((file) => ({ path: file.path, expectedDigest: expectedCurrent[file.path], content: file.content }));
|
|
1384
|
+
const preview = createEditProposal({ changes });
|
|
1385
|
+
const operation = workspaceRestoreOperationSchema.parse({
|
|
1386
|
+
id: randomUUID(),
|
|
1387
|
+
checkpoint,
|
|
1388
|
+
proposalId: preview.proposalId,
|
|
1389
|
+
expected: expectedCurrent,
|
|
1390
|
+
stage: "prepared"
|
|
1391
|
+
});
|
|
1392
|
+
save("restore", operation);
|
|
1393
|
+
return { operation, proposal: { ...preview, changes } };
|
|
1394
|
+
}),
|
|
1395
|
+
applyRestore: async (id, reviewedProposalId) => withWorkspaceMutation(workspace.root, async () => {
|
|
1396
|
+
const operation = getOperation(id);
|
|
1397
|
+
if (operation.proposalId !== reviewedProposalId)
|
|
1398
|
+
throw new Error("Restore requires the reviewed proposal identity.");
|
|
1399
|
+
const patch = proposal(operation);
|
|
1400
|
+
if (operation.stage === "completed")
|
|
1401
|
+
return operation;
|
|
1402
|
+
if (operation.stage === "forking")
|
|
1403
|
+
throw new Error(`Fork outcome uncertain. Inspect child sessions titled restore:${operation.id} and call recoverFork with the exact child ID; no files changed.`);
|
|
1404
|
+
const current = [];
|
|
1405
|
+
for (const file of operation.checkpoint.files) {
|
|
1406
|
+
const found = await read(file.path);
|
|
1407
|
+
if (found.mode !== file.mode)
|
|
1408
|
+
throw new Error(`Restore mode conflict: ${file.path}.`);
|
|
1409
|
+
current.push(found);
|
|
1410
|
+
}
|
|
1411
|
+
const beforeApply = current.every((file) => file.digest === operation.expected[file.path]);
|
|
1412
|
+
const afterApply = current.every((file) => file.digest === operation.checkpoint.files.find((entry) => entry.path === file.path)?.digest);
|
|
1413
|
+
if (["applying", "applied"].includes(operation.stage) && afterApply) {
|
|
1414
|
+
operation.stage = "completed";
|
|
1415
|
+
save("restore", operation);
|
|
1416
|
+
return operation;
|
|
1417
|
+
}
|
|
1418
|
+
if (!beforeApply || operation.stage === "applied")
|
|
1419
|
+
throw new Error("Restore conflicts with subsequent edits or a partially applied filesystem operation; manual recovery required.");
|
|
1420
|
+
if (operation.stage === "prepared") {
|
|
1421
|
+
const source = await validateTurn(operation.checkpoint);
|
|
1422
|
+
operation.stage = "forking";
|
|
1423
|
+
save("restore", operation);
|
|
1424
|
+
const fork = await sessions.fork(source.sessionId, {
|
|
1425
|
+
atTurnId: operation.checkpoint.turnId,
|
|
1426
|
+
expectedRevision: source.revision,
|
|
1427
|
+
title: `restore:${operation.id}`
|
|
1428
|
+
});
|
|
1429
|
+
operation.forkSessionId = fork.sessionId;
|
|
1430
|
+
operation.stage = "forked";
|
|
1431
|
+
save("restore", operation);
|
|
1432
|
+
}
|
|
1433
|
+
if (!operation.forkSessionId)
|
|
1434
|
+
throw new Error("Restore has no recorded conversation fork.");
|
|
1435
|
+
operation.stage = "applying";
|
|
1436
|
+
save("restore", operation);
|
|
1437
|
+
await workspace.applyPatchWithModes(patch, new Map(operation.checkpoint.files.map((file) => [file.path, { beforeMode: file.mode, afterMode: file.mode }])));
|
|
1438
|
+
operation.stage = "applied";
|
|
1439
|
+
save("restore", operation);
|
|
1440
|
+
operation.stage = "completed";
|
|
1441
|
+
save("restore", operation);
|
|
1442
|
+
return operation;
|
|
1443
|
+
}),
|
|
1444
|
+
recoverFork: async (id, forkSessionId) => withWorkspaceMutation(workspace.root, async () => {
|
|
1445
|
+
const operation = getOperation(id);
|
|
1446
|
+
const fork = await sessions.get(forkSessionId);
|
|
1447
|
+
if (operation.stage !== "forking" || !fork || fork.parentSessionId !== operation.checkpoint.sessionId || fork.forkedFromTurnId !== operation.checkpoint.turnId || fork.title !== `restore:${operation.id}`)
|
|
1448
|
+
throw new Error("Fork does not match this interrupted restore.");
|
|
1449
|
+
operation.forkSessionId = forkSessionId;
|
|
1450
|
+
operation.stage = "forked";
|
|
1451
|
+
save("restore", operation);
|
|
1452
|
+
return operation;
|
|
1453
|
+
})
|
|
1454
|
+
};
|
|
1455
|
+
};
|
|
1004
1456
|
|
|
1005
|
-
// src/cli/console/console-
|
|
1457
|
+
// packages/core/src/cli/console/console-checkpoints.ts
|
|
1458
|
+
var coverage = `Checkpoint coverage: 1–20 selected existing UTF-8 files, at most 64 KiB each. No creation, deletion, binary or mode restore. No automatic rollback.
|
|
1459
|
+
`;
|
|
1460
|
+
var handleConsoleCheckpoint = async (command, context) => {
|
|
1461
|
+
if (command !== "/checkpoint" && !command.startsWith("/checkpoint "))
|
|
1462
|
+
return false;
|
|
1463
|
+
const write = context.write ?? ((text) => {
|
|
1464
|
+
process.stdout.write(text);
|
|
1465
|
+
});
|
|
1466
|
+
write(coverage);
|
|
1467
|
+
if (await context.hasActiveTurn()) {
|
|
1468
|
+
write(`Finish or deny pending work before using checkpoints.
|
|
1469
|
+
`);
|
|
1470
|
+
return true;
|
|
1471
|
+
}
|
|
1472
|
+
const store = await openWorkspaceCheckpointStore(context.workspace, context.sessions);
|
|
1473
|
+
let fork;
|
|
1474
|
+
try {
|
|
1475
|
+
const match = /^(\S+)(?:\s+([\s\S]*))?$/.exec(command.slice("/checkpoint".length).trim());
|
|
1476
|
+
const argument = match?.[1], target = match?.[2] ?? "";
|
|
1477
|
+
const action = argument || await context.input.select("Checkpoints", [
|
|
1478
|
+
{ value: "capture", label: "Capture selected files" },
|
|
1479
|
+
{ value: "list", label: "List captures and restore operations" },
|
|
1480
|
+
{ value: "review", label: "Review a checkpoint" },
|
|
1481
|
+
{ value: "restore", label: "Review and restore selected files" },
|
|
1482
|
+
{ value: "retry", label: "Review an existing restore operation", detail: "Retains its original digests; conflicts require manual recovery" }
|
|
1483
|
+
]);
|
|
1484
|
+
if (!action)
|
|
1485
|
+
return true;
|
|
1486
|
+
if (action === "list") {
|
|
1487
|
+
write(sanitizeTerminalText(JSON.stringify({
|
|
1488
|
+
checkpoints: store.listCheckpoints(context.session.sessionId),
|
|
1489
|
+
restores: store.listRestores(context.session.sessionId),
|
|
1490
|
+
storage: store.storageStatus()
|
|
1491
|
+
}, null, 2)) + `
|
|
1492
|
+
`);
|
|
1493
|
+
} else if (action === "capture") {
|
|
1494
|
+
const turn = context.session.runs.at(-1);
|
|
1495
|
+
if (!turn) {
|
|
1496
|
+
write(`Complete a task before capturing its conversation turn.
|
|
1497
|
+
`);
|
|
1498
|
+
return true;
|
|
1499
|
+
}
|
|
1500
|
+
const raw = target || await context.input.question('Workspace paths as a JSON array (e.g. ["greeting.mjs"]): ');
|
|
1501
|
+
const paths = JSON.parse(raw);
|
|
1502
|
+
if (!Array.isArray(paths) || !paths.every((value) => typeof value === "string"))
|
|
1503
|
+
throw new Error("Paths must be a JSON array of strings.");
|
|
1504
|
+
const checkpoint = await store.capture({ sessionId: context.session.sessionId, turnId: turn.turnId, paths });
|
|
1505
|
+
write(`Captured checkpoint ${checkpoint.id} · ${checkpoint.files.length} files · turn ${turn.turnId}
|
|
1506
|
+
`);
|
|
1507
|
+
} else if (["review", "restore", "retry"].includes(action)) {
|
|
1508
|
+
const choices = action === "retry" ? store.listRestores(context.session.sessionId).filter((item) => item.stage !== "completed").map((item) => ({ value: item.id, label: item.id, detail: item.stage })) : store.listCheckpoints(context.session.sessionId).map((item) => ({ value: item.id, label: item.id, detail: item.files.map((file) => file.path).join(", ") }));
|
|
1509
|
+
const id = target || await context.input.select(action === "retry" ? "Restore operations" : "Saved checkpoints", choices);
|
|
1510
|
+
if (!id)
|
|
1511
|
+
return true;
|
|
1512
|
+
let operation;
|
|
1513
|
+
if (action === "retry") {
|
|
1514
|
+
operation = store.getOperation(id);
|
|
1515
|
+
if (operation.checkpoint.sessionId !== context.session.sessionId)
|
|
1516
|
+
throw new Error("Restore is outside this conversation.");
|
|
1517
|
+
if (operation.stage === "forking") {
|
|
1518
|
+
write(`Restore ${operation.id} has an uncertain fork. Inspect child sessions titled restore:${operation.id}; manual engine recovery is required. No retry or new fork was attempted.
|
|
1519
|
+
`);
|
|
1520
|
+
return true;
|
|
1521
|
+
}
|
|
1522
|
+
} else {
|
|
1523
|
+
const view = await store.inspectCheckpoint(id);
|
|
1524
|
+
if (view.checkpoint.sessionId !== context.session.sessionId)
|
|
1525
|
+
throw new Error("Checkpoint is outside this conversation.");
|
|
1526
|
+
for (const file of view.files) {
|
|
1527
|
+
write(file.status === "available" ? `Current digest: ${file.expectedDigest}
|
|
1528
|
+
` + formatFileDiff(file) : `${sanitizeTerminalText(file.path)}: ${file.status}; restore blocked.
|
|
1529
|
+
`);
|
|
1530
|
+
}
|
|
1531
|
+
if (action === "review" || view.files.some((file) => file.status !== "available"))
|
|
1532
|
+
return true;
|
|
1533
|
+
if ((await context.input.question("Review current contents and digests above. Type prepare to adopt these exact restore preconditions: ")).trim() !== "prepare")
|
|
1534
|
+
return true;
|
|
1535
|
+
const expected = Object.fromEntries(view.files.flatMap((file) => file.status === "available" ? [[file.path, file.expectedDigest]] : []));
|
|
1536
|
+
operation = (await store.prepareRestore(id, expected)).operation;
|
|
1537
|
+
}
|
|
1538
|
+
write(`Restore operation ${operation.id} · ${operation.stage}
|
|
1539
|
+
`);
|
|
1540
|
+
const preview = await store.previewRestore(operation.id);
|
|
1541
|
+
for (const file of preview.files)
|
|
1542
|
+
write(formatFileDiff(file));
|
|
1543
|
+
write(`Proposal: ${preview.proposalId}
|
|
1544
|
+
Restoring forks the captured conversation; the original is retained.
|
|
1545
|
+
`);
|
|
1546
|
+
if ((await context.input.question("Type restore to apply this exact reviewed proposal (Enter leaves it pending): ")).trim() !== "restore")
|
|
1547
|
+
return true;
|
|
1548
|
+
const result = await store.applyRestore(operation.id, preview.proposalId);
|
|
1549
|
+
write(`Restore ${result.id}: ${result.stage}
|
|
1550
|
+
`);
|
|
1551
|
+
if (result.forkSessionId)
|
|
1552
|
+
fork = await context.sessions.get(result.forkSessionId);
|
|
1553
|
+
} else
|
|
1554
|
+
write(`Use /checkpoint [capture [JSON paths]|list|review [id]|restore [id]|retry [operationId]].
|
|
1555
|
+
`);
|
|
1556
|
+
} finally {
|
|
1557
|
+
store.close();
|
|
1558
|
+
}
|
|
1559
|
+
if (fork) {
|
|
1560
|
+
await context.restoreSession(fork);
|
|
1561
|
+
write(`Restored conversation: ${fork.sessionId} (fork of ${context.session.sessionId}).
|
|
1562
|
+
`);
|
|
1563
|
+
}
|
|
1564
|
+
return true;
|
|
1565
|
+
};
|
|
1566
|
+
|
|
1567
|
+
// packages/core/src/cli/console/console-task.ts
|
|
1568
|
+
import { execFile } from "node:child_process";
|
|
1569
|
+
import { promisify } from "node:util";
|
|
1570
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1571
|
+
import { z as z2 } from "zod";
|
|
1572
|
+
|
|
1573
|
+
// packages/core/src/cli/console/console-budget.ts
|
|
1006
1574
|
var tokenOptions = [
|
|
1007
1575
|
"maxInputTokens",
|
|
1008
1576
|
"maxOutputTokens",
|
|
@@ -1019,14 +1587,17 @@ var tokenEnvironment = [
|
|
|
1019
1587
|
"ZHIVEX_HARNESS_SUBAGENT_MAX_OUTPUT_TOKENS",
|
|
1020
1588
|
"ZHIVEX_HARNESS_SUBAGENT_MAX_TOTAL_TOKENS"
|
|
1021
1589
|
];
|
|
1022
|
-
var
|
|
1590
|
+
var interactiveBudgetOptions = (options, env = process.env) => ({
|
|
1023
1591
|
...options,
|
|
1024
|
-
...options.maxToolErrors === undefined && env.ZHIVEX_HARNESS_MAX_TOOL_ERRORS === undefined ? { maxToolErrors: 20 } : {},
|
|
1025
1592
|
unlimitedSteps: options.unlimitedSteps ?? (options.maxSteps === undefined && env.ZHIVEX_HARNESS_MAX_STEPS === undefined),
|
|
1026
1593
|
unlimitedToolCalls: options.unlimitedToolCalls ?? (options.maxToolCalls === undefined && env.ZHIVEX_HARNESS_MAX_TOOL_CALLS === undefined),
|
|
1027
1594
|
unlimitedDuration: options.unlimitedDuration ?? (options.timeoutMs === undefined && env.ZHIVEX_HARNESS_TIMEOUT_MS === undefined),
|
|
1028
1595
|
unlimitedTokens: options.unlimitedTokens ?? !(tokenOptions.some((key) => options[key] !== undefined) || tokenEnvironment.some((key) => env[key] !== undefined))
|
|
1029
1596
|
});
|
|
1597
|
+
var consoleBudgetOptions = (options, env = process.env) => ({
|
|
1598
|
+
...interactiveBudgetOptions(options, env),
|
|
1599
|
+
...options.maxToolErrors === undefined && env.ZHIVEX_HARNESS_MAX_TOOL_ERRORS === undefined ? { maxToolErrors: 20 } : {}
|
|
1600
|
+
});
|
|
1030
1601
|
var restoreConsoleOptions = (current, saved) => ({
|
|
1031
1602
|
...current,
|
|
1032
1603
|
...saved,
|
|
@@ -1037,8 +1608,10 @@ var restoreConsoleOptions = (current, saved) => ({
|
|
|
1037
1608
|
unlimitedDuration: saved.unlimitedDuration ?? false
|
|
1038
1609
|
});
|
|
1039
1610
|
var formatConsoleBudget = (config, usage) => {
|
|
1040
|
-
const lines = [`Step limit: ${config.budget.unlimitedSteps ? "none" : config.maxSteps} model iterations per turn.`, config.budget.unlimitedTokens ? "Cumulative token budget: unlimited; operation, model, state and safety controls still apply." : `Cumulative token limits per run: input ${config.budget.maxInputTokens}; output ${config.budget.maxOutputTokens}; total ${config.budget.maxTotalTokens}.`];
|
|
1611
|
+
const lines = [`Step limit: ${config.budget.unlimitedSteps ? "none" : config.maxSteps} model iterations per turn.`, config.budget.unlimitedTokens ? "Cumulative token budget per run: unlimited; operation, model, state and safety controls still apply." : `Cumulative token limits per run: input ${config.budget.maxInputTokens}; output ${config.budget.maxOutputTokens}; total ${config.budget.maxTotalTokens}.`];
|
|
1041
1612
|
lines.push(`Tool limits: ${config.budget.unlimitedToolCalls ? "no cumulative cap on" : config.budget.maxToolCalls} calls / ${config.budget.maxToolErrors} errors; time: ${config.unlimitedDuration ? "no cumulative deadline" : `${Math.round(config.timeoutMs / 60000)} minutes per run`}.`);
|
|
1613
|
+
if (config.costBudget)
|
|
1614
|
+
lines.push(`Legacy measured-cost limit: $${config.costBudget.maxCostUsd} per run (estimate, not an invoice or guaranteed financial cap).`);
|
|
1042
1615
|
if (!usage)
|
|
1043
1616
|
return [...lines, "Latest run usage: unavailable."].join(`
|
|
1044
1617
|
`);
|
|
@@ -1053,7 +1626,7 @@ var formatConsoleBudget = (config, usage) => {
|
|
|
1053
1626
|
`);
|
|
1054
1627
|
};
|
|
1055
1628
|
|
|
1056
|
-
// src/cli/console/console-context.ts
|
|
1629
|
+
// packages/core/src/cli/console/console-context.ts
|
|
1057
1630
|
var retainedSkills = (context, messages) => {
|
|
1058
1631
|
const ids = new Set;
|
|
1059
1632
|
for (const message of messages) {
|
|
@@ -1096,24 +1669,24 @@ var formatConsoleDiff = (diff, color) => diff.split(`
|
|
|
1096
1669
|
const safe = sanitizeTerminalText(line);
|
|
1097
1670
|
if (!color)
|
|
1098
1671
|
return safe;
|
|
1099
|
-
const code = line.startsWith("+") ?
|
|
1100
|
-
return code ?
|
|
1672
|
+
const code = line.startsWith("+") ? "added" : line.startsWith("-") ? "removed" : line.startsWith("@@") ? "info" : undefined;
|
|
1673
|
+
return code ? paintTerminal(safe, code, color) : safe;
|
|
1101
1674
|
}).join(`
|
|
1102
1675
|
`);
|
|
1103
1676
|
|
|
1104
1677
|
class ConsoleAttachments {
|
|
1105
1678
|
files = new Map;
|
|
1106
1679
|
list() {
|
|
1107
|
-
return [...this.files.values()].map(({ path:
|
|
1680
|
+
return [...this.files.values()].map(({ path: path3, digest: digest2, truncated }) => ({ path: path3, digest: digest2, truncated }));
|
|
1108
1681
|
}
|
|
1109
1682
|
clear() {
|
|
1110
1683
|
this.files.clear();
|
|
1111
1684
|
}
|
|
1112
|
-
remove(
|
|
1113
|
-
return this.files.delete(
|
|
1685
|
+
remove(path3) {
|
|
1686
|
+
return this.files.delete(path3);
|
|
1114
1687
|
}
|
|
1115
|
-
async add(workspace,
|
|
1116
|
-
const file = await workspace.readFile(
|
|
1688
|
+
async add(workspace, path3) {
|
|
1689
|
+
const file = await workspace.readFile(path3);
|
|
1117
1690
|
const next = new Map(this.files).set(file.path, file);
|
|
1118
1691
|
if (next.size > 8 || [...next.values()].reduce((sum, value) => sum + Buffer.byteLength(value.content), 0) > 64 * 1024) {
|
|
1119
1692
|
throw new Error("Attachments exceed 8 files or 64 KiB; use a smaller selection.");
|
|
@@ -1136,10 +1709,487 @@ ${JSON.stringify([...this.files.values()])}`;
|
|
|
1136
1709
|
}
|
|
1137
1710
|
}
|
|
1138
1711
|
|
|
1139
|
-
// src/cli/console.ts
|
|
1140
|
-
|
|
1712
|
+
// packages/core/src/cli/console/console-diff.ts
|
|
1713
|
+
async function consoleWorkspaceDiff(workspace, color = false) {
|
|
1714
|
+
const result = await workspace.gitDiff();
|
|
1715
|
+
const commands = [result.status, result.diff, result.staged];
|
|
1716
|
+
const failed = commands.filter((command) => command.exitCode !== 0 || command.timedOut);
|
|
1717
|
+
if (failed.length)
|
|
1718
|
+
return `Git review unavailable; absence of changes is not established.
|
|
1719
|
+
` + failed.map((command) => sanitizeTerminalText(command.stderr.trim() || `Git command failed (exit ${command.exitCode}, timeout ${command.timedOut}).`)).join(`
|
|
1720
|
+
`) + `
|
|
1721
|
+
Use /activity for observed mutations; initialize Git or inspect files manually.
|
|
1722
|
+
`;
|
|
1723
|
+
return formatConsoleDiff(commands.map((command) => command.stdout).join(""), color) || `No Git-visible workspace changes.
|
|
1724
|
+
`;
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
// packages/core/src/cli/console/console-task.ts
|
|
1728
|
+
var CODE_TASK_KEY = "zhivexCodeTaskV1";
|
|
1729
|
+
var briefSchema = z2.strictObject({
|
|
1730
|
+
goal: z2.string().trim().min(1).max(2000),
|
|
1731
|
+
paths: z2.array(z2.string()).min(1).max(20),
|
|
1732
|
+
checks: z2.array(z2.string()).min(1).max(8),
|
|
1733
|
+
budget: z2.strictObject({ inputTokens: z2.number().int().positive().safe(), outputTokens: z2.number().int().positive().safe(), totalTokens: z2.number().int().positive().safe() }).optional(),
|
|
1734
|
+
constraints: z2.array(z2.string().trim().min(1).max(500)).max(8).default([])
|
|
1735
|
+
});
|
|
1736
|
+
var taskSchema = z2.strictObject({
|
|
1737
|
+
schemaVersion: z2.literal(1),
|
|
1738
|
+
goal: briefSchema.shape.goal,
|
|
1739
|
+
constraints: briefSchema.shape.constraints,
|
|
1740
|
+
contract: z2.unknown(),
|
|
1741
|
+
baseline: z2.record(z2.string(), z2.string()),
|
|
1742
|
+
budgetVersion: z2.literal(1).optional(),
|
|
1743
|
+
keep: z2.strictObject({ runId: z2.string(), snapshotDigest: z2.string(), at: z2.number() }).optional()
|
|
1744
|
+
});
|
|
1745
|
+
function restoredCodeTask(state) {
|
|
1746
|
+
const raw = state?.metadata?.[CODE_TASK_KEY];
|
|
1747
|
+
if (raw === undefined)
|
|
1748
|
+
return;
|
|
1749
|
+
const parsed = taskSchema.parse(raw);
|
|
1750
|
+
return { ...parsed, contract: compileTaskAcceptanceContract(parsed.contract).contract };
|
|
1751
|
+
}
|
|
1752
|
+
var execFileAsync = promisify(execFile);
|
|
1753
|
+
async function requireGitVisibleTaskFiles(harness, paths) {
|
|
1754
|
+
for (const path3 of paths) {
|
|
1755
|
+
try {
|
|
1756
|
+
const { stdout } = await execFileAsync("git", ["--literal-pathspecs", "ls-files", "--error-unmatch", "-v", "-z", "--", path3], { cwd: harness.workspace.root, encoding: "utf8", timeout: 1e4, maxBuffer: 64 * 1024 });
|
|
1757
|
+
if (stdout !== `H ${path3}\x00`)
|
|
1758
|
+
throw new Error("Selected file is hidden from Git review.");
|
|
1759
|
+
} catch {
|
|
1760
|
+
throw new Error(`Guided tasks require Git-tracked selected files visible to diff (no skip-worktree or assume-unchanged): ${path3}`);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
async function prepareCodeTask(harness, input) {
|
|
1765
|
+
if (harness.config.execution.backend !== "none" || harness.config.orchestration.profiles.length)
|
|
1766
|
+
throw new Error("Guided /task currently supports the native backend without subagents.");
|
|
1767
|
+
const brief = briefSchema.parse(input);
|
|
1768
|
+
const diff = await harness.workspace.gitDiff();
|
|
1769
|
+
if ([diff.status, diff.diff, diff.staged].some((result) => result.exitCode !== 0 || result.timedOut))
|
|
1770
|
+
throw new Error("Start a guided task in a Git repository; /diff can explain unavailable Git evidence.");
|
|
1771
|
+
if ([diff.status, diff.diff, diff.staged].some((result) => result.stdout.trim()))
|
|
1772
|
+
throw new Error("Task baseline requires a clean Git-visible workspace. Preserve existing changes yourself, or prepare a separate worktree before /task start.");
|
|
1773
|
+
const manifestFile = await harness.workspace.readFile("package.json");
|
|
1774
|
+
if (manifestFile.truncated)
|
|
1775
|
+
throw new Error("Task manifest must fit a complete workspace read.");
|
|
1776
|
+
const manifest = JSON.parse(manifestFile.content.replace(/^\d+: /gm, ""));
|
|
1777
|
+
const checks = await Promise.all(brief.checks.map(async (script, index) => {
|
|
1778
|
+
const expectedScript = manifest.scripts?.[script];
|
|
1779
|
+
if (typeof expectedScript !== "string" || !expectedScript.trim() || expectedScript.length > 2000)
|
|
1780
|
+
throw new Error(`Task check ${script} must be an existing nonblank package script at most 2000 characters.`);
|
|
1781
|
+
const resolved = await resolvePackageCheckCommand(harness.workspace.root, manifest, script, expectedScript, harness.config.allowedChecks);
|
|
1782
|
+
return {
|
|
1783
|
+
id: `check-${index + 1}`,
|
|
1784
|
+
kind: "package-script",
|
|
1785
|
+
script,
|
|
1786
|
+
expectedScript,
|
|
1787
|
+
command: resolved.command[0],
|
|
1788
|
+
args: resolved.command.slice(1),
|
|
1789
|
+
purpose: `Check ${script} for: ${brief.goal}`.slice(0, 500),
|
|
1790
|
+
execution: { backend: "none", approval: "required" }
|
|
1791
|
+
};
|
|
1792
|
+
}));
|
|
1793
|
+
const contract = compileTaskAcceptanceContract({
|
|
1794
|
+
schemaVersion: 1,
|
|
1795
|
+
taskId: randomUUID2(),
|
|
1796
|
+
allowedWritePaths: brief.paths,
|
|
1797
|
+
protectedFiles: ["package.json"],
|
|
1798
|
+
requiredChecks: checks,
|
|
1799
|
+
humanReview: [{ id: "operator", requirement: brief.goal, status: "pending" }, ...brief.constraints.map((requirement, index) => ({ id: `constraint-${index + 1}`, requirement, status: "pending" }))]
|
|
1800
|
+
}).contract;
|
|
1801
|
+
await requireGitVisibleTaskFiles(harness, contract.allowedWritePaths);
|
|
1802
|
+
const baseline = {};
|
|
1803
|
+
for (const path3 of contract.allowedWritePaths) {
|
|
1804
|
+
const file = await harness.workspace.inspectFile(path3);
|
|
1805
|
+
if (file.bytes > 64 * 1024)
|
|
1806
|
+
throw new Error("Guided tasks require selected existing text files at most 64 KiB each.");
|
|
1807
|
+
if ((await harness.workspace.readFile(path3)).digest !== file.digest)
|
|
1808
|
+
throw new Error("Task file changed during preparation. Retry with a stable baseline.");
|
|
1809
|
+
baseline[path3] = file.digest;
|
|
1810
|
+
}
|
|
1811
|
+
const inspected = await harness.workspace.gitDiff();
|
|
1812
|
+
if ([inspected.status, inspected.diff, inspected.staged].some((result) => result.exitCode !== 0 || result.timedOut || result.stdout.trim()))
|
|
1813
|
+
throw new Error("Git baseline changed during task preparation. Inspect your workspace before retrying.");
|
|
1814
|
+
await initializeHarnessTaskBudget(harness, contract.taskId, brief.budget);
|
|
1815
|
+
return { schemaVersion: 1, budgetVersion: 1, goal: brief.goal, constraints: brief.constraints, contract, baseline };
|
|
1816
|
+
}
|
|
1817
|
+
function codeTaskPrompt(task, prompt) {
|
|
1818
|
+
return `Operator task goal: ${task.goal}
|
|
1819
|
+
Constraints: ${task.constraints.join("; ") || "No additional constraints"}
|
|
1820
|
+
` + `Exact editable files: ${task.contract.allowedWritePaths.join(", ")}. Execute every declared check after the final edit. ` + `Passing checks leave human review pending; do not claim operator acceptance.
|
|
1821
|
+
|
|
1822
|
+
${prompt}`;
|
|
1823
|
+
}
|
|
1824
|
+
async function recoverCodeTask(harness, task) {
|
|
1825
|
+
if (task.budgetVersion !== 1)
|
|
1826
|
+
return task;
|
|
1827
|
+
const recovery = await inspectHarnessTaskContinuity(harness, task.contract.taskId);
|
|
1828
|
+
const current = recovery.currentContract;
|
|
1829
|
+
const digest2 = compileTaskAcceptanceContract(task.contract).digest;
|
|
1830
|
+
if (!current || current.digest === digest2)
|
|
1831
|
+
return task;
|
|
1832
|
+
const history = recovery.runs.at(-1).ledger.revisions;
|
|
1833
|
+
const prior = history.findIndex((revision) => revision.digest === digest2);
|
|
1834
|
+
const requirements = current.contract.humanReview;
|
|
1835
|
+
const constraints = requirements.filter((item) => item.id !== "operator").map((item) => item.requirement);
|
|
1836
|
+
if (prior < 0 || requirements.find((item) => item.id === "operator")?.requirement !== task.goal || constraints.length <= task.constraints.length || constraints.length > 8 || task.constraints.some((value, index) => constraints[index] !== value) || requirements.filter((item) => item.id !== "operator").some((item, index) => item.status !== "pending" || item.id !== `constraint-${index + 1}`) || history.slice(prior + 1).some((revision) => compileTaskAcceptanceContract({ ...revision.contract, humanReview: task.contract.humanReview }).digest !== digest2)) {
|
|
1837
|
+
throw new Error("TASK_CONTINUITY_CONTRACT_CONFLICT");
|
|
1838
|
+
}
|
|
1839
|
+
return { ...task, constraints, contract: current.contract, keep: undefined };
|
|
1840
|
+
}
|
|
1841
|
+
async function reviseCodeTask(harness, task, correction) {
|
|
1842
|
+
if (!correction.trim() || correction.length > 500 || task.constraints.length >= 8)
|
|
1843
|
+
throw new Error("A correction must be 1–500 characters; at most 8 constraints are supported.");
|
|
1844
|
+
const next = {
|
|
1845
|
+
...task,
|
|
1846
|
+
constraints: [...task.constraints, correction],
|
|
1847
|
+
keep: undefined,
|
|
1848
|
+
contract: { ...task.contract, humanReview: [
|
|
1849
|
+
{ id: "operator", requirement: task.goal, status: "pending" },
|
|
1850
|
+
...[...task.constraints, correction].map((requirement, index) => ({ id: `constraint-${index + 1}`, requirement, status: "pending" }))
|
|
1851
|
+
] }
|
|
1852
|
+
};
|
|
1853
|
+
const recovery = await inspectHarnessTaskContinuity(harness, task.contract.taskId);
|
|
1854
|
+
const latest = recovery.runs.at(-1);
|
|
1855
|
+
if (recovery.budget.runs.length && !latest)
|
|
1856
|
+
throw new Error("TASK_CONTINUITY_RUN_MISSING");
|
|
1857
|
+
if (latest) {
|
|
1858
|
+
if (recovery.currentContract?.digest !== compileTaskAcceptanceContract(task.contract).digest)
|
|
1859
|
+
throw new Error("TASK_CONTINUITY_CONTRACT_CONFLICT");
|
|
1860
|
+
await reviseHarnessTaskAcceptance(harness, {
|
|
1861
|
+
runId: latest.runId,
|
|
1862
|
+
expectedRunRevision: latest.revision,
|
|
1863
|
+
expectedContractRevision: recovery.currentContract.revision,
|
|
1864
|
+
contract: next.contract
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
return { ...next, contract: compileTaskAcceptanceContract(next.contract).contract };
|
|
1868
|
+
}
|
|
1869
|
+
function codeTaskBudgetRecap(value) {
|
|
1870
|
+
const { monetary, monetaryDetails, cancellations, ...tokenSummary } = value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1871
|
+
const summary = inspectTaskBudgetSummary(tokenSummary);
|
|
1872
|
+
if (!summary)
|
|
1873
|
+
return `Task budget: unavailable; further execution requires its established authority.
|
|
1874
|
+
`;
|
|
1875
|
+
const cancellation = Array.isArray(cancellations) ? cancellations.at(-1) : undefined;
|
|
1876
|
+
const money = monetaryDetails && typeof monetaryDetails === "object" ? monetaryDetails : undefined;
|
|
1877
|
+
const amount = (value2) => typeof value2 === "number" && Number.isFinite(value2) ? value2.toFixed(6) : "unknown";
|
|
1878
|
+
const tokens = (value2) => `input ${value2.inputTokens}; output ${value2.outputTokens}; total ${value2.totalTokens}`;
|
|
1879
|
+
return sanitizeTerminalText(`Task budget authority: ${summary.accountRunId} · revision ${summary.revision}
|
|
1880
|
+
` + `Task token limits: ${tokens(summary.limits)}
|
|
1881
|
+
Confirmed: ${tokens(summary.confirmed)}
|
|
1882
|
+
` + `Reserved: ${tokens(summary.reserved)}
|
|
1883
|
+
Unknown consumption held: ${!summary.usageComplete ? "unresolved actual usage; recorded exposure " : ""}${tokens(summary.unknown)}
|
|
1884
|
+
` + `Task remaining: ${tokens(summary.remaining)}
|
|
1885
|
+
` + (summary.invocationPending ? `Retained invocation: ${summary.activeRunId ?? "unresolved prior run"}; a new run cannot take over while its outcome remains pending.
|
|
1886
|
+
` : "") + `Task admission: ${summary.invocationPending ? "blocked by a retained invocation; inspect the prior run" : !summary.usageComplete ? "blocked by incomplete consumption; held reservations remain charged" : summary.admissionsClosed ? "closed; explicit continuation required" : "open subject to remaining budget"}
|
|
1887
|
+
` + (cancellation ? `Cancellation requested for ${String(cancellation.runId)}; ${cancellation.localExecution === "native_tools_drained" ? "native tool callbacks drained" : "local execution unconfirmed"}. Provider stop unconfirmed; prior work and receipts retained. Task acceptance remains separate.
|
|
1888
|
+
` : "") + (monetary !== undefined ? `Task monetary ${formatUsageLedger(monetary)}
|
|
1889
|
+
` : "") + (money ? `Estimated confirmed USD ${amount(money.estimatedConfirmedUsd)}; reserved ${amount(money.reservedUsd)}; unknown exposure held ${amount(money.unknownHeldUsd)}; remaining ${amount(money.remainingUsd)}. Late receipts: ${typeof money.lateCalls === "number" ? money.lateCalls : "unknown"}.
|
|
1890
|
+
` : ""));
|
|
1891
|
+
}
|
|
1892
|
+
async function freshCodeTaskBudgetRecap(harness, task) {
|
|
1893
|
+
return codeTaskBudgetRecap(task.budgetVersion === 1 ? await inspectHarnessTaskBudget(harness, task.contract.taskId) : undefined);
|
|
1894
|
+
}
|
|
1895
|
+
function codeTaskRecap(state, budgetSummary) {
|
|
1896
|
+
const task = restoredCodeTask(state);
|
|
1897
|
+
if (!task)
|
|
1898
|
+
return "";
|
|
1899
|
+
const raw = state.metadata?.[TASK_ACCEPTANCE_EVIDENCE_KEY];
|
|
1900
|
+
const evidence = raw && typeof raw === "object" ? raw : {};
|
|
1901
|
+
const checks = Array.isArray(evidence.checks) ? evidence.checks : [];
|
|
1902
|
+
return sanitizeTerminalText(`Task: ${task.goal}
|
|
1903
|
+
Constraints: ${task.constraints.join("; ") || "none"}
|
|
1904
|
+
` + `Files: ${task.contract.allowedWritePaths.join(", ")}
|
|
1905
|
+
Agent: ${state.status} · task evidence: ${evidence.status ?? "pending"}
|
|
1906
|
+
` + codeTaskBudgetRecap(budgetSummary ?? state.metadata?.[TASK_BUDGET_KEY]) + task.contract.requiredChecks.map((check) => {
|
|
1907
|
+
const receipt = checks.find((item) => item.checkId === check.id);
|
|
1908
|
+
return `${check.kind === "package-script" ? check.script : check.id}: ${!receipt ? "no receipt" : `exit ${receipt.exitCode} · timeout ${receipt.timedOut} · unchanged ${receipt.unchanged}`}`;
|
|
1909
|
+
}).join(`
|
|
1910
|
+
`) + `
|
|
1911
|
+
Human decision: ${task.keep?.runId === state.runId ? "kept at a reviewed snapshot; recheck current files with /task review" : "pending"}
|
|
1912
|
+
` + `Next: /task review for fresh diff and evidence; /task keep after review, or /task revise <correction>.
|
|
1913
|
+
` + `Native checks run approved repository code on this host. Evidence covers selected files and package.json, not repository-wide isolation.
|
|
1914
|
+
`);
|
|
1915
|
+
}
|
|
1916
|
+
async function freshCodeTaskRecap(harness, state) {
|
|
1917
|
+
const task = restoredCodeTask(state);
|
|
1918
|
+
const budget = task?.budgetVersion === 1 ? await inspectHarnessTaskBudget(harness, task.contract.taskId) : undefined;
|
|
1919
|
+
const recap = codeTaskRecap(state, budget);
|
|
1920
|
+
if (task?.budgetVersion === 1) {
|
|
1921
|
+
const recovery = await inspectHarnessTaskContinuity(harness, task.contract.taskId);
|
|
1922
|
+
if (recovery.reasons.length)
|
|
1923
|
+
return recap.replace(/Next:[^\n]*\n/, `Next: resolve continuity blockers using durable evidence; execution and keep remain blocked.
|
|
1924
|
+
`) + `CONTINUITY BLOCKED: ${recovery.reasons.join(", ")}. Review durable evidence before execution or keep.
|
|
1925
|
+
`;
|
|
1926
|
+
}
|
|
1927
|
+
const evidence = state?.metadata?.[TASK_ACCEPTANCE_EVIDENCE_KEY];
|
|
1928
|
+
if (task && evidence?.contractDigest && evidence.contractDigest !== compileTaskAcceptanceContract(task.contract).digest) {
|
|
1929
|
+
return recap + `REQUIREMENTS CONFLICT: the engine contract differs from this Code brief. Keep is blocked; reconcile requirements before another task turn.
|
|
1930
|
+
`;
|
|
1931
|
+
}
|
|
1932
|
+
if (!task || !state || !evidence?.delivery)
|
|
1933
|
+
return recap;
|
|
1934
|
+
try {
|
|
1935
|
+
const ledger = { schemaVersion: 1, revisions: [{ revision: 1, previousDigest: null, ...compileTaskAcceptanceContract(task.contract) }] };
|
|
1936
|
+
const binding = await nativeTaskSnapshot(harness.workspace, ledger, state.runId);
|
|
1937
|
+
if (binding.snapshotDigest !== evidence.delivery.snapshotDigest)
|
|
1938
|
+
return recap + `STALE EVIDENCE: selected files or package.json changed. Keep is blocked; revise and rerun checks.
|
|
1939
|
+
`;
|
|
1940
|
+
} catch {
|
|
1941
|
+
return recap + `EVIDENCE UNAVAILABLE: current files could not be inspected. Keep is blocked.
|
|
1942
|
+
`;
|
|
1943
|
+
}
|
|
1944
|
+
return recap;
|
|
1945
|
+
}
|
|
1946
|
+
async function keepCodeTask(harness, state, confirm) {
|
|
1947
|
+
if (!Number.isSafeInteger(state.revision))
|
|
1948
|
+
throw new Error("Task has no durable revision; reopen before review.");
|
|
1949
|
+
const task = restoredCodeTask(state);
|
|
1950
|
+
const evidence = state.metadata?.[TASK_ACCEPTANCE_EVIDENCE_KEY];
|
|
1951
|
+
if (!task || state.status !== "completed" || evidence?.status !== "pending_review" || !evidence.delivery)
|
|
1952
|
+
throw new Error("Task is not ready: every declared check must pass after the final edit and the agent must finish.");
|
|
1953
|
+
const validateContinuity = async () => {
|
|
1954
|
+
if (task.budgetVersion !== 1)
|
|
1955
|
+
throw new Error("TASK_CONTINUITY_BUDGET_REQUIRED");
|
|
1956
|
+
const recovery = await inspectHarnessTaskContinuity(harness, task.contract.taskId);
|
|
1957
|
+
const current2 = recovery.runs.at(-1);
|
|
1958
|
+
if (recovery.reasons.length || current2?.runId !== state.runId || current2.revision !== state.revision || current2.checks.some((check) => check.status !== "confirmed"))
|
|
1959
|
+
throw new Error("TASK_CONTINUITY_REVIEW_BLOCKED: reload the current task and reconcile missing or stale evidence.");
|
|
1960
|
+
if (recovery.currentContract?.digest !== compileTaskAcceptanceContract(task.contract).digest)
|
|
1961
|
+
throw new Error("TASK_CONTINUITY_CONTRACT_CONFLICT");
|
|
1962
|
+
};
|
|
1963
|
+
await validateContinuity();
|
|
1964
|
+
if (evidence.contractDigest !== compileTaskAcceptanceContract(task.contract).digest)
|
|
1965
|
+
throw new Error("Task requirements changed outside this Code brief. No keep decision was saved; reconcile the engine contract first.");
|
|
1966
|
+
const ledger = { schemaVersion: 1, revisions: [{ revision: 1, previousDigest: null, ...compileTaskAcceptanceContract(task.contract) }] };
|
|
1967
|
+
const current = await nativeTaskSnapshot(harness.workspace, ledger, state.runId);
|
|
1968
|
+
if (current.snapshotDigest !== evidence.delivery.snapshotDigest)
|
|
1969
|
+
throw new Error("Task evidence is stale: selected files or package.json changed. Revise and rerun checks.");
|
|
1970
|
+
await requireGitVisibleTaskFiles(harness, task.contract.allowedWritePaths);
|
|
1971
|
+
const diff = await consoleWorkspaceDiff(harness.workspace);
|
|
1972
|
+
if (diff.startsWith("Git review unavailable"))
|
|
1973
|
+
throw new Error("Cannot keep without a current Git review.");
|
|
1974
|
+
const budget = task.budgetVersion === 1 ? await inspectHarnessTaskBudget(harness, task.contract.taskId) : undefined;
|
|
1975
|
+
if (!await confirm(codeTaskRecap(state, budget) + diff))
|
|
1976
|
+
return;
|
|
1977
|
+
await validateContinuity();
|
|
1978
|
+
if ((await nativeTaskSnapshot(harness.workspace, ledger, state.runId)).snapshotDigest !== current.snapshotDigest || await consoleWorkspaceDiff(harness.workspace) !== diff)
|
|
1979
|
+
throw new Error("Files or Git review changed during review; no keep decision was saved.");
|
|
1980
|
+
await requireGitVisibleTaskFiles(harness, task.contract.allowedWritePaths);
|
|
1981
|
+
await harness.store.save({ ...state, metadata: { ...state.metadata, [CODE_TASK_KEY]: JSON.parse(JSON.stringify({ ...task, keep: { runId: state.runId, snapshotDigest: current.snapshotDigest, at: Date.now() } })) } }, { expectedRevision: state.revision });
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
// packages/core/src/cli/console/console-run-policy.ts
|
|
1985
|
+
import { z as z3 } from "zod";
|
|
1986
|
+
var key = "zhivexCodeNextRunPolicy";
|
|
1987
|
+
var schema = z3.strictObject({
|
|
1988
|
+
schemaVersion: z3.literal(1),
|
|
1989
|
+
pricingFile: z3.string().min(1).max(4096).optional(),
|
|
1990
|
+
usageLimitUsd: z3.number().finite().positive().optional()
|
|
1991
|
+
});
|
|
1992
|
+
var consoleRunPolicyMetadata = (options) => {
|
|
1993
|
+
const saved = schema.parse({
|
|
1994
|
+
schemaVersion: 1,
|
|
1995
|
+
...options.pricingFile ? { pricingFile: options.pricingFile } : {},
|
|
1996
|
+
...options.usageLimitUsd !== undefined ? { usageLimitUsd: options.usageLimitUsd } : {}
|
|
1997
|
+
});
|
|
1998
|
+
return { [key]: {
|
|
1999
|
+
schemaVersion: saved.schemaVersion,
|
|
2000
|
+
...saved.pricingFile ? { pricingFile: saved.pricingFile } : {},
|
|
2001
|
+
...saved.usageLimitUsd !== undefined ? { usageLimitUsd: saved.usageLimitUsd } : {}
|
|
2002
|
+
} };
|
|
2003
|
+
};
|
|
2004
|
+
var restoreConsoleRunPolicy = (options, state) => {
|
|
2005
|
+
if (state.metadata?.[key] === undefined)
|
|
2006
|
+
return options;
|
|
2007
|
+
const saved = schema.parse(state.metadata[key]);
|
|
2008
|
+
const next = { ...options };
|
|
2009
|
+
delete next.pricingFile;
|
|
2010
|
+
delete next.usageLimitUsd;
|
|
2011
|
+
return {
|
|
2012
|
+
...next,
|
|
2013
|
+
...saved.pricingFile ? { pricingFile: saved.pricingFile } : {},
|
|
2014
|
+
...saved.usageLimitUsd !== undefined ? { usageLimitUsd: saved.usageLimitUsd } : {}
|
|
2015
|
+
};
|
|
2016
|
+
};
|
|
2017
|
+
// packages/core/src/client/continuation.ts
|
|
2018
|
+
function terminalContinuationMessages(messages) {
|
|
2019
|
+
const recorded = new Set(messages.flatMap((message) => message.parts.flatMap((part) => part.type === "tool-result" ? [part.toolResult.toolCallId] : [])));
|
|
2020
|
+
return messages.flatMap((message) => {
|
|
2021
|
+
if (message.role !== "assistant")
|
|
2022
|
+
return [message];
|
|
2023
|
+
const missing = message.parts.filter((part) => part.type === "tool-call" && !recorded.has(part.toolCall.id));
|
|
2024
|
+
if (!missing.length)
|
|
2025
|
+
return [message];
|
|
2026
|
+
return [message, { role: "tool", parts: missing.map((part) => {
|
|
2027
|
+
if (part.type !== "tool-call")
|
|
2028
|
+
throw new Error("INVALID_CONTINUATION");
|
|
2029
|
+
return { type: "tool-result", toolResult: { toolCallId: part.toolCall.id, toolName: part.toolCall.name, isError: true, output: { status: "outcome_unknown", reason: "Previous run ended without a recorded tool result. Inspect current state before any new proposal; do not assume execution or success." } } };
|
|
2030
|
+
}) }];
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
// packages/core/src/cli/console/console-progress.ts
|
|
2034
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2035
|
+
function consoleProgressGuard() {
|
|
2036
|
+
const controller = new AbortController;
|
|
2037
|
+
const calls = new Map;
|
|
2038
|
+
let previous = "", repeated = 0;
|
|
2039
|
+
return {
|
|
2040
|
+
signal: controller.signal,
|
|
2041
|
+
observe(event) {
|
|
2042
|
+
if (event.type === "tool-call") {
|
|
2043
|
+
const { id, ...request } = event.toolCall;
|
|
2044
|
+
calls.set(id, createHash2("sha256").update(JSON.stringify(request)).digest("hex"));
|
|
2045
|
+
}
|
|
2046
|
+
if (event.type !== "tool-result")
|
|
2047
|
+
return;
|
|
2048
|
+
const key2 = calls.get(event.toolResult.toolCallId);
|
|
2049
|
+
calls.delete(event.toolResult.toolCallId);
|
|
2050
|
+
if (!event.toolResult.isError || !key2) {
|
|
2051
|
+
previous = "";
|
|
2052
|
+
repeated = 0;
|
|
2053
|
+
return;
|
|
2054
|
+
}
|
|
2055
|
+
repeated = key2 === previous ? repeated + 1 : 1;
|
|
2056
|
+
previous = key2;
|
|
2057
|
+
if (repeated === 3)
|
|
2058
|
+
controller.abort(new Error("Repeated identical tool failures. Inspect /status and correct the cause before /continue."));
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
// packages/core/src/cli/console/console-run-view.ts
|
|
2064
|
+
class ConsoleRunView {
|
|
2065
|
+
output;
|
|
2066
|
+
state;
|
|
2067
|
+
draft;
|
|
2068
|
+
timer;
|
|
2069
|
+
bottom = 0;
|
|
2070
|
+
started = 0;
|
|
2071
|
+
phase = "Waiting for model response";
|
|
2072
|
+
step = 0;
|
|
2073
|
+
constructor(output, state, draft) {
|
|
2074
|
+
this.output = output;
|
|
2075
|
+
this.state = state;
|
|
2076
|
+
this.draft = draft;
|
|
2077
|
+
}
|
|
2078
|
+
begin(phase = "Waiting for model response") {
|
|
2079
|
+
if (this.timer)
|
|
2080
|
+
return;
|
|
2081
|
+
this.started = Date.now();
|
|
2082
|
+
this.phase = phase;
|
|
2083
|
+
this.step = 0;
|
|
2084
|
+
this.resume();
|
|
2085
|
+
}
|
|
2086
|
+
resume() {
|
|
2087
|
+
if (this.timer || !this.output.isTTY || process.env.TERM === "dumb" || (this.output.rows ?? 24) < 18 || (this.output.columns ?? 80) < 32)
|
|
2088
|
+
return;
|
|
2089
|
+
this.layout();
|
|
2090
|
+
this.output.on("resize", this.resize);
|
|
2091
|
+
this.timer = setInterval(() => this.draw(), 250);
|
|
2092
|
+
this.timer.unref();
|
|
2093
|
+
}
|
|
2094
|
+
lines() {
|
|
2095
|
+
const width = consoleWidth(this.output.columns);
|
|
2096
|
+
return [
|
|
2097
|
+
"─".repeat(width),
|
|
2098
|
+
...consoleStateLines(this.state(), this.output.columns),
|
|
2099
|
+
consoleLabel(`${this.phase} · ${Math.floor((Date.now() - this.started) / 1000)}s · step ${this.step}`, width),
|
|
2100
|
+
consoleLabel(this.draft(), width),
|
|
2101
|
+
consoleLabel("Ctrl+C stop · Enter queues · /activity later", width)
|
|
2102
|
+
];
|
|
2103
|
+
}
|
|
2104
|
+
layout() {
|
|
2105
|
+
this.bottom = Math.max(3, (this.output.rows ?? 24) - this.lines().length);
|
|
2106
|
+
this.output.write(`\x1B[1;${this.bottom}r\x1B[${this.bottom};1H`);
|
|
2107
|
+
this.draw();
|
|
2108
|
+
}
|
|
2109
|
+
resize = () => {
|
|
2110
|
+
if ((this.output.rows ?? 24) < 18 || (this.output.columns ?? 80) < 32) {
|
|
2111
|
+
this.end();
|
|
2112
|
+
return;
|
|
2113
|
+
}
|
|
2114
|
+
this.output.write("\x1B[r");
|
|
2115
|
+
this.layout();
|
|
2116
|
+
};
|
|
2117
|
+
draw() {
|
|
2118
|
+
if (!this.bottom)
|
|
2119
|
+
return;
|
|
2120
|
+
this.output.write("\x1B7" + this.lines().map((line, index) => `\x1B[${this.bottom + index + 1};1H\x1B[2K${line}`).join("") + "\x1B8");
|
|
2121
|
+
}
|
|
2122
|
+
observe(event) {
|
|
2123
|
+
if (event.type === "agent-step-start") {
|
|
2124
|
+
this.step = event.stepIndex + 1;
|
|
2125
|
+
this.phase = "Waiting for model response";
|
|
2126
|
+
} else if (event.type === "text-delta")
|
|
2127
|
+
this.phase = "Receiving response";
|
|
2128
|
+
else if (event.type === "tool-call")
|
|
2129
|
+
this.phase = "Running action";
|
|
2130
|
+
else if (event.type === "agent-compaction")
|
|
2131
|
+
this.phase = "Updating context";
|
|
2132
|
+
else if (event.type === "tool-approval-request" || event.type === "agent-approval-request")
|
|
2133
|
+
this.phase = "Approval pending";
|
|
2134
|
+
else if (event.type === "tool-result")
|
|
2135
|
+
this.phase = event.toolResult.isError ? "Action failed · inspect result above" : "Action returned";
|
|
2136
|
+
this.draw();
|
|
2137
|
+
}
|
|
2138
|
+
end() {
|
|
2139
|
+
if (!this.bottom)
|
|
2140
|
+
return;
|
|
2141
|
+
clearInterval(this.timer);
|
|
2142
|
+
this.timer = undefined;
|
|
2143
|
+
this.output.off("resize", this.resize);
|
|
2144
|
+
this.output.write(`\x1B[r\x1B[${this.bottom + 1};1H\x1B[J`);
|
|
2145
|
+
this.bottom = 0;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
// packages/core/src/cli/console/console-outcome.ts
|
|
2150
|
+
var formatConsoleOutcome = (result, appliedFiles, denied, diff) => {
|
|
2151
|
+
const rejections = result.state?.approvalHistory?.filter((item) => !item.approve) ?? [];
|
|
2152
|
+
const rejectedCalls = new Set(rejections.flatMap((item) => item.toolCallId ? [item.toolCallId] : []));
|
|
2153
|
+
const failed = result.toolResults.filter((item) => item.isError && !rejectedCalls.has(item.toolCallId)).length;
|
|
2154
|
+
const rejected = Math.max(denied, rejections.length);
|
|
2155
|
+
const counts = verificationCounts(result.toolResults);
|
|
2156
|
+
const rejectedText = rejected > 0 ? ` · ${rejected} rejected` : "";
|
|
2157
|
+
const checks = counts.total > 0 ? ` · checks: ${counts.passed} passed, ${counts.failed} failed` : "";
|
|
2158
|
+
const net = ` · net +${diff?.added ?? 0} −${diff?.removed ?? 0}`;
|
|
2159
|
+
const files = appliedFiles === 1 ? "1 file changed" : `${appliedFiles} files changed`;
|
|
2160
|
+
const checkText = counts.total > 0 ? `checks: ${counts.passed} passed, ${counts.failed} failed` : "no checks ran";
|
|
2161
|
+
if (failed > 0) {
|
|
2162
|
+
const actions = failed === 1 ? "1 action failed" : `${failed} actions failed`;
|
|
2163
|
+
return `Finished with errors · ${actions} · ${files}${net} · ${checkText} · /activity${rejectedText}`;
|
|
2164
|
+
}
|
|
2165
|
+
if (result.status === "waiting_approval")
|
|
2166
|
+
return `Waiting for your decision · /pending${net}${rejectedText}`;
|
|
2167
|
+
if (result.status !== "completed")
|
|
2168
|
+
return `Stopped · ${result.status.replace(/_/g, " ")}${net}${checks}${rejectedText}`;
|
|
2169
|
+
return `Done · ${files}${net} · ${checkText}${rejectedText}`;
|
|
2170
|
+
};
|
|
2171
|
+
var formatTurnBanner = (summary) => `
|
|
2172
|
+
${"─".repeat(32)}
|
|
2173
|
+
${summary}
|
|
2174
|
+
|
|
2175
|
+
`;
|
|
2176
|
+
|
|
2177
|
+
// packages/core/src/cli/console/console-recovery.ts
|
|
2178
|
+
var checkpointRecovery = (message) => {
|
|
2179
|
+
if (!/^(Stale patch rejected for |Restore conflicts|Restore mode conflict|Restore requires the reviewed proposal identity|Fork outcome uncertain)/.test(message))
|
|
2180
|
+
return;
|
|
2181
|
+
return `RESTORE BLOCKED · original preconditions retained
|
|
2182
|
+
` + message + `
|
|
2183
|
+
` + `Inspect current files with /diff and the operation with /checkpoint list.
|
|
2184
|
+
` + `For a content conflict, review the checkpoint again before a fresh /checkpoint restore.
|
|
2185
|
+
` + `A partially applied restore or uncertain fork requires manual recovery. /checkpoint retry retains the original digests.
|
|
2186
|
+
`;
|
|
2187
|
+
};
|
|
2188
|
+
|
|
2189
|
+
// packages/core/src/cli/console.ts
|
|
2190
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1141
2191
|
|
|
1142
|
-
// src/cli/session-management.ts
|
|
2192
|
+
// packages/core/src/cli/session-management.ts
|
|
1143
2193
|
var openSessionStoreForConfig = (config) => openCliSessionStore({
|
|
1144
2194
|
workspace: config.workspace,
|
|
1145
2195
|
stateDirectory: config.stateDirectory,
|
|
@@ -1253,10 +2303,10 @@ var updateIndexedSessionRun = async (config, runId, status) => {
|
|
|
1253
2303
|
}
|
|
1254
2304
|
};
|
|
1255
2305
|
|
|
1256
|
-
// src/models/compaction-recommendations.ts
|
|
2306
|
+
// packages/core/src/models/compaction-recommendations.ts
|
|
1257
2307
|
import { recommendAuxiliaryModel } from "@zhivex-ai/core";
|
|
1258
2308
|
|
|
1259
|
-
// src/models/sdk-catalog-adapter.ts
|
|
2309
|
+
// packages/core/src/models/sdk-catalog-adapter.ts
|
|
1260
2310
|
import { createModelCatalog } from "@zhivex-ai/core";
|
|
1261
2311
|
function toSdkCompactionCatalog(catalog, inputTokens) {
|
|
1262
2312
|
const entries = catalog.providers.flatMap((provider) => provider.models.map((model) => {
|
|
@@ -1299,7 +2349,7 @@ function toSdkCompactionCatalog(catalog, inputTokens) {
|
|
|
1299
2349
|
});
|
|
1300
2350
|
}
|
|
1301
2351
|
|
|
1302
|
-
// src/models/compaction-recommendations.ts
|
|
2352
|
+
// packages/core/src/models/compaction-recommendations.ts
|
|
1303
2353
|
function recommendCompactionModels(catalog, request) {
|
|
1304
2354
|
for (const value of [request.inputTokens, request.outputTokens]) {
|
|
1305
2355
|
if (!Number.isSafeInteger(value) || value <= 0)
|
|
@@ -1388,7 +2438,7 @@ function recommendCompactionModels(catalog, request) {
|
|
|
1388
2438
|
};
|
|
1389
2439
|
}
|
|
1390
2440
|
|
|
1391
|
-
// src/cli/console/console-compaction.ts
|
|
2441
|
+
// packages/core/src/cli/console/console-compaction.ts
|
|
1392
2442
|
async function handleConsoleCompaction(command, deps) {
|
|
1393
2443
|
if (command !== "/compaction" && !command.startsWith("/compaction "))
|
|
1394
2444
|
return false;
|
|
@@ -1459,7 +2509,7 @@ async function handleConsoleCompaction(command, deps) {
|
|
|
1459
2509
|
return true;
|
|
1460
2510
|
}
|
|
1461
2511
|
|
|
1462
|
-
// src/cli/console.ts
|
|
2512
|
+
// packages/core/src/cli/console.ts
|
|
1463
2513
|
var chat = async (options) => {
|
|
1464
2514
|
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
1465
2515
|
throw new Error("Chat mode requires an interactive terminal. Use run for automation.");
|
|
@@ -1473,25 +2523,29 @@ var chat = async (options) => {
|
|
|
1473
2523
|
const credentials = { store: new CliCredentials, input: readline };
|
|
1474
2524
|
let credentialsRevision = credentials.store.revision;
|
|
1475
2525
|
let activeController;
|
|
2526
|
+
let runView;
|
|
1476
2527
|
const interrupt = () => {
|
|
1477
2528
|
if (activeController && !activeController.signal.aborted) {
|
|
1478
2529
|
activeController.abort();
|
|
1479
2530
|
process.stderr.write(`
|
|
1480
|
-
|
|
2531
|
+
Cancellation requested locally; waiting for durable state and native cleanup. Provider stop is unconfirmed.
|
|
1481
2532
|
`);
|
|
1482
2533
|
}
|
|
1483
2534
|
};
|
|
1484
2535
|
readline.onInterrupt = interrupt;
|
|
1485
2536
|
process.on("SIGINT", interrupt);
|
|
1486
|
-
const abortable = async (operation) => {
|
|
2537
|
+
const abortable = async (operation, phase) => {
|
|
1487
2538
|
const controller = new AbortController;
|
|
1488
2539
|
activeController = controller;
|
|
1489
2540
|
readline.startBackground();
|
|
2541
|
+
runView?.begin(phase);
|
|
1490
2542
|
try {
|
|
1491
2543
|
return await operation(controller.signal);
|
|
1492
2544
|
} finally {
|
|
2545
|
+
runView?.end();
|
|
1493
2546
|
readline.stopBackground();
|
|
1494
2547
|
activeController = undefined;
|
|
2548
|
+
requestInFlight = false;
|
|
1495
2549
|
}
|
|
1496
2550
|
};
|
|
1497
2551
|
let verbose = false;
|
|
@@ -1508,6 +2562,7 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1508
2562
|
let session = selectedSession ?? await sessionStore.create();
|
|
1509
2563
|
let messages = [];
|
|
1510
2564
|
let retainedTasks = [];
|
|
2565
|
+
let codeTask;
|
|
1511
2566
|
let retainedResponses = [];
|
|
1512
2567
|
let persistenceHarness;
|
|
1513
2568
|
const latestState = async (selected) => {
|
|
@@ -1518,6 +2573,11 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1518
2573
|
const persistence = reusable ? undefined : await openHarnessPersistence(baseConfig);
|
|
1519
2574
|
try {
|
|
1520
2575
|
const state = await (reusable?.store ?? persistence.store).load(latest.runId, baseConfig.scope);
|
|
2576
|
+
if (!state && latest.status === "failed") {
|
|
2577
|
+
process.stderr.write(`Run ${sanitizeTerminalText(latest.runId)} has no durable checkpoint. Inspect the admission error; no effects are retried automatically. Use /new for a fresh conversation.
|
|
2578
|
+
`);
|
|
2579
|
+
return;
|
|
2580
|
+
}
|
|
1521
2581
|
if (!state)
|
|
1522
2582
|
throw new HarnessStateConflictError(`Run ${latest.runId} referenced by session ${selected.sessionId} was not found.`);
|
|
1523
2583
|
return state;
|
|
@@ -1525,9 +2585,34 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1525
2585
|
persistence?.close();
|
|
1526
2586
|
}
|
|
1527
2587
|
};
|
|
2588
|
+
const restorableState = async (selected) => {
|
|
2589
|
+
const latest = await latestState(selected);
|
|
2590
|
+
if (latest || selected.runs.at(-1)?.status !== "failed")
|
|
2591
|
+
return latest;
|
|
2592
|
+
const persistence = await openHarnessPersistence(baseConfig);
|
|
2593
|
+
try {
|
|
2594
|
+
for (const run of selected.runs.slice(0, -1).reverse()) {
|
|
2595
|
+
const state = await persistence.store.load(run.runId, baseConfig.scope);
|
|
2596
|
+
if (state)
|
|
2597
|
+
return restoredCodeTask(state) ? state : undefined;
|
|
2598
|
+
}
|
|
2599
|
+
return;
|
|
2600
|
+
} finally {
|
|
2601
|
+
persistence.close();
|
|
2602
|
+
}
|
|
2603
|
+
};
|
|
2604
|
+
const sessionTaskDraft = async (selected) => {
|
|
2605
|
+
const persistence = await openHarnessPersistence(baseConfig);
|
|
2606
|
+
try {
|
|
2607
|
+
const draft = await readHarnessTaskDraft(persistence.store, baseConfig.scope, selected.sessionId);
|
|
2608
|
+
return draft === undefined ? undefined : restoredCodeTask({ metadata: { [CODE_TASK_KEY]: JSON.parse(JSON.stringify(draft)) } });
|
|
2609
|
+
} finally {
|
|
2610
|
+
persistence.close();
|
|
2611
|
+
}
|
|
2612
|
+
};
|
|
1528
2613
|
let harness;
|
|
1529
2614
|
try {
|
|
1530
|
-
const restored = await
|
|
2615
|
+
const restored = await restorableState(session);
|
|
1531
2616
|
if (restored) {
|
|
1532
2617
|
const persisted = readHarnessResumeConfig(restored);
|
|
1533
2618
|
runtimeOptions = restoreConsoleOptions(runtimeOptions, {
|
|
@@ -1535,13 +2620,20 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1535
2620
|
provider: restored.provider,
|
|
1536
2621
|
model: restored.modelId
|
|
1537
2622
|
});
|
|
2623
|
+
runtimeOptions = restoreConsoleRunPolicy(runtimeOptions, restored);
|
|
1538
2624
|
routes = readHarnessResumeRoutes(restored);
|
|
1539
2625
|
messages = restored.messages;
|
|
1540
2626
|
retainedTasks = taskSources(restored.metadata);
|
|
1541
2627
|
retainedResponses = restored.metadata?.zhivexAssistantResponses ?? [];
|
|
2628
|
+
codeTask = restoredCodeTask(restored);
|
|
1542
2629
|
}
|
|
2630
|
+
codeTask = await sessionTaskDraft(session) ?? codeTask;
|
|
2631
|
+
if (codeTask?.budgetVersion === 1)
|
|
2632
|
+
runtimeOptions = { ...runtimeOptions, unlimitedTokens: false };
|
|
1543
2633
|
harness = (await createConfiguredHarness(runtimeOptions, [], routes, credentials)).harness;
|
|
1544
2634
|
persistenceHarness = harness;
|
|
2635
|
+
if (codeTask)
|
|
2636
|
+
codeTask = await recoverCodeTask(harness, codeTask);
|
|
1545
2637
|
credentialsRevision = credentials.store.revision;
|
|
1546
2638
|
} catch (error) {
|
|
1547
2639
|
process.off("SIGINT", interrupt);
|
|
@@ -1549,36 +2641,116 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1549
2641
|
sessionStore.close();
|
|
1550
2642
|
throw error;
|
|
1551
2643
|
}
|
|
2644
|
+
const autoApprove = await openAutoApproveController(harness.config.workspace, options);
|
|
2645
|
+
readline.onManual(() => autoApprove.setSession("manual"));
|
|
2646
|
+
const limitsExceeded = () => {
|
|
2647
|
+
const cap = runtimeOptions.usageLimitUsd;
|
|
2648
|
+
const spent = displayLedger?.estimatedUsd;
|
|
2649
|
+
if (typeof cap === "number" && typeof spent === "number" && spent >= cap)
|
|
2650
|
+
return true;
|
|
2651
|
+
const budget = harness.config.budget;
|
|
2652
|
+
return budget.unlimitedTokens === false && contextTokens >= budget.maxTotalTokens;
|
|
2653
|
+
};
|
|
2654
|
+
let displayLedger = inspectUsageLedger((await latestState(session))?.metadata?.[USAGE_LEDGER_KEY]);
|
|
2655
|
+
let requestInFlight = false;
|
|
2656
|
+
let contextTokens = estimateMessages(messages);
|
|
2657
|
+
let rejectedDecisions = 0;
|
|
2658
|
+
let consoleIssue;
|
|
2659
|
+
const composerState = () => ({
|
|
2660
|
+
model: `${harness.config.provider}/${harness.config.model}`,
|
|
2661
|
+
reasoning: harness.config.reasoningEffort ?? "default",
|
|
2662
|
+
...session.title ? { title: session.title } : {},
|
|
2663
|
+
status: session.runs.at(-1)?.status === "waiting_approval" ? "Waiting for your decision · /pending" : consoleIssue ?? "ready",
|
|
2664
|
+
attachments: attachments.list().length,
|
|
2665
|
+
automaticApprovals: options.yes === true,
|
|
2666
|
+
...options.approvalMode ? { approvalMode: options.approvalMode } : {},
|
|
2667
|
+
autoApproveMode: autoApprove.policy().mode,
|
|
2668
|
+
...displayLedger ? { runUsage: requestInFlight ? { ...displayLedger, estimatedUsd: null, usageComplete: false } : displayLedger } : {},
|
|
2669
|
+
nextLimitUsd: runtimeOptions.usageLimitUsd ?? null,
|
|
2670
|
+
contextTokens
|
|
2671
|
+
});
|
|
2672
|
+
runView = new ConsoleRunView(process.stdout, composerState, () => readline.backgroundStatus);
|
|
2673
|
+
let reviewRestored = false;
|
|
2674
|
+
const reviewProjectLabel = () => {
|
|
2675
|
+
const home = process.env.HOME;
|
|
2676
|
+
const workspace = harness.config.workspace;
|
|
2677
|
+
const project = home && (workspace === home || workspace.startsWith(`${home}/`)) ? `~${workspace.slice(home.length)}` : workspace;
|
|
2678
|
+
return `${project} · ${harness.config.provider}/${harness.config.model}`;
|
|
2679
|
+
};
|
|
1552
2680
|
const consoleApprovals = async (approvals, context) => {
|
|
2681
|
+
runView.end();
|
|
1553
2682
|
readline.stopBackground();
|
|
2683
|
+
let decisions;
|
|
2684
|
+
let settled = false;
|
|
1554
2685
|
try {
|
|
1555
|
-
|
|
2686
|
+
decisions = await terminalApprovalResolver(options.approvalMode ?? options.yes, (question) => readline.question(question), {
|
|
2687
|
+
select: (title, items) => readline.select(title, items),
|
|
2688
|
+
review: (review, items) => readline.review({ ...review, headerRight: review.headerRight ?? reviewProjectLabel() }, items),
|
|
2689
|
+
workspace: harness.config.workspace,
|
|
2690
|
+
sessionGrants,
|
|
2691
|
+
fileDiff: (approval) => approvalFileDiff(harness.workspace, approval),
|
|
2692
|
+
fileDiffFull: (approval) => approvalFileDiff(harness.workspace, approval, Number.POSITIVE_INFINITY),
|
|
2693
|
+
autoApprove: () => autoApprove.policy(limitsExceeded()),
|
|
2694
|
+
readText: (relative) => readWorkspaceSnapshot(harness.config.workspace, relative),
|
|
2695
|
+
auditRoot: harness.config.workspace,
|
|
2696
|
+
restored: reviewRestored,
|
|
2697
|
+
projectLabel: reviewProjectLabel()
|
|
2698
|
+
}, harness)(approvals, context);
|
|
2699
|
+
settled = true;
|
|
2700
|
+
rejectedDecisions += decisions?.filter((item) => !item.approve).length ?? 0;
|
|
2701
|
+
if (decisions)
|
|
2702
|
+
process.stderr.write(`Approval decisions: ${decisions.filter((item) => item.approve).length} allowed · ${decisions.filter((item) => !item.approve).length} rejected
|
|
2703
|
+
`);
|
|
2704
|
+
return decisions;
|
|
1556
2705
|
} finally {
|
|
1557
|
-
if (activeController && !activeController.signal.aborted)
|
|
2706
|
+
if (activeController && !activeController.signal.aborted) {
|
|
1558
2707
|
readline.startBackground();
|
|
2708
|
+
runView.resume();
|
|
2709
|
+
}
|
|
2710
|
+
if (settled && !decisions)
|
|
2711
|
+
process.stderr.write(`Decided later · nothing applied · /pending to review
|
|
2712
|
+
`);
|
|
1559
2713
|
}
|
|
1560
2714
|
};
|
|
1561
|
-
const createTracker = () => {
|
|
1562
|
-
|
|
2715
|
+
const createTracker = (runId) => {
|
|
2716
|
+
const rendering = createTaskTelemetry();
|
|
2717
|
+
const initialOffset = harness.workspace.mutationAudit().length;
|
|
2718
|
+
rejectedDecisions = 0;
|
|
2719
|
+
displayLedger = inspectUsageLedger(harness.usageLedger?.summary(runId));
|
|
1563
2720
|
const tracker = {
|
|
1564
2721
|
streamedText: false,
|
|
2722
|
+
markdown: new TerminalMarkdown((text) => {
|
|
2723
|
+
rendering.measure("render", () => process.stdout.write(text));
|
|
2724
|
+
if (text)
|
|
2725
|
+
rendering.mark("first-visible-text");
|
|
2726
|
+
}, terminalSupportsColor(Boolean(process.stdout.isTTY)), () => process.stdout.columns || 80),
|
|
1565
2727
|
activityHistory,
|
|
1566
|
-
inputStatus: () => readline.backgroundStatus
|
|
2728
|
+
inputStatus: () => readline.backgroundStatus,
|
|
2729
|
+
consoleView: true,
|
|
2730
|
+
turnDiff: { added: 0, removed: 0 }
|
|
1567
2731
|
};
|
|
1568
|
-
return {
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
2732
|
+
return {
|
|
2733
|
+
tracker,
|
|
2734
|
+
onTaskTelemetry: (snapshot) => {
|
|
2735
|
+
rendering.finish();
|
|
2736
|
+
if (verbose)
|
|
2737
|
+
process.stderr.write(JSON.stringify({ taskTelemetry: snapshot, terminalTelemetry: rendering.snapshot() }) + `
|
|
2738
|
+
`);
|
|
2739
|
+
},
|
|
2740
|
+
outcome: (result) => formatConsoleOutcome(result, harness.workspace.mutationAudit().length - initialOffset, rejectedDecisions, tracker.turnDiff),
|
|
2741
|
+
onEvent: async (event) => {
|
|
2742
|
+
if (event.type === "agent-step-start")
|
|
2743
|
+
requestInFlight = true;
|
|
2744
|
+
if (event.type === "agent-step-finish" || event.type === "agent-run-finish")
|
|
2745
|
+
requestInFlight = false;
|
|
2746
|
+
if (event.type === "agent-step-finish" || event.type === "agent-run-finish")
|
|
2747
|
+
displayLedger = inspectUsageLedger(harness.usageLedger?.summary(runId));
|
|
2748
|
+
if (event.type === "agent-run-finish")
|
|
2749
|
+
contextTokens = estimateMessages(event.state.messages);
|
|
2750
|
+
runView.observe(event);
|
|
2751
|
+
await rendering.measure("render", () => streamSink({ json: false, jsonl: false }, tracker, !verbose)(event));
|
|
1580
2752
|
}
|
|
1581
|
-
}
|
|
2753
|
+
};
|
|
1582
2754
|
};
|
|
1583
2755
|
const refreshSession = async () => {
|
|
1584
2756
|
const refreshed = await sessionStore.get(session.sessionId);
|
|
@@ -1607,6 +2779,8 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1607
2779
|
await harness.close();
|
|
1608
2780
|
harness = created.harness;
|
|
1609
2781
|
persistenceHarness = harness;
|
|
2782
|
+
if (codeTask)
|
|
2783
|
+
codeTask = await recoverCodeTask(harness, codeTask);
|
|
1610
2784
|
credentialsRevision = credentials.store.revision;
|
|
1611
2785
|
runtimeOptions = nextOptions;
|
|
1612
2786
|
routes = new Map(nextRoutes);
|
|
@@ -1617,10 +2791,12 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1617
2791
|
return withTemporaryHarnessProfiles(profiles, (temporaryProfiles) => replaceHarness(normalOptions, normalRoutes, temporaryProfiles), operation);
|
|
1618
2792
|
};
|
|
1619
2793
|
const restoreSession = async (selected) => {
|
|
1620
|
-
const state = await
|
|
2794
|
+
const state = await restorableState(selected);
|
|
1621
2795
|
const persisted = state ? readHarnessResumeConfig(state) : undefined;
|
|
1622
|
-
|
|
2796
|
+
let nextOptions = state ? restoreConsoleRunPolicy(restoreConsoleOptions(runtimeOptions, { ...persistedCliOptions(persisted), provider: state.provider, model: state.modelId }), state) : runtimeOptions;
|
|
1623
2797
|
const nextRoutes = state ? readHarnessResumeRoutes(state) : resolveHarnessModelRoutes();
|
|
2798
|
+
const draft = await sessionTaskDraft(selected);
|
|
2799
|
+
const task = draft ?? restoredCodeTask(state);
|
|
1624
2800
|
await replaceHarness(nextOptions, nextRoutes);
|
|
1625
2801
|
session = selected;
|
|
1626
2802
|
attachments.clear();
|
|
@@ -1629,8 +2805,11 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1629
2805
|
messages = state?.messages ?? [];
|
|
1630
2806
|
retainedTasks = taskSources(state?.metadata);
|
|
1631
2807
|
retainedResponses = state?.metadata?.zhivexAssistantResponses ?? [];
|
|
2808
|
+
codeTask = task ? await recoverCodeTask(harness, task) : undefined;
|
|
2809
|
+
displayLedger = inspectUsageLedger(state?.metadata?.[USAGE_LEDGER_KEY]);
|
|
2810
|
+
contextTokens = estimateMessages(messages);
|
|
1632
2811
|
};
|
|
1633
|
-
const continuePendingApproval = async (approve) => {
|
|
2812
|
+
const continuePendingApproval = async (approve, supplied) => {
|
|
1634
2813
|
const current = await refreshSession();
|
|
1635
2814
|
const state = await latestState(current);
|
|
1636
2815
|
if (!state || state.status !== "waiting_approval" || state.pendingApprovals.length === 0) {
|
|
@@ -1638,50 +2817,39 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1638
2817
|
`);
|
|
1639
2818
|
return;
|
|
1640
2819
|
}
|
|
1641
|
-
const
|
|
2820
|
+
const decisions = supplied ?? (requiresExplicitHostReview(harness) ? approve ? await consoleApprovals(state.pendingApprovals, state) : await terminalApprovalResolver("restricted", undefined, undefined, harness)(state.pendingApprovals, state) : approvalResponses(state.pendingApprovals, approve, approve ? "Approved inline in chat." : "Denied inline in chat."));
|
|
2821
|
+
if (!decisions)
|
|
2822
|
+
return;
|
|
2823
|
+
const { tracker, onEvent, onTaskTelemetry, outcome } = createTracker(state.runId);
|
|
2824
|
+
if (!approve)
|
|
2825
|
+
rejectedDecisions += state.pendingApprovals.length;
|
|
1642
2826
|
session = await sessionStore.updateRun(session.sessionId, state.runId, { status: "running" });
|
|
1643
2827
|
let result;
|
|
1644
2828
|
try {
|
|
1645
|
-
result = await abortable((abortSignal) =>
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
select: (title, items) => readline.select(title, items),
|
|
1655
|
-
workspace: harness.config.workspace,
|
|
1656
|
-
sessionGrants
|
|
1657
|
-
}, harness)(state.pendingApprovals, state);
|
|
1658
|
-
} finally {
|
|
1659
|
-
if (!abortSignal.aborted)
|
|
1660
|
-
readline.startBackground();
|
|
1661
|
-
}
|
|
1662
|
-
if (!approvals)
|
|
1663
|
-
throw new Error("EXPLICIT_REVIEW_REQUIRED");
|
|
1664
|
-
} else {
|
|
1665
|
-
approvals = issueObservedApprovalResponses(harness, state, approvalResponses(state.pendingApprovals, approve, approve ? "Approved inline in chat." : "Denied inline in chat."), "cli-console-command", state.pendingApprovals.map(() => "interactive"));
|
|
1666
|
-
}
|
|
1667
|
-
return runHarness(harness, {
|
|
1668
|
-
state,
|
|
1669
|
-
toolExecution: { ...harnessToolExecution },
|
|
1670
|
-
abortSignal,
|
|
1671
|
-
approvals
|
|
1672
|
-
}, {
|
|
1673
|
-
onEvent,
|
|
1674
|
-
resolveApprovals: consoleApprovals
|
|
1675
|
-
});
|
|
2829
|
+
result = await abortable((abortSignal) => runHarnessTask(harness, {
|
|
2830
|
+
state,
|
|
2831
|
+
toolExecution: { ...harnessToolExecution },
|
|
2832
|
+
abortSignal,
|
|
2833
|
+
approvals: decisions
|
|
2834
|
+
}, {
|
|
2835
|
+
onEvent,
|
|
2836
|
+
onTaskTelemetry,
|
|
2837
|
+
resolveApprovals: consoleApprovals
|
|
1676
2838
|
}));
|
|
1677
2839
|
} catch {
|
|
1678
2840
|
flushToolActivity(tracker);
|
|
1679
2841
|
tracker.markdown?.flush();
|
|
1680
2842
|
const durable = await latestState(await refreshSession());
|
|
2843
|
+
displayLedger = inspectUsageLedger(durable?.metadata?.[USAGE_LEDGER_KEY]);
|
|
2844
|
+
if (durable) {
|
|
2845
|
+
messages = durable.messages;
|
|
2846
|
+
retainedTasks = taskSources(durable.metadata);
|
|
2847
|
+
retainedResponses = durable.metadata?.zhivexAssistantResponses ?? [];
|
|
2848
|
+
}
|
|
1681
2849
|
session = await sessionStore.updateRun(session.sessionId, state.runId, {
|
|
1682
2850
|
status: durable ? sessionStatus(durable.status) : "failed"
|
|
1683
2851
|
});
|
|
1684
|
-
process.stderr.write(approve ? `Run ${state.runId} failed while applying the approval; inspect
|
|
2852
|
+
process.stderr.write(approve ? `Run ${state.runId} failed while applying the approval; inspect /status and /activity before /pending.
|
|
1685
2853
|
` : `Run ${state.runId} ended after the denial.
|
|
1686
2854
|
`);
|
|
1687
2855
|
return;
|
|
@@ -1694,15 +2862,17 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1694
2862
|
process.stdout.write(`
|
|
1695
2863
|
`);
|
|
1696
2864
|
messages = result.messages;
|
|
2865
|
+
displayLedger = inspectUsageLedger(result.state.metadata?.[USAGE_LEDGER_KEY]);
|
|
2866
|
+
contextTokens = estimateMessages(messages);
|
|
2867
|
+
process.stderr.write(formatTurnBanner(outcome(result)));
|
|
2868
|
+
process.stderr.write(await freshCodeTaskRecap(harness, result.state));
|
|
2869
|
+
codeTask = restoredCodeTask(result.state);
|
|
2870
|
+
writeUsageLedger(result.state.metadata);
|
|
1697
2871
|
retainedTasks = taskSources(result.state.metadata);
|
|
1698
2872
|
retainedResponses = result.state.metadata?.zhivexAssistantResponses ?? [];
|
|
1699
2873
|
session = await sessionStore.updateRun(session.sessionId, state.runId, {
|
|
1700
2874
|
status: sessionStatus(result.status)
|
|
1701
2875
|
});
|
|
1702
|
-
if (result.status === "waiting_approval") {
|
|
1703
|
-
process.stderr.write(`Run ${state.runId} requires another decision; use /pending, /approve, or /deny.
|
|
1704
|
-
`);
|
|
1705
|
-
}
|
|
1706
2876
|
};
|
|
1707
2877
|
const statusLine = async () => {
|
|
1708
2878
|
await hasActiveTurn();
|
|
@@ -1710,61 +2880,81 @@ Stopping the active operation; waiting for durable state and cleanup.
|
|
|
1710
2880
|
const latest = current.runs.at(-1);
|
|
1711
2881
|
const failedState = latest?.status === "failed" ? await latestState(current) : undefined;
|
|
1712
2882
|
const routeText = routes.size === 0 ? "default" : [...routes.values()].map((route) => `${route.profile}=${route.provider}:${route.model}`).join(", ");
|
|
1713
|
-
|
|
1714
|
-
|
|
2883
|
+
const cap = runtimeOptions.usageLimitUsd ?? "none";
|
|
2884
|
+
return `session ${current.sessionId} · ${harness.config.provider}/${harness.config.model}` + ` · steps ${harness.config.maxSteps} · approvals ${options.approvalMode ?? (options.yes ? "auto" : "ask")} · ${messages.length} messages · routes ${routeText}` + `${latest ? ` · last ${latest.runId} (${latest.status})` : ""}` + `
|
|
2885
|
+
Credential: ${credentials.store.source(harness.config.provider)}. Account access is not checked until your first task.` + `
|
|
2886
|
+
Context ~${contextTokens} retained tokens. Estimates cover retained messages only; they exclude request instructions and tools. Costs are estimates, not invoices.` + `
|
|
2887
|
+
Next run cap ${cap}.` + (failedState ? `
|
|
2888
|
+
Last failure: ${terminalRunFailure(failedState.error)} (${failedState.currentStep}/${failedState.maxSteps} steps).` : "") + `
|
|
2889
|
+
While working: type a draft, Enter queues the next task, Up recalls the last queued task. Ctrl+C stops and clears the queue.`;
|
|
1715
2890
|
};
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
model: harness.config.model,
|
|
1721
|
-
sessionId: session.sessionId,
|
|
1722
|
-
...session.title ? { sessionTitle: session.title } : {}
|
|
1723
|
-
}, { color: terminalSupportsColor(Boolean(process.stderr.isTTY)), columns: process.stdout.columns ?? 80 }) + `
|
|
1724
|
-
`);
|
|
1725
|
-
process.stderr.write(`Ready · credential: ${credentials.store.source(harness.config.provider)} · account access is not checked until your first task.
|
|
2891
|
+
const writeUsageLedger = (metadata) => {
|
|
2892
|
+
const summary = inspectUsageLedger(metadata?.[USAGE_LEDGER_KEY]);
|
|
2893
|
+
if (typeof summary?.limitUsd === "number" || typeof runtimeOptions.usageLimitUsd === "number") {
|
|
2894
|
+
process.stderr.write(formatUsageLedger(metadata?.[USAGE_LEDGER_KEY]) + `
|
|
1726
2895
|
`);
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
2896
|
+
}
|
|
2897
|
+
};
|
|
2898
|
+
const approvalPolicy = options.approvalMode === "restricted" ? "Restricted mode: additional approvals are denied." : options.yes ? "Automatic approvals are on within workspace policy." : "Zhivex asks before it changes files.";
|
|
2899
|
+
const opening = selectedSession ? await latestState(session) : undefined;
|
|
2900
|
+
const pendingOnRestore = Boolean(selectedSession) && opening?.status === "waiting_approval" && opening.pendingApprovals.length > 0;
|
|
2901
|
+
if (!pendingOnRestore) {
|
|
2902
|
+
process.stderr.write(formatConsoleWelcome({
|
|
2903
|
+
version: HARNESS_VERSION,
|
|
2904
|
+
workspace: harness.config.workspace,
|
|
2905
|
+
provider: harness.config.provider,
|
|
2906
|
+
model: harness.config.model
|
|
2907
|
+
}, {
|
|
2908
|
+
layout: "code",
|
|
2909
|
+
policy: approvalPolicy,
|
|
2910
|
+
restored: Boolean(selectedSession),
|
|
2911
|
+
color: terminalSupportsColor(Boolean(process.stderr.isTTY)),
|
|
2912
|
+
columns: process.stderr.columns || process.stdout.columns || 80,
|
|
2913
|
+
rows: process.stderr.rows || process.stdout.rows || 24,
|
|
2914
|
+
tty: Boolean(process.stderr.isTTY),
|
|
2915
|
+
...process.env.TERM !== undefined ? { term: process.env.TERM } : {}
|
|
2916
|
+
}) + `
|
|
1732
2917
|
`);
|
|
1733
|
-
|
|
2918
|
+
}
|
|
2919
|
+
const showSessionState = async (restored = false) => {
|
|
1734
2920
|
await hasActiveTurn();
|
|
1735
2921
|
const state = await latestState(await refreshSession());
|
|
1736
|
-
if (!state)
|
|
2922
|
+
if (!state) {
|
|
2923
|
+
if (codeTask)
|
|
2924
|
+
process.stderr.write(`Task: ${sanitizeTerminalText(codeTask.goal)}
|
|
2925
|
+
` + await freshCodeTaskBudgetRecap(harness, codeTask));
|
|
1737
2926
|
return;
|
|
1738
|
-
process.stderr.write(`Run ${sanitizeTerminalText(state.runId)} · durable status: ${state.status}
|
|
1739
|
-
`);
|
|
1740
|
-
for (const approval of state.pendingApprovals) {
|
|
1741
|
-
process.stderr.write(`
|
|
1742
|
-
Pending approval:
|
|
1743
|
-
${summarizeApproval(approval)}
|
|
1744
|
-
`);
|
|
1745
2927
|
}
|
|
2928
|
+
if (state.status === "waiting_approval" && state.pendingApprovals.length > 0) {
|
|
2929
|
+
reviewRestored = restored;
|
|
2930
|
+
try {
|
|
2931
|
+
const decisions = await consoleApprovals(state.pendingApprovals, state);
|
|
2932
|
+
if (decisions)
|
|
2933
|
+
await continuePendingApproval(true, decisions);
|
|
2934
|
+
} finally {
|
|
2935
|
+
reviewRestored = false;
|
|
2936
|
+
}
|
|
2937
|
+
return;
|
|
2938
|
+
}
|
|
2939
|
+
process.stderr.write(await freshCodeTaskRecap(harness, state));
|
|
1746
2940
|
};
|
|
1747
2941
|
try {
|
|
1748
|
-
await showSessionState();
|
|
2942
|
+
await showSessionState(Boolean(selectedSession));
|
|
2943
|
+
let commandInProgress = "";
|
|
1749
2944
|
for (;; ) {
|
|
2945
|
+
commandInProgress = "";
|
|
1750
2946
|
try {
|
|
1751
2947
|
const pendingTurn = await hasActiveTurn();
|
|
1752
2948
|
readline.setQueueEnabled(!pendingTurn);
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
reasoning: harness.config.reasoningEffort ?? "default",
|
|
1756
|
-
...session.title ? { title: session.title } : {},
|
|
1757
|
-
status: session.runs.at(-1)?.status === "waiting_approval" ? "approval pending · /pending" : "ready",
|
|
1758
|
-
attachments: attachments.list().length,
|
|
1759
|
-
automaticApprovals: options.yes === true,
|
|
1760
|
-
...options.approvalMode ? { approvalMode: options.approvalMode } : {}
|
|
1761
|
-
});
|
|
2949
|
+
contextTokens = estimateMessages(messages);
|
|
2950
|
+
const submitted = await readline.compose(composerState());
|
|
1762
2951
|
const literalInput = readline.lastSubmissionWasPaste || submitted.includes(`
|
|
1763
2952
|
`);
|
|
1764
2953
|
let prompt = literalInput ? submitted : submitted.trim();
|
|
1765
2954
|
if (!prompt.trim()) {
|
|
1766
2955
|
continue;
|
|
1767
2956
|
}
|
|
2957
|
+
consoleIssue = undefined;
|
|
1768
2958
|
let command = literalInput ? "" : prompt;
|
|
1769
2959
|
if (["/menu", "/provider", "/providers", "/model", "/models"].includes(command)) {
|
|
1770
2960
|
const selection = await navigateConsole(readline, {
|
|
@@ -1793,6 +2983,86 @@ ${summarizeApproval(approval)}
|
|
|
1793
2983
|
continue;
|
|
1794
2984
|
}
|
|
1795
2985
|
}
|
|
2986
|
+
commandInProgress = command;
|
|
2987
|
+
if (command === "/task" || command.startsWith("/task ")) {
|
|
2988
|
+
if (await hasActiveTurn()) {
|
|
2989
|
+
process.stderr.write(`Finish or deny pending work before reviewing or changing task requirements.
|
|
2990
|
+
`);
|
|
2991
|
+
continue;
|
|
2992
|
+
}
|
|
2993
|
+
const argument = command.slice(5).trim();
|
|
2994
|
+
const state = await latestState(await refreshSession());
|
|
2995
|
+
if (argument.startsWith("start ")) {
|
|
2996
|
+
if (codeTask)
|
|
2997
|
+
throw new Error("Use /task revise to correct this task, or /new for a separate task.");
|
|
2998
|
+
codeTask = await prepareCodeTask(harness, JSON.parse(argument.slice(6)));
|
|
2999
|
+
await persistHarnessTaskDraft(harness, session.sessionId, JSON.parse(JSON.stringify(codeTask)));
|
|
3000
|
+
process.stderr.write(`Task draft: ${sanitizeTerminalText(codeTask.goal)}
|
|
3001
|
+
Baseline inspected. Draft and budget authority retained; submit the task request to begin execution.
|
|
3002
|
+
Native checks execute approved code on this host; there is no task sandbox or automatic rollback.
|
|
3003
|
+
`);
|
|
3004
|
+
continue;
|
|
3005
|
+
}
|
|
3006
|
+
if (argument === "keep") {
|
|
3007
|
+
if (!state)
|
|
3008
|
+
throw new Error("Submit a task before keeping its result.");
|
|
3009
|
+
await keepCodeTask(harness, state, async (review) => {
|
|
3010
|
+
process.stdout.write(review);
|
|
3011
|
+
return (await readline.question("Type keep to record your decision for this exact snapshot: ")).trim() === "keep";
|
|
3012
|
+
});
|
|
3013
|
+
codeTask = restoredCodeTask(await latestState(await refreshSession()));
|
|
3014
|
+
if (codeTask)
|
|
3015
|
+
await persistHarnessTaskDraft(harness, session.sessionId, JSON.parse(JSON.stringify(codeTask)));
|
|
3016
|
+
process.stderr.write(`Task decision inspected; /task review shows whether keep was recorded. Commit or export with your usual Git workflow.
|
|
3017
|
+
`);
|
|
3018
|
+
continue;
|
|
3019
|
+
}
|
|
3020
|
+
if (argument.startsWith("revise ")) {
|
|
3021
|
+
if (!codeTask)
|
|
3022
|
+
throw new Error("Start or reopen a guided task first.");
|
|
3023
|
+
const correction = argument.slice(7).trim();
|
|
3024
|
+
if (!correction || correction.length > 500 || codeTask.constraints.length >= 8)
|
|
3025
|
+
throw new Error("A correction must be 1–500 characters; at most 8 constraints are supported.");
|
|
3026
|
+
codeTask = await reviseCodeTask(harness, codeTask, correction);
|
|
3027
|
+
prompt = correction;
|
|
3028
|
+
command = "";
|
|
3029
|
+
} else {
|
|
3030
|
+
if (argument && argument !== "review") {
|
|
3031
|
+
process.stderr.write(`Use /task start {"goal":"...","paths":["..."],"checks":["test"],"constraints":[]} | review | keep | revise <correction>.
|
|
3032
|
+
`);
|
|
3033
|
+
continue;
|
|
3034
|
+
}
|
|
3035
|
+
process.stdout.write(await freshCodeTaskRecap(harness, state) || (codeTask ? `Task draft retained; submit the task request.
|
|
3036
|
+
` + await freshCodeTaskBudgetRecap(harness, codeTask) : `No guided task in this conversation. Use /task start with a goal, exact paths and package checks.
|
|
3037
|
+
`));
|
|
3038
|
+
process.stdout.write(await consoleWorkspaceDiff(harness.workspace));
|
|
3039
|
+
continue;
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
if (await handleConsoleCheckpoint(command, {
|
|
3043
|
+
workspace: harness.workspace,
|
|
3044
|
+
sessions: sessionStore,
|
|
3045
|
+
session: await refreshSession(),
|
|
3046
|
+
input: readline,
|
|
3047
|
+
hasActiveTurn,
|
|
3048
|
+
restoreSession
|
|
3049
|
+
}))
|
|
3050
|
+
continue;
|
|
3051
|
+
if (await handleConsoleBudget(command, {
|
|
3052
|
+
options: runtimeOptions,
|
|
3053
|
+
provider: harness.config.provider,
|
|
3054
|
+
guidedTask: Boolean(codeTask),
|
|
3055
|
+
model: harness.config.model,
|
|
3056
|
+
input: readline,
|
|
3057
|
+
hasActiveTurn,
|
|
3058
|
+
replaceOptions: async (next) => {
|
|
3059
|
+
await replaceHarness(next, routes);
|
|
3060
|
+
if (codeTask)
|
|
3061
|
+
process.stderr.write(`The current task retains its original budget authority across turns, corrections and restarts. This setting applies to future tasks; use /new to start one.
|
|
3062
|
+
`);
|
|
3063
|
+
}
|
|
3064
|
+
}))
|
|
3065
|
+
continue;
|
|
1796
3066
|
if (await handleConsoleCompaction(command, {
|
|
1797
3067
|
config: harness.config,
|
|
1798
3068
|
options: runtimeOptions,
|
|
@@ -1825,9 +3095,64 @@ ${summarizeApproval(approval)}
|
|
|
1825
3095
|
}
|
|
1826
3096
|
await replaceHarness({ ...runtimeOptions, maxSteps: Number(next), unlimitedSteps: false }, routes);
|
|
1827
3097
|
process.stderr.write(`Step limit updated: ${harness.config.maxSteps} for next turns.
|
|
3098
|
+
`);
|
|
3099
|
+
if (codeTask)
|
|
3100
|
+
process.stderr.write(`The current task retains its original budget authority; changing next-turn limits does not replenish it.
|
|
1828
3101
|
`);
|
|
1829
3102
|
continue;
|
|
1830
3103
|
}
|
|
3104
|
+
if (command === "/manual") {
|
|
3105
|
+
autoApprove.setSession("manual");
|
|
3106
|
+
process.stderr.write(`Approvals: manual for this session. The workspace file is unchanged.
|
|
3107
|
+
`);
|
|
3108
|
+
continue;
|
|
3109
|
+
}
|
|
3110
|
+
if (command === "/undo" || command.startsWith("/undo ")) {
|
|
3111
|
+
const requested = command.slice("/undo".length).trim();
|
|
3112
|
+
const entries = await readAutoApprovals(harness.config.workspace);
|
|
3113
|
+
const target = requested || entries.at(-1)?.id;
|
|
3114
|
+
if (!target) {
|
|
3115
|
+
process.stderr.write(`No auto-approved change to undo.
|
|
3116
|
+
`);
|
|
3117
|
+
continue;
|
|
3118
|
+
}
|
|
3119
|
+
const result2 = await revertAutoApproval(harness.config.workspace, target);
|
|
3120
|
+
process.stderr.write(result2.ok ? `Reverted ${result2.paths.join(", ")}.
|
|
3121
|
+
` : `${result2.reason}
|
|
3122
|
+
`);
|
|
3123
|
+
continue;
|
|
3124
|
+
}
|
|
3125
|
+
if (command === "/auto-approve" || command.startsWith("/auto-approve ")) {
|
|
3126
|
+
const requested = command.slice("/auto-approve".length).trim();
|
|
3127
|
+
if (!requested) {
|
|
3128
|
+
const policy = autoApprove.policy();
|
|
3129
|
+
const recent = (await readAutoApprovals(harness.config.workspace)).slice(-5).map(publicAutoApproval);
|
|
3130
|
+
process.stderr.write(`Approvals: ${policy.mode}. Allowlist: ${policy.commandAllowlist.join(", ") || "none"}. m or /manual returns to Manual.
|
|
3131
|
+
`);
|
|
3132
|
+
if (recent.length)
|
|
3133
|
+
process.stderr.write(recent.map((item) => `${item.id} · ${item.paths.join(", ") || item.name} · ${item.undoable ? "undoable" : "not undoable"}`).join(`
|
|
3134
|
+
`) + `
|
|
3135
|
+
`);
|
|
3136
|
+
continue;
|
|
3137
|
+
}
|
|
3138
|
+
const workspaceSave = requested.startsWith("workspace ");
|
|
3139
|
+
const mode = (workspaceSave ? requested.slice("workspace ".length) : requested).trim();
|
|
3140
|
+
if (mode !== "manual" && mode !== "auto-edits" && mode !== "auto-limits") {
|
|
3141
|
+
process.stderr.write(`Use /auto-approve manual|auto-edits|auto-limits, or /auto-approve workspace <mode>.
|
|
3142
|
+
`);
|
|
3143
|
+
continue;
|
|
3144
|
+
}
|
|
3145
|
+
if (workspaceSave) {
|
|
3146
|
+
await autoApprove.saveWorkspace(mode);
|
|
3147
|
+
process.stderr.write(`Approvals: ${mode} saved for this workspace.
|
|
3148
|
+
`);
|
|
3149
|
+
} else {
|
|
3150
|
+
autoApprove.setSession(mode);
|
|
3151
|
+
process.stderr.write(`Approvals: ${mode} for this session. /manual drops back without changing the workspace file.
|
|
3152
|
+
`);
|
|
3153
|
+
}
|
|
3154
|
+
continue;
|
|
3155
|
+
}
|
|
1831
3156
|
if (command === "/approvals" || command.startsWith("/approvals ")) {
|
|
1832
3157
|
if (await hasActiveTurn()) {
|
|
1833
3158
|
process.stderr.write(`Finish or deny pending work before changing approval mode.
|
|
@@ -1854,6 +3179,11 @@ ${summarizeApproval(approval)}
|
|
|
1854
3179
|
continue;
|
|
1855
3180
|
}
|
|
1856
3181
|
if (command === "/connection") {
|
|
3182
|
+
if (codeTask) {
|
|
3183
|
+
process.stderr.write(`Connection tests are unavailable during a guided task because every model call must belong to its budget authority. Use /new for a separate connection test.
|
|
3184
|
+
`);
|
|
3185
|
+
continue;
|
|
3186
|
+
}
|
|
1857
3187
|
if (await hasActiveTurn()) {
|
|
1858
3188
|
process.stderr.write(`Finish or deny pending work before testing the connection.
|
|
1859
3189
|
`);
|
|
@@ -1880,7 +3210,7 @@ ${summarizeApproval(approval)}
|
|
|
1880
3210
|
timeoutMs: 15000,
|
|
1881
3211
|
abortSignal: AbortSignal.any([signal, AbortSignal.timeout(15000)])
|
|
1882
3212
|
});
|
|
1883
|
-
});
|
|
3213
|
+
}, "Testing connection");
|
|
1884
3214
|
process.stderr.write(`Connection verified: the selected model accepted a request. Tool support and other models were not tested.
|
|
1885
3215
|
`);
|
|
1886
3216
|
}
|
|
@@ -1914,15 +3244,23 @@ ${summarizeApproval(approval)}
|
|
|
1914
3244
|
}
|
|
1915
3245
|
if (command === "/usage") {
|
|
1916
3246
|
const state = await latestState(await refreshSession());
|
|
3247
|
+
if (restoredCodeTask(state))
|
|
3248
|
+
process.stdout.write(await freshCodeTaskRecap(harness, state));
|
|
3249
|
+
else if (codeTask)
|
|
3250
|
+
process.stdout.write(await freshCodeTaskBudgetRecap(harness, codeTask));
|
|
1917
3251
|
const ledger = inspectUsageLedger(state?.metadata?.[USAGE_LEDGER_KEY]);
|
|
1918
3252
|
const usage = ledger ? ledger.usageComplete ? {
|
|
1919
3253
|
inputTokens: ledger.inputTokens,
|
|
1920
3254
|
outputTokens: ledger.outputTokens,
|
|
1921
3255
|
totalTokens: ledger.inputTokens + ledger.outputTokens
|
|
1922
3256
|
} : undefined : state?.usage;
|
|
1923
|
-
|
|
3257
|
+
const saved = state ? readHarnessResumeConfig(state) : undefined;
|
|
3258
|
+
process.stdout.write(formatConsoleBudget(saved ? resolveHarnessConfig(saved) : harness.config, usage) + `
|
|
1924
3259
|
`);
|
|
1925
|
-
process.stdout.write(
|
|
3260
|
+
process.stdout.write(formatUsageLedger(ledger) + `
|
|
3261
|
+
`);
|
|
3262
|
+
process.stdout.write(codeTask ? `Next task estimated USD limit: ${runtimeOptions.usageLimitUsd ?? "off"}. Use /budget to change future tasks. This task retains its original policy.
|
|
3263
|
+
` : `Next run estimated USD limit: ${runtimeOptions.usageLimitUsd ?? "off"}. Use /budget to change it. Pending runs retain their original policy.
|
|
1926
3264
|
`);
|
|
1927
3265
|
continue;
|
|
1928
3266
|
}
|
|
@@ -1968,6 +3306,10 @@ ${summarizeApproval(approval)}
|
|
|
1968
3306
|
`);
|
|
1969
3307
|
continue;
|
|
1970
3308
|
}
|
|
3309
|
+
if (command === "/theme" || command.startsWith("/theme ")) {
|
|
3310
|
+
process.stderr.write(terminalThemeCommand(command));
|
|
3311
|
+
continue;
|
|
3312
|
+
}
|
|
1971
3313
|
if (command === "/help" || command === "/help all") {
|
|
1972
3314
|
process.stderr.write(formatConsoleHelp("direct", command === "/help all"));
|
|
1973
3315
|
continue;
|
|
@@ -2006,10 +3348,7 @@ ${summarizeApproval(approval)}
|
|
|
2006
3348
|
continue;
|
|
2007
3349
|
}
|
|
2008
3350
|
if (command === "/diff") {
|
|
2009
|
-
|
|
2010
|
-
const output = `${diff.status.stdout}${diff.diff.stdout}${diff.staged.stdout}`;
|
|
2011
|
-
process.stdout.write(formatConsoleDiff(output, terminalSupportsColor(Boolean(process.stdout.isTTY))) || `No workspace changes.
|
|
2012
|
-
`);
|
|
3351
|
+
process.stdout.write(await consoleWorkspaceDiff(harness.workspace, terminalSupportsColor(Boolean(process.stdout.isTTY))));
|
|
2013
3352
|
continue;
|
|
2014
3353
|
}
|
|
2015
3354
|
if (command === "/compact") {
|
|
@@ -2024,14 +3363,8 @@ ${summarizeApproval(approval)}
|
|
|
2024
3363
|
if (!state || state.status !== "waiting_approval" || state.pendingApprovals.length === 0) {
|
|
2025
3364
|
process.stderr.write(`The current session has no pending approval.
|
|
2026
3365
|
`);
|
|
2027
|
-
} else
|
|
2028
|
-
|
|
2029
|
-
process.stderr.write(`
|
|
2030
|
-
Pending approval:
|
|
2031
|
-
${summarizeApproval(approval)}
|
|
2032
|
-
`);
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
3366
|
+
} else
|
|
3367
|
+
await showSessionState(false);
|
|
2035
3368
|
continue;
|
|
2036
3369
|
}
|
|
2037
3370
|
if (command === "/approve" || command === "/deny") {
|
|
@@ -2168,14 +3501,25 @@ ${summarizeApproval(approval)}
|
|
|
2168
3501
|
continue;
|
|
2169
3502
|
}
|
|
2170
3503
|
await restoreSession(selected);
|
|
2171
|
-
await showSessionState();
|
|
3504
|
+
await showSessionState(true);
|
|
2172
3505
|
const active2 = await hasActiveTurn();
|
|
2173
|
-
process.stderr.write(active2 ? `
|
|
3506
|
+
process.stderr.write(active2?.status === "waiting_approval" ? `Waiting for your decision · /pending
|
|
2174
3507
|
` : `Resumed session ${session.sessionId}.
|
|
2175
3508
|
`);
|
|
2176
3509
|
continue;
|
|
2177
3510
|
}
|
|
2178
3511
|
if (command === "/review" || command.startsWith("/review ")) {
|
|
3512
|
+
if (codeTask) {
|
|
3513
|
+
if (await hasActiveTurn()) {
|
|
3514
|
+
process.stderr.write(`Finish or deny pending work before reviewing the task.
|
|
3515
|
+
`);
|
|
3516
|
+
continue;
|
|
3517
|
+
}
|
|
3518
|
+
process.stdout.write(await freshCodeTaskRecap(harness, await latestState(await refreshSession())) || `Task draft retained; submit the task request.
|
|
3519
|
+
` + await freshCodeTaskBudgetRecap(harness, codeTask));
|
|
3520
|
+
process.stdout.write(await consoleWorkspaceDiff(harness.workspace));
|
|
3521
|
+
continue;
|
|
3522
|
+
}
|
|
2179
3523
|
const reviewPrompt = prompt.slice("/review".length).trim();
|
|
2180
3524
|
if (!reviewPrompt) {
|
|
2181
3525
|
process.stderr.write(`Usage: /review <task>
|
|
@@ -2188,7 +3532,7 @@ ${summarizeApproval(approval)}
|
|
|
2188
3532
|
`);
|
|
2189
3533
|
continue;
|
|
2190
3534
|
}
|
|
2191
|
-
const review = await withTemporaryProfiles(["explorer", "reviewer"], () => abortable((abortSignal) => runHarnessReviewGroup(harness, { prompt: reviewPrompt, scope: harness.config.scope, abortSignal }, ["explorer", "reviewer"])));
|
|
3535
|
+
const review = await withTemporaryProfiles(["explorer", "reviewer"], () => abortable((abortSignal) => runHarnessReviewGroup(harness, { prompt: reviewPrompt, scope: harness.config.scope, abortSignal }, ["explorer", "reviewer"]), "Running review"));
|
|
2192
3536
|
for (const output of review.outputs) {
|
|
2193
3537
|
process.stdout.write(`
|
|
2194
3538
|
[${output.name ?? output.agentId ?? "reviewer"}] ${output.status}
|
|
@@ -2201,7 +3545,8 @@ ${summarizeApproval(approval)}
|
|
|
2201
3545
|
}
|
|
2202
3546
|
const active = await hasActiveTurn();
|
|
2203
3547
|
if (active) {
|
|
2204
|
-
process.stderr.write(
|
|
3548
|
+
process.stderr.write(active.status === "waiting_approval" ? `Waiting for your decision · /pending
|
|
3549
|
+
` : `A run is ${active.status}. Wait before a new turn, or inspect /status.
|
|
2205
3550
|
`);
|
|
2206
3551
|
continue;
|
|
2207
3552
|
}
|
|
@@ -2215,7 +3560,8 @@ ${summarizeApproval(approval)}
|
|
|
2215
3560
|
continue;
|
|
2216
3561
|
}
|
|
2217
3562
|
prompt = "Continue the previous unfinished task using the retained conversation and recorded results. Inspect current state before any action whose outcome is unknown. Do not repeat completed actions. Report remaining blockers if no progress is possible.";
|
|
2218
|
-
process.stderr.write(`Continuing in a new run
|
|
3563
|
+
process.stderr.write(codeTask ? `Continuing in a new run under the same task budget authority; previous results retained.
|
|
3564
|
+
` : `Continuing in a new run with the current limits; previous results retained.
|
|
2219
3565
|
`);
|
|
2220
3566
|
} else if (!literalInput && prompt === "/paste") {
|
|
2221
3567
|
prompt = await readline.multiline();
|
|
@@ -2234,8 +3580,16 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2234
3580
|
continue;
|
|
2235
3581
|
}
|
|
2236
3582
|
readline.rememberPrompt(prompt, literalInput || command === "/paste");
|
|
3583
|
+
if (codeTask && codeTask.budgetVersion !== 1)
|
|
3584
|
+
throw new Error("This legacy task has no established task budget authority. Its saved evidence remains available for review. Use /new and /task start to establish an explicit new task before further model calls.");
|
|
2237
3585
|
prompt = await attachments.prompt(harness.workspace, prompt);
|
|
2238
|
-
|
|
3586
|
+
if (codeTask) {
|
|
3587
|
+
codeTask = { ...codeTask, keep: undefined };
|
|
3588
|
+
prompt = codeTaskPrompt(codeTask, prompt);
|
|
3589
|
+
}
|
|
3590
|
+
if (codeTask)
|
|
3591
|
+
await persistHarnessTaskDraft(harness, session.sessionId, JSON.parse(JSON.stringify(codeTask)));
|
|
3592
|
+
const runId = `run_${randomUUID3()}`;
|
|
2239
3593
|
session = await sessionStore.appendRun(session.sessionId, {
|
|
2240
3594
|
runId,
|
|
2241
3595
|
provider: harness.config.provider,
|
|
@@ -2243,12 +3597,12 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2243
3597
|
status: "created"
|
|
2244
3598
|
});
|
|
2245
3599
|
const turn = session.runs.at(-1);
|
|
2246
|
-
const { tracker, onEvent } = createTracker();
|
|
3600
|
+
const { tracker, onEvent, onTaskTelemetry, outcome } = createTracker(runId);
|
|
2247
3601
|
const progress = consoleProgressGuard();
|
|
2248
3602
|
let markedRunning = false;
|
|
2249
3603
|
let result;
|
|
2250
3604
|
try {
|
|
2251
|
-
result = await abortable((abortSignal) =>
|
|
3605
|
+
result = await abortable((abortSignal) => runHarnessTask(harness, messages.length === 0 ? {
|
|
2252
3606
|
runId,
|
|
2253
3607
|
toolExecution: { ...harnessToolExecution },
|
|
2254
3608
|
abortSignal: AbortSignal.any([abortSignal, progress.signal]),
|
|
@@ -2258,6 +3612,8 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2258
3612
|
scope: harness.config.scope,
|
|
2259
3613
|
metadata: {
|
|
2260
3614
|
...createHarnessResumeMetadata(harness.config, routes),
|
|
3615
|
+
...consoleRunPolicyMetadata(runtimeOptions),
|
|
3616
|
+
...codeTask ? { [CODE_TASK_KEY]: JSON.parse(JSON.stringify(codeTask)) } : {},
|
|
2261
3617
|
[TASK_SOURCE_KEY]: retainedTasks,
|
|
2262
3618
|
zhivexAssistantResponses: retainedResponses,
|
|
2263
3619
|
zhivexCliSession: {
|
|
@@ -2277,6 +3633,8 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2277
3633
|
scope: harness.config.scope,
|
|
2278
3634
|
metadata: {
|
|
2279
3635
|
...createHarnessResumeMetadata(harness.config, routes),
|
|
3636
|
+
...consoleRunPolicyMetadata(runtimeOptions),
|
|
3637
|
+
...codeTask ? { [CODE_TASK_KEY]: JSON.parse(JSON.stringify(codeTask)) } : {},
|
|
2280
3638
|
[TASK_SOURCE_KEY]: retainedTasks,
|
|
2281
3639
|
zhivexAssistantResponses: retainedResponses,
|
|
2282
3640
|
zhivexCliSession: {
|
|
@@ -2287,6 +3645,8 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2287
3645
|
}
|
|
2288
3646
|
}
|
|
2289
3647
|
}, {
|
|
3648
|
+
...codeTask ? { taskAcceptance: codeTask.contract, taskBudgetExisting: true, taskBudgetContinue: true } : {},
|
|
3649
|
+
onTaskTelemetry,
|
|
2290
3650
|
onEvent: async (event) => {
|
|
2291
3651
|
progress.observe(event);
|
|
2292
3652
|
if (!markedRunning && event.type === "agent-run-start") {
|
|
@@ -2296,11 +3656,11 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2296
3656
|
await onEvent(event);
|
|
2297
3657
|
},
|
|
2298
3658
|
resolveApprovals: consoleApprovals
|
|
2299
|
-
}))
|
|
3659
|
+
}));
|
|
2300
3660
|
} catch (error) {
|
|
2301
3661
|
flushToolActivity(tracker);
|
|
2302
3662
|
tracker.markdown?.flush();
|
|
2303
|
-
const durable = await
|
|
3663
|
+
const durable = await harness.store.load(runId, harness.config.scope);
|
|
2304
3664
|
session = await sessionStore.updateRun(session.sessionId, runId, {
|
|
2305
3665
|
status: durable ? sessionStatus(durable.status) : "failed"
|
|
2306
3666
|
});
|
|
@@ -2325,33 +3685,34 @@ ${sanitizeTerminalText(prompt)}
|
|
|
2325
3685
|
retainedTasks = taskSources(result.state.metadata);
|
|
2326
3686
|
retainedResponses = result.state.metadata?.zhivexAssistantResponses ?? [];
|
|
2327
3687
|
attachments.clear();
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
process.stderr.write(
|
|
2331
|
-
|
|
3688
|
+
writeUsageLedger(result.state.metadata);
|
|
3689
|
+
displayLedger = inspectUsageLedger(result.state.metadata?.[USAGE_LEDGER_KEY]);
|
|
3690
|
+
process.stderr.write(formatTurnBanner(outcome(result)));
|
|
3691
|
+
process.stderr.write(await freshCodeTaskRecap(harness, result.state));
|
|
3692
|
+
codeTask = restoredCodeTask(result.state);
|
|
2332
3693
|
session = await sessionStore.updateRun(session.sessionId, runId, {
|
|
2333
3694
|
status: sessionStatus(result.status)
|
|
2334
3695
|
});
|
|
2335
3696
|
if (result.status === "failed" || result.status === "cancelled")
|
|
2336
3697
|
process.stderr.write(`Progress saved. Use /continue to start another run from these results, or /limits to adjust next turns.
|
|
2337
3698
|
`);
|
|
2338
|
-
if (result.status === "waiting_approval") {
|
|
2339
|
-
process.stderr.write(`Run ${result.state.runId} is paused; use /pending, /approve, or /deny here.
|
|
2340
|
-
`);
|
|
2341
|
-
}
|
|
2342
3699
|
} catch (error) {
|
|
2343
3700
|
if (readline.isClosed)
|
|
2344
3701
|
break;
|
|
2345
3702
|
const aborted = error instanceof Error && error.name === "AbortError";
|
|
3703
|
+
const recovery = commandInProgress.startsWith("/checkpoint") ? checkpointRecovery(terminalErrorMessage(error)) : undefined;
|
|
3704
|
+
consoleIssue = recovery ? "restore blocked · /checkpoint list" : aborted ? "interrupted · session retained" : "error · inspect message above";
|
|
2346
3705
|
process.stderr.write(aborted ? `
|
|
2347
3706
|
Input interrupted. Session retained; use /pending to inspect approvals.
|
|
2348
|
-
` : `
|
|
3707
|
+
` : recovery ? `
|
|
3708
|
+
${sanitizeTerminalText(recovery)}` : `
|
|
2349
3709
|
${sanitizeTerminalText(terminalErrorMessage(error))}
|
|
2350
|
-
Session retained; use /status
|
|
3710
|
+
Session retained; use /status and /activity. Inspect /pending before /continue.
|
|
2351
3711
|
`);
|
|
2352
3712
|
}
|
|
2353
3713
|
}
|
|
2354
3714
|
} finally {
|
|
3715
|
+
runView.end();
|
|
2355
3716
|
process.off("SIGINT", interrupt);
|
|
2356
3717
|
readline.close();
|
|
2357
3718
|
await harness.close();
|
|
@@ -2360,12 +3721,13 @@ Session retained; use /status, /pending, or /continue.
|
|
|
2360
3721
|
}
|
|
2361
3722
|
};
|
|
2362
3723
|
|
|
2363
|
-
// src/cli/run-commands.ts
|
|
3724
|
+
// packages/core/src/cli/run-commands.ts
|
|
2364
3725
|
var runOnce = async (options) => {
|
|
2365
3726
|
if (!options.prompt) {
|
|
2366
3727
|
throw new CliUsageError('Missing task. Example: zhivex-harness run "fix the tests".');
|
|
2367
3728
|
}
|
|
2368
3729
|
const { harness, routes } = await createConfiguredHarness(options);
|
|
3730
|
+
const autoApprove = await openAutoApproveController(harness.config.workspace, options);
|
|
2369
3731
|
const tracker = { streamedText: false };
|
|
2370
3732
|
let closeAttempted = false;
|
|
2371
3733
|
try {
|
|
@@ -2377,7 +3739,14 @@ var runOnce = async (options) => {
|
|
|
2377
3739
|
...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
|
|
2378
3740
|
}, {
|
|
2379
3741
|
onEvent: streamSink(options, tracker),
|
|
2380
|
-
resolveApprovals: terminalApprovalResolver(options.approvalMode ?? options.yes, undefined,
|
|
3742
|
+
resolveApprovals: terminalApprovalResolver(options.approvalMode ?? options.yes, undefined, {
|
|
3743
|
+
workspace: harness.config.workspace,
|
|
3744
|
+
fileDiff: (approval) => approvalFileDiff(harness.workspace, approval),
|
|
3745
|
+
fileDiffFull: (approval) => approvalFileDiff(harness.workspace, approval, Number.POSITIVE_INFINITY),
|
|
3746
|
+
autoApprove: () => autoApprove.policy(options.usageLimitUsd === 0),
|
|
3747
|
+
readText: (relative) => readWorkspaceSnapshot(harness.config.workspace, relative),
|
|
3748
|
+
auditRoot: harness.config.workspace
|
|
3749
|
+
}, harness)
|
|
2381
3750
|
}));
|
|
2382
3751
|
closeAttempted = true;
|
|
2383
3752
|
await harness.close();
|
|
@@ -2559,15 +3928,15 @@ ${summarizeApproval(approval)}
|
|
|
2559
3928
|
}
|
|
2560
3929
|
};
|
|
2561
3930
|
|
|
2562
|
-
// src/cli/governance-report.ts
|
|
2563
|
-
import
|
|
3931
|
+
// packages/core/src/cli/governance-report.ts
|
|
3932
|
+
import path3 from "node:path";
|
|
2564
3933
|
async function governanceReportCli(options, config, store) {
|
|
2565
3934
|
let index;
|
|
2566
3935
|
let history;
|
|
2567
3936
|
try {
|
|
2568
3937
|
const envelopes = [];
|
|
2569
3938
|
if (options.reportEnvelopePath) {
|
|
2570
|
-
const data = await readRegularFileNoFollow(
|
|
3939
|
+
const data = await readRegularFileNoFollow(path3.resolve(options.reportEnvelopePath), { label: "Governance envelope", maxBytes: 256 * 1024 });
|
|
2571
3940
|
try {
|
|
2572
3941
|
envelopes.push(JSON.parse(data.contents.toString("utf8")));
|
|
2573
3942
|
} catch {
|
|
@@ -2590,7 +3959,7 @@ async function governanceReportCli(options, config, store) {
|
|
|
2590
3959
|
}
|
|
2591
3960
|
}
|
|
2592
3961
|
|
|
2593
|
-
// src/cli/run-management.ts
|
|
3962
|
+
// packages/core/src/cli/run-management.ts
|
|
2594
3963
|
var printRunsDocument = (document, json) => {
|
|
2595
3964
|
if (json || !document || typeof document !== "object") {
|
|
2596
3965
|
process.stdout.write(`${JSON.stringify(document, null, 2)}
|
|
@@ -2682,12 +4051,12 @@ var manageRuns = async (options) => {
|
|
|
2682
4051
|
}
|
|
2683
4052
|
};
|
|
2684
4053
|
|
|
2685
|
-
// src/cli/changes.ts
|
|
2686
|
-
import
|
|
4054
|
+
// packages/core/src/cli/changes.ts
|
|
4055
|
+
import path4 from "node:path";
|
|
2687
4056
|
var MAX_CHANGE_ENVELOPE_JSON_BYTES = 4 * 1024 * 1024;
|
|
2688
4057
|
var MAX_CHANGE_ARTIFACT_BYTES = 64 * 1024 * 1024;
|
|
2689
4058
|
var readStableCliArtifact = async (filePath, maxBytes) => {
|
|
2690
|
-
const absolute =
|
|
4059
|
+
const absolute = path4.resolve(process.cwd(), filePath);
|
|
2691
4060
|
try {
|
|
2692
4061
|
return (await readRegularFileNoFollow(absolute, {
|
|
2693
4062
|
label: `Change artifact ${filePath}`,
|
|
@@ -2769,7 +4138,7 @@ var manageChanges = async (options) => {
|
|
|
2769
4138
|
process.exitCode = CLI_EXIT_CODES.runtimeError;
|
|
2770
4139
|
};
|
|
2771
4140
|
|
|
2772
|
-
// src/persistence/project-memory-command.ts
|
|
4141
|
+
// packages/core/src/persistence/project-memory-command.ts
|
|
2773
4142
|
async function executeHarnessMemoryCommand(options, command, args, source = "Explicit operator input") {
|
|
2774
4143
|
const counts = {
|
|
2775
4144
|
remember: 1,
|
|
@@ -2838,14 +4207,14 @@ async function executeHarnessMemoryCommand(options, command, args, source = "Exp
|
|
|
2838
4207
|
}
|
|
2839
4208
|
}
|
|
2840
4209
|
|
|
2841
|
-
// src/cli/memory.ts
|
|
4210
|
+
// packages/core/src/cli/memory.ts
|
|
2842
4211
|
async function manageMemory(options) {
|
|
2843
4212
|
const document = await executeHarnessMemoryCommand(resolveHarnessConfig(options), options.memoryCommand, options.memoryArguments ?? [], options.memorySource);
|
|
2844
4213
|
process.stdout.write(`${JSON.stringify(document, null, 2)}
|
|
2845
4214
|
`);
|
|
2846
4215
|
}
|
|
2847
4216
|
|
|
2848
|
-
// src/persistence/state-backup-stream.ts
|
|
4217
|
+
// packages/core/src/persistence/state-backup-stream.ts
|
|
2849
4218
|
var MAGIC = `ZHIVEX-STATE-SEGMENTS-1
|
|
2850
4219
|
`;
|
|
2851
4220
|
var STRING_CHARS = 8192;
|
|
@@ -2874,13 +4243,13 @@ function* canonicalChunks(value) {
|
|
|
2874
4243
|
} else {
|
|
2875
4244
|
yield "{";
|
|
2876
4245
|
let first = true;
|
|
2877
|
-
for (const
|
|
4246
|
+
for (const key2 of Object.keys(value).sort()) {
|
|
2878
4247
|
if (!first)
|
|
2879
4248
|
yield ",";
|
|
2880
4249
|
first = false;
|
|
2881
|
-
yield* canonicalChunks(
|
|
4250
|
+
yield* canonicalChunks(key2);
|
|
2882
4251
|
yield ":";
|
|
2883
|
-
yield* canonicalChunks(value[
|
|
4252
|
+
yield* canonicalChunks(value[key2]);
|
|
2884
4253
|
}
|
|
2885
4254
|
yield "}";
|
|
2886
4255
|
}
|
|
@@ -2898,8 +4267,8 @@ function* tokens(value) {
|
|
|
2898
4267
|
for (const item of value)
|
|
2899
4268
|
yield* tokens(item);
|
|
2900
4269
|
else
|
|
2901
|
-
for (const [
|
|
2902
|
-
yield* tokens(
|
|
4270
|
+
for (const [key2, item] of Object.entries(value)) {
|
|
4271
|
+
yield* tokens(key2);
|
|
2903
4272
|
yield* tokens(item);
|
|
2904
4273
|
}
|
|
2905
4274
|
yield ["end"];
|
|
@@ -3014,151 +4383,151 @@ async function readBackupTransport(source, legacyMaxBytes) {
|
|
|
3014
4383
|
return root;
|
|
3015
4384
|
}
|
|
3016
4385
|
|
|
3017
|
-
// src/persistence/state-backup.ts
|
|
3018
|
-
import { createHash as
|
|
4386
|
+
// packages/core/src/persistence/state-backup.ts
|
|
4387
|
+
import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
|
|
3019
4388
|
import { constants as fsConstants2 } from "node:fs";
|
|
3020
4389
|
import { chmod, link, lstat as lstat2, open, realpath, unlink } from "node:fs/promises";
|
|
3021
|
-
import
|
|
3022
|
-
import { z } from "zod";
|
|
4390
|
+
import path5 from "node:path";
|
|
4391
|
+
import { z as z4 } from "zod";
|
|
3023
4392
|
import { normalizeAgentRunState } from "@zhivex-ai/agents";
|
|
3024
4393
|
import { createSqliteAgentRunStore } from "@zhivex-ai/agents/ops";
|
|
3025
4394
|
|
|
3026
|
-
// src/persistence/sdk-store-identity.ts
|
|
3027
|
-
import { createHash as
|
|
3028
|
-
var sdkCanonicalKey = (kind, scope, value) => `${kind}:v2:${
|
|
4395
|
+
// packages/core/src/persistence/sdk-store-identity.ts
|
|
4396
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
4397
|
+
var sdkCanonicalKey = (kind, scope, value) => `${kind}:v2:${createHash3("sha256").update(JSON.stringify([
|
|
3029
4398
|
JSON.stringify([scope.namespace ?? null, scope.tenantId, scope.userId ?? null]),
|
|
3030
4399
|
value
|
|
3031
4400
|
])).digest("hex")}`;
|
|
3032
4401
|
var sdkLegacyKey = (scope, value) => `${encodeURIComponent(scope.namespace ?? "default")}:${encodeURIComponent(scope.tenantId)}:${encodeURIComponent(scope.userId ?? "*")}:${value}`;
|
|
3033
|
-
var sdkRunKeyMatches = (
|
|
4402
|
+
var sdkRunKeyMatches = (key2, scope, value) => key2 === sdkCanonicalKey("agent-run", scope, value) || key2 === sdkLegacyKey(scope, value);
|
|
3034
4403
|
|
|
3035
|
-
// src/persistence/state-backup.ts
|
|
4404
|
+
// packages/core/src/persistence/state-backup.ts
|
|
3036
4405
|
var HARNESS_STATE_BACKUP_SCHEMA_VERSION = 1;
|
|
3037
4406
|
var HARNESS_STATE_BACKUP_MAX_BYTES = 64 * 1024 * 1024;
|
|
3038
4407
|
var terminalRunStatuses = new Set(["completed", "failed", "cancelled", "timed_out"]);
|
|
3039
4408
|
var terminalSessionStatuses = new Set(["completed", "failed", "cancelled", "timed_out"]);
|
|
3040
|
-
var digestSchema =
|
|
3041
|
-
var bindingKeySchema =
|
|
3042
|
-
var jsonRecordSchema =
|
|
3043
|
-
var durableScopeSchema =
|
|
3044
|
-
tenantId:
|
|
3045
|
-
userId:
|
|
3046
|
-
namespace:
|
|
4409
|
+
var digestSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
|
|
4410
|
+
var bindingKeySchema = z4.string().regex(/^[a-f0-9]{64}$/);
|
|
4411
|
+
var jsonRecordSchema = z4.record(z4.string(), z4.unknown());
|
|
4412
|
+
var durableScopeSchema = z4.object({
|
|
4413
|
+
tenantId: z4.string().min(1),
|
|
4414
|
+
userId: z4.string().min(1).optional(),
|
|
4415
|
+
namespace: z4.string().min(1).optional()
|
|
3047
4416
|
}).strict();
|
|
3048
|
-
var journalEntrySchema =
|
|
3049
|
-
runId:
|
|
4417
|
+
var journalEntrySchema = z4.object({
|
|
4418
|
+
runId: z4.string().min(1),
|
|
3050
4419
|
scope: durableScopeSchema,
|
|
3051
|
-
toolCallId:
|
|
3052
|
-
toolName:
|
|
3053
|
-
status:
|
|
3054
|
-
idempotencyKey:
|
|
3055
|
-
revision:
|
|
3056
|
-
input:
|
|
3057
|
-
output:
|
|
3058
|
-
error:
|
|
3059
|
-
startedAt:
|
|
3060
|
-
completedAt:
|
|
3061
|
-
updatedAt:
|
|
4420
|
+
toolCallId: z4.string().min(1),
|
|
4421
|
+
toolName: z4.string().min(1),
|
|
4422
|
+
status: z4.enum(["pending", "running", "completed", "failed"]),
|
|
4423
|
+
idempotencyKey: z4.string().min(1),
|
|
4424
|
+
revision: z4.number().int().nonnegative(),
|
|
4425
|
+
input: z4.json().optional(),
|
|
4426
|
+
output: z4.json().optional(),
|
|
4427
|
+
error: z4.object({ message: z4.string() }).strict().optional(),
|
|
4428
|
+
startedAt: z4.number().nonnegative().optional(),
|
|
4429
|
+
completedAt: z4.number().nonnegative().optional(),
|
|
4430
|
+
updatedAt: z4.number().nonnegative()
|
|
3062
4431
|
}).passthrough();
|
|
3063
|
-
var runRecordSchema =
|
|
3064
|
-
key:
|
|
4432
|
+
var runRecordSchema = z4.object({
|
|
4433
|
+
key: z4.string().min(1).max(1024),
|
|
3065
4434
|
state: jsonRecordSchema,
|
|
3066
|
-
updatedAt:
|
|
4435
|
+
updatedAt: z4.number().int().nonnegative()
|
|
3067
4436
|
}).strict();
|
|
3068
|
-
var journalRecordSchema =
|
|
3069
|
-
runKey:
|
|
3070
|
-
toolCallId:
|
|
4437
|
+
var journalRecordSchema = z4.object({
|
|
4438
|
+
runKey: z4.string().min(1).max(1024),
|
|
4439
|
+
toolCallId: z4.string().min(1).max(1024),
|
|
3071
4440
|
entry: journalEntrySchema,
|
|
3072
|
-
revision:
|
|
3073
|
-
updatedAt:
|
|
4441
|
+
revision: z4.number().int().nonnegative(),
|
|
4442
|
+
updatedAt: z4.number().int().nonnegative()
|
|
3074
4443
|
}).strict();
|
|
3075
|
-
var idempotencyRecordSchema =
|
|
3076
|
-
key:
|
|
3077
|
-
runKey:
|
|
3078
|
-
updatedAt:
|
|
4444
|
+
var idempotencyRecordSchema = z4.object({
|
|
4445
|
+
key: z4.string().min(1).max(1024),
|
|
4446
|
+
runKey: z4.string().min(1).max(1024),
|
|
4447
|
+
updatedAt: z4.number().int().nonnegative()
|
|
3079
4448
|
}).strict();
|
|
3080
|
-
var parentRecordSchema =
|
|
3081
|
-
runKey:
|
|
3082
|
-
parentRunKey:
|
|
3083
|
-
updatedAt:
|
|
4449
|
+
var parentRecordSchema = z4.object({
|
|
4450
|
+
runKey: z4.string().min(1).max(1024),
|
|
4451
|
+
parentRunKey: z4.string().min(1).max(1024),
|
|
4452
|
+
updatedAt: z4.number().int().nonnegative()
|
|
3084
4453
|
}).strict();
|
|
3085
|
-
var memoryRecordSchema =
|
|
3086
|
-
key:
|
|
3087
|
-
messages:
|
|
3088
|
-
updatedAt:
|
|
4454
|
+
var memoryRecordSchema = z4.object({
|
|
4455
|
+
key: z4.string().min(1).max(1024),
|
|
4456
|
+
messages: z4.array(z4.unknown()),
|
|
4457
|
+
updatedAt: z4.number().int().nonnegative()
|
|
3089
4458
|
}).strict();
|
|
3090
4459
|
var serializedMemory = (entry) => JSON.stringify(entry.key.startsWith("agent-memory:v2:") ? { schemaVersion: 1, memoryKey: entry.key, messages: entry.messages } : entry.messages);
|
|
3091
4460
|
var memoryKeysForRuns = (config, runs) => new Set(runs.flatMap(({ state }) => [...new Set([state.runId, state.agentId].filter((id) => typeof id === "string"))].flatMap((id) => [sdkLegacyKey(config.scope, id), sdkCanonicalKey("agent-memory", config.scope, id)])));
|
|
3092
|
-
var sessionRecordSchema =
|
|
3093
|
-
sessionId:
|
|
4461
|
+
var sessionRecordSchema = z4.object({
|
|
4462
|
+
sessionId: z4.string().min(1).max(260),
|
|
3094
4463
|
workspaceKey: bindingKeySchema,
|
|
3095
4464
|
scopeKey: bindingKeySchema,
|
|
3096
|
-
title:
|
|
3097
|
-
parentSessionId:
|
|
3098
|
-
forkedFromTurnId:
|
|
3099
|
-
revision:
|
|
3100
|
-
activitySequence:
|
|
3101
|
-
createdAt:
|
|
3102
|
-
updatedAt:
|
|
3103
|
-
archivedAt:
|
|
3104
|
-
deletedAt:
|
|
3105
|
-
metadataBytes:
|
|
4465
|
+
title: z4.string().nullable(),
|
|
4466
|
+
parentSessionId: z4.string().nullable(),
|
|
4467
|
+
forkedFromTurnId: z4.string().nullable(),
|
|
4468
|
+
revision: z4.number().int().nonnegative(),
|
|
4469
|
+
activitySequence: z4.number().int().nonnegative(),
|
|
4470
|
+
createdAt: z4.number().int().nonnegative(),
|
|
4471
|
+
updatedAt: z4.number().int().nonnegative(),
|
|
4472
|
+
archivedAt: z4.number().int().nonnegative().nullable(),
|
|
4473
|
+
deletedAt: z4.number().int().nonnegative().nullable(),
|
|
4474
|
+
metadataBytes: z4.number().int().nonnegative()
|
|
3106
4475
|
}).strict();
|
|
3107
|
-
var sessionRunRecordSchema =
|
|
3108
|
-
turnId:
|
|
3109
|
-
sourceTurnId:
|
|
3110
|
-
sessionId:
|
|
3111
|
-
ordinal:
|
|
3112
|
-
runId:
|
|
3113
|
-
provider:
|
|
3114
|
-
model:
|
|
3115
|
-
role:
|
|
3116
|
-
status:
|
|
3117
|
-
createdAt:
|
|
3118
|
-
updatedAt:
|
|
3119
|
-
completedAt:
|
|
3120
|
-
metadataBytes:
|
|
4476
|
+
var sessionRunRecordSchema = z4.object({
|
|
4477
|
+
turnId: z4.string().min(1).max(260),
|
|
4478
|
+
sourceTurnId: z4.string().nullable(),
|
|
4479
|
+
sessionId: z4.string().min(1).max(260),
|
|
4480
|
+
ordinal: z4.number().int().nonnegative(),
|
|
4481
|
+
runId: z4.string().min(1).max(260),
|
|
4482
|
+
provider: z4.string().min(1).max(260),
|
|
4483
|
+
model: z4.string().min(1).max(260),
|
|
4484
|
+
role: z4.string().nullable(),
|
|
4485
|
+
status: z4.string().min(1),
|
|
4486
|
+
createdAt: z4.number().int().nonnegative(),
|
|
4487
|
+
updatedAt: z4.number().int().nonnegative(),
|
|
4488
|
+
completedAt: z4.number().int().nonnegative().nullable(),
|
|
4489
|
+
metadataBytes: z4.number().int().nonnegative()
|
|
3121
4490
|
}).strict();
|
|
3122
|
-
var checkpointRecordSchema =
|
|
3123
|
-
|
|
3124
|
-
id:
|
|
4491
|
+
var checkpointRecordSchema = z4.discriminatedUnion("kind", [
|
|
4492
|
+
z4.object({
|
|
4493
|
+
id: z4.string().uuid(),
|
|
3125
4494
|
workspaceKey: bindingKeySchema,
|
|
3126
4495
|
scopeKey: bindingKeySchema,
|
|
3127
|
-
kind:
|
|
4496
|
+
kind: z4.literal("checkpoint"),
|
|
3128
4497
|
body: workspaceCheckpointSchema
|
|
3129
4498
|
}).strict(),
|
|
3130
|
-
|
|
3131
|
-
id:
|
|
4499
|
+
z4.object({
|
|
4500
|
+
id: z4.string().uuid(),
|
|
3132
4501
|
workspaceKey: bindingKeySchema,
|
|
3133
4502
|
scopeKey: bindingKeySchema,
|
|
3134
|
-
kind:
|
|
4503
|
+
kind: z4.literal("restore"),
|
|
3135
4504
|
body: workspaceRestoreOperationSchema
|
|
3136
4505
|
}).strict()
|
|
3137
4506
|
]);
|
|
3138
4507
|
var checkpointTableSql = "CREATE TABLE IF NOT EXISTS zhivex_workspace_checkpoints (id TEXT PRIMARY KEY, workspace_key TEXT NOT NULL, scope_key TEXT NOT NULL, kind TEXT NOT NULL, body TEXT NOT NULL)";
|
|
3139
|
-
var stateBackupPayloadSchema =
|
|
3140
|
-
schemaVersion:
|
|
3141
|
-
kind:
|
|
3142
|
-
createdAt:
|
|
3143
|
-
binding:
|
|
4508
|
+
var stateBackupPayloadSchema = z4.object({
|
|
4509
|
+
schemaVersion: z4.literal(HARNESS_STATE_BACKUP_SCHEMA_VERSION),
|
|
4510
|
+
kind: z4.literal("state-backup"),
|
|
4511
|
+
createdAt: z4.iso.datetime({ precision: 3 }),
|
|
4512
|
+
binding: z4.object({
|
|
3144
4513
|
workspaceKey: bindingKeySchema,
|
|
3145
4514
|
scopeKey: bindingKeySchema,
|
|
3146
|
-
scopePrefix:
|
|
4515
|
+
scopePrefix: z4.string().min(1).max(1024)
|
|
3147
4516
|
}).strict(),
|
|
3148
|
-
schemas:
|
|
3149
|
-
operations:
|
|
3150
|
-
sessions:
|
|
4517
|
+
schemas: z4.object({
|
|
4518
|
+
operations: z4.literal(HARNESS_OPERATIONS_SCHEMA_VERSION),
|
|
4519
|
+
sessions: z4.literal(HARNESS_SESSION_SCHEMA_VERSION)
|
|
3151
4520
|
}).strict(),
|
|
3152
|
-
records:
|
|
3153
|
-
runs:
|
|
3154
|
-
toolJournal:
|
|
3155
|
-
idempotency:
|
|
3156
|
-
parents:
|
|
3157
|
-
memory:
|
|
3158
|
-
sessions:
|
|
3159
|
-
sessionRuns:
|
|
3160
|
-
workspaceCheckpoints:
|
|
3161
|
-
budgetLedgers:
|
|
4521
|
+
records: z4.object({
|
|
4522
|
+
runs: z4.array(runRecordSchema),
|
|
4523
|
+
toolJournal: z4.array(journalRecordSchema),
|
|
4524
|
+
idempotency: z4.array(idempotencyRecordSchema),
|
|
4525
|
+
parents: z4.array(parentRecordSchema),
|
|
4526
|
+
memory: z4.array(memoryRecordSchema),
|
|
4527
|
+
sessions: z4.array(sessionRecordSchema),
|
|
4528
|
+
sessionRuns: z4.array(sessionRunRecordSchema),
|
|
4529
|
+
workspaceCheckpoints: z4.array(checkpointRecordSchema).max(100).optional(),
|
|
4530
|
+
budgetLedgers: z4.array(runRecordSchema).optional()
|
|
3162
4531
|
}).strict()
|
|
3163
4532
|
}).strict();
|
|
3164
4533
|
var stateBackupBundleSchema = stateBackupPayloadSchema.extend({ checksum: digestSchema }).strict();
|
|
@@ -3167,15 +4536,15 @@ var canonicalJson = (value) => {
|
|
|
3167
4536
|
return JSON.stringify(value);
|
|
3168
4537
|
if (Array.isArray(value))
|
|
3169
4538
|
return `[${value.map(canonicalJson).join(",")}]`;
|
|
3170
|
-
return `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([
|
|
4539
|
+
return `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key2, entry]) => `${JSON.stringify(key2)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
3171
4540
|
};
|
|
3172
4541
|
var checksumPayload = (payload) => {
|
|
3173
|
-
const hash =
|
|
4542
|
+
const hash = createHash4("sha256");
|
|
3174
4543
|
for (const chunk of canonicalChunks(payload))
|
|
3175
4544
|
hash.update(chunk);
|
|
3176
4545
|
return `sha256:${hash.digest("hex")}`;
|
|
3177
4546
|
};
|
|
3178
|
-
var stableKey = (kind, value) =>
|
|
4547
|
+
var stableKey = (kind, value) => createHash4("sha256").update(kind).update("\x00").update(value).digest("hex");
|
|
3179
4548
|
var scopeValue = (config) => `${config.scope.tenantId}\x00${config.scope.userId ?? ""}\x00${config.scope.namespace ?? ""}`;
|
|
3180
4549
|
var scopePrefix = (config) => `${encodeURIComponent(config.scope.namespace ?? "default")}:${encodeURIComponent(config.scope.tenantId)}:${encodeURIComponent(config.scope.userId ?? "*")}:`;
|
|
3181
4550
|
var stateMatchesScope = (config, state) => {
|
|
@@ -3214,7 +4583,7 @@ var validateBudgetLedger = (config, run, identities) => {
|
|
|
3214
4583
|
return identity;
|
|
3215
4584
|
};
|
|
3216
4585
|
var bindingForConfig = async (config) => ({
|
|
3217
|
-
workspaceKey: stableKey("workspace", await realpath(
|
|
4586
|
+
workspaceKey: stableKey("workspace", await realpath(path5.resolve(config.workspace))),
|
|
3218
4587
|
scopeKey: stableKey("scope", scopeValue(config)),
|
|
3219
4588
|
scopePrefix: scopePrefix(config)
|
|
3220
4589
|
});
|
|
@@ -3239,7 +4608,7 @@ var prepareDatabase = async (config) => {
|
|
|
3239
4608
|
scope: config.scope
|
|
3240
4609
|
});
|
|
3241
4610
|
sessions.close();
|
|
3242
|
-
return
|
|
4611
|
+
return path5.join(await realpath(config.stateDirectory), HARNESS_SQLITE_FILE);
|
|
3243
4612
|
};
|
|
3244
4613
|
var locateExistingDatabase = async (config) => {
|
|
3245
4614
|
if (config.storeBackend !== "sqlite") {
|
|
@@ -3254,7 +4623,7 @@ var locateExistingDatabase = async (config) => {
|
|
|
3254
4623
|
return;
|
|
3255
4624
|
throw error;
|
|
3256
4625
|
}
|
|
3257
|
-
const databasePath =
|
|
4626
|
+
const databasePath = path5.join(canonicalStateDirectory, HARNESS_SQLITE_FILE);
|
|
3258
4627
|
try {
|
|
3259
4628
|
const entry = await lstat2(databasePath);
|
|
3260
4629
|
if (entry.isSymbolicLink() || !entry.isFile()) {
|
|
@@ -3381,10 +4750,10 @@ var readPayload = async (config, recordedWorkspace, accessLease) => {
|
|
|
3381
4750
|
const memory = database.query("SELECT memory_key, messages_json, updated_at_ms FROM zhivex_agent_memory ORDER BY memory_key").all().filter((row) => memoryKeys.has(row.memory_key)).map((row) => {
|
|
3382
4751
|
const value = JSON.parse(row.messages_json);
|
|
3383
4752
|
if (row.memory_key.startsWith("agent-memory:v2:")) {
|
|
3384
|
-
const envelope =
|
|
4753
|
+
const envelope = z4.strictObject({ schemaVersion: z4.literal(1), memoryKey: z4.literal(row.memory_key), messages: z4.array(z4.unknown()) }).parse(value);
|
|
3385
4754
|
return { key: row.memory_key, messages: envelope.messages, updatedAt: row.updated_at_ms };
|
|
3386
4755
|
}
|
|
3387
|
-
return { key: row.memory_key, messages:
|
|
4756
|
+
return { key: row.memory_key, messages: z4.array(z4.unknown()).parse(value), updatedAt: row.updated_at_ms };
|
|
3388
4757
|
});
|
|
3389
4758
|
const sessionRows = database.query("SELECT * FROM zhivex_cli_sessions ORDER BY session_id").all().filter((row) => row.workspace_key === binding.workspaceKey && row.scope_key === binding.scopeKey);
|
|
3390
4759
|
const selectedSessionIds = new Set(sessionRows.map((row) => row.session_id));
|
|
@@ -3461,8 +4830,8 @@ var createHarnessStateBackup = async (config) => {
|
|
|
3461
4830
|
return stateBackupBundleSchema.parse({ ...payload, checksum: checksumPayload(payload) });
|
|
3462
4831
|
};
|
|
3463
4832
|
var writePrivateBackup = async (target, contents) => {
|
|
3464
|
-
const requested =
|
|
3465
|
-
const parent =
|
|
4833
|
+
const requested = path5.resolve(target);
|
|
4834
|
+
const parent = path5.dirname(requested);
|
|
3466
4835
|
let parentHandle;
|
|
3467
4836
|
try {
|
|
3468
4837
|
parentHandle = await open(parent, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
|
|
@@ -3475,7 +4844,7 @@ var writePrivateBackup = async (target, contents) => {
|
|
|
3475
4844
|
cause: error
|
|
3476
4845
|
});
|
|
3477
4846
|
}
|
|
3478
|
-
const staged =
|
|
4847
|
+
const staged = path5.join(parent, `.zhivex-state-backup-${randomUUID4()}.tmp`);
|
|
3479
4848
|
let handle;
|
|
3480
4849
|
let published = false;
|
|
3481
4850
|
let stagedExists = false;
|
|
@@ -3531,7 +4900,7 @@ var exportHarnessStateBackup = async (config, target) => {
|
|
|
3531
4900
|
return {
|
|
3532
4901
|
schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
|
|
3533
4902
|
kind: "state-export",
|
|
3534
|
-
path:
|
|
4903
|
+
path: path5.resolve(target),
|
|
3535
4904
|
checksum: bundle.checksum,
|
|
3536
4905
|
counts: Object.fromEntries(Object.entries(bundle.records).map(([name, rows]) => [name, rows?.length ?? 0]))
|
|
3537
4906
|
};
|
|
@@ -3539,7 +4908,7 @@ var exportHarnessStateBackup = async (config, target) => {
|
|
|
3539
4908
|
var readHarnessStateBackup = async (source) => {
|
|
3540
4909
|
let input;
|
|
3541
4910
|
try {
|
|
3542
|
-
input = await readBackupTransport(
|
|
4911
|
+
input = await readBackupTransport(path5.resolve(source), HARNESS_STATE_BACKUP_MAX_BYTES);
|
|
3543
4912
|
} catch (error) {
|
|
3544
4913
|
if (error instanceof SyntaxError) {
|
|
3545
4914
|
throw new HarnessStateConflictError("Harness state backup is not valid JSON.", { cause: error });
|
|
@@ -3669,7 +5038,7 @@ var validateBundleBinding = async (config, bundle) => {
|
|
|
3669
5038
|
const turn = bundle.records.sessionRuns.find((run) => run.turnId === checkpoint.turnId && run.sessionId === checkpoint.sessionId);
|
|
3670
5039
|
if (!turn || !terminalSessionStatuses.has(turn.status))
|
|
3671
5040
|
throw new HarnessStateConflictError("Checkpoint targets a missing terminal turn.");
|
|
3672
|
-
if (new Set(checkpoint.files.map((file) => file.path)).size !== checkpoint.files.length || checkpoint.files.some((file) => `sha256:${
|
|
5041
|
+
if (new Set(checkpoint.files.map((file) => file.path)).size !== checkpoint.files.length || checkpoint.files.some((file) => `sha256:${createHash4("sha256").update(file.content).digest("hex")}` !== file.digest || Buffer.byteLength(file.content) > 65536)) {
|
|
3673
5042
|
throw new HarnessStateConflictError("Checkpoint content identity is invalid.");
|
|
3674
5043
|
}
|
|
3675
5044
|
if (record.kind === "restore") {
|
|
@@ -3904,7 +5273,7 @@ var inspectHarnessState = async (config) => {
|
|
|
3904
5273
|
};
|
|
3905
5274
|
};
|
|
3906
5275
|
|
|
3907
|
-
// src/cli/state.ts
|
|
5276
|
+
// packages/core/src/cli/state.ts
|
|
3908
5277
|
var manageState = async (options) => {
|
|
3909
5278
|
const config = resolveHarnessConfig(options);
|
|
3910
5279
|
let document;
|
|
@@ -3927,7 +5296,7 @@ var manageState = async (options) => {
|
|
|
3927
5296
|
`);
|
|
3928
5297
|
};
|
|
3929
5298
|
|
|
3930
|
-
// src/cli/checkpoints.ts
|
|
5299
|
+
// packages/core/src/cli/checkpoints.ts
|
|
3931
5300
|
async function checkpointCliDocument(options) {
|
|
3932
5301
|
const config = resolveHarnessConfig(options);
|
|
3933
5302
|
const workspace = await Workspace.open(config.workspace);
|
|
@@ -4055,7 +5424,7 @@ async function manageCheckpoints(options) {
|
|
|
4055
5424
|
}
|
|
4056
5425
|
}
|
|
4057
5426
|
|
|
4058
|
-
// src/cli/task-input.ts
|
|
5427
|
+
// packages/core/src/cli/task-input.ts
|
|
4059
5428
|
var MAX_STDIN_TASK_BYTES = 1024 * 1024;
|
|
4060
5429
|
async function readStdinTask(input = process.stdin) {
|
|
4061
5430
|
if (input.isTTY)
|
|
@@ -4080,9 +5449,20 @@ async function readStdinTask(input = process.stdin) {
|
|
|
4080
5449
|
return task;
|
|
4081
5450
|
}
|
|
4082
5451
|
|
|
4083
|
-
// src/cli.ts
|
|
5452
|
+
// packages/core/src/cli.ts
|
|
4084
5453
|
var main = async (argv = process.argv.slice(2)) => {
|
|
5454
|
+
if (["web", "--web"].includes(argv[0] ?? ""))
|
|
5455
|
+
throw new (await import("./arguments-x24bbqvd.js")).CliUsageError("Use Zhivex Electron for the desktop UI or zhx chat --area code for the shared core. The legacy browser has been removed.");
|
|
4085
5456
|
let parsedOptions = parseCliArgs(argv);
|
|
5457
|
+
if (parsedOptions.command === "automations" && parsedOptions.automationCommand === "apply" || parsedOptions.command === "connections" && parsedOptions.managementAction === "configure" || parsedOptions.command === "agents" && parsedOptions.managementAction === "tools") {
|
|
5458
|
+
const text = await readStdinTask();
|
|
5459
|
+
try {
|
|
5460
|
+
parsedOptions.managementInput = JSON.parse(text);
|
|
5461
|
+
} catch {
|
|
5462
|
+
throw new (await import("./arguments-x24bbqvd.js")).CliUsageError("Configuration input must be valid JSON.");
|
|
5463
|
+
}
|
|
5464
|
+
parsedOptions.managementArgs = [];
|
|
5465
|
+
}
|
|
4086
5466
|
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
4087
5467
|
const openConsole = interactive && !parsedOptions.json && !parsedOptions.jsonl && (parsedOptions.command === "chat" || parsedOptions.command === "run" && parsedOptions.implicitCommand && !parsedOptions.prompt);
|
|
4088
5468
|
if (openConsole)
|
|
@@ -4090,8 +5470,15 @@ var main = async (argv = process.argv.slice(2)) => {
|
|
|
4090
5470
|
if ((parsedOptions.command === "run" || parsedOptions.command === "review") && parsedOptions.prompt === "-") {
|
|
4091
5471
|
parsedOptions = { ...parsedOptions, prompt: await readStdinTask() };
|
|
4092
5472
|
}
|
|
5473
|
+
if (!["help", "version"].includes(parsedOptions.command) && (["application", "agents", "connections", "projects", "personal", "automations"].includes(parsedOptions.command) || parsedOptions.applicationDirectory || parsedOptions.applicationArea)) {
|
|
5474
|
+
const { useApplicationCli } = await import("./application-cli-z3f9pvcf.js");
|
|
5475
|
+
const serviceFile = await useApplicationCli(parsedOptions);
|
|
5476
|
+
if (["application", "agents", "connections", "projects", "personal", "automations"].includes(parsedOptions.command))
|
|
5477
|
+
return;
|
|
5478
|
+
parsedOptions = { ...parsedOptions, ...serviceFile ? { serviceFile } : {} };
|
|
5479
|
+
}
|
|
4093
5480
|
if (parsedOptions.serviceFile) {
|
|
4094
|
-
const { runServiceCli } = await import("./service-client-cli-
|
|
5481
|
+
const { runServiceCli } = await import("./service-client-cli-2rzxy5mj.js");
|
|
4095
5482
|
await runServiceCli(parsedOptions, annotateCliStreamError);
|
|
4096
5483
|
return;
|
|
4097
5484
|
}
|
|
@@ -4128,7 +5515,7 @@ var main = async (argv = process.argv.slice(2)) => {
|
|
|
4128
5515
|
await doctor(options);
|
|
4129
5516
|
return;
|
|
4130
5517
|
case "chat":
|
|
4131
|
-
await chat(options);
|
|
5518
|
+
await observeCliPolicy(options, {}, () => chat(options));
|
|
4132
5519
|
return;
|
|
4133
5520
|
case "resume":
|
|
4134
5521
|
await resumeRun(options);
|
|
@@ -4156,7 +5543,7 @@ var main = async (argv = process.argv.slice(2)) => {
|
|
|
4156
5543
|
return;
|
|
4157
5544
|
case "export-audit":
|
|
4158
5545
|
case "verify-audit": {
|
|
4159
|
-
const { auditPackCli } = await import("./audit-pack-
|
|
5546
|
+
const { auditPackCli } = await import("./audit-pack-h44kjkbj.js");
|
|
4160
5547
|
await auditPackCli(options);
|
|
4161
5548
|
return;
|
|
4162
5549
|
}
|