@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
|
@@ -0,0 +1,1744 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CliUsageError
|
|
3
|
+
} from "./index-nkwy5bjr.js";
|
|
4
|
+
import {
|
|
5
|
+
formatApproval,
|
|
6
|
+
formatTerminalEvent,
|
|
7
|
+
formatVerificationSummary,
|
|
8
|
+
isTableSeparator,
|
|
9
|
+
renderTerminalTable,
|
|
10
|
+
resolveTerminalApprovals,
|
|
11
|
+
sanitizeTerminalText,
|
|
12
|
+
tableCells,
|
|
13
|
+
terminalRunFailure,
|
|
14
|
+
terminalSupportsColor
|
|
15
|
+
} from "./index-3rvk23e8.js";
|
|
16
|
+
import {
|
|
17
|
+
decideBatch
|
|
18
|
+
} from "./index-dpbmxnrf.js";
|
|
19
|
+
import {
|
|
20
|
+
resolveHarnessModelRoutes,
|
|
21
|
+
serializeHarnessModelRoutes
|
|
22
|
+
} from "./index-ay26xfxt.js";
|
|
23
|
+
import {
|
|
24
|
+
runResultDocument
|
|
25
|
+
} from "./index-q7qdw883.js";
|
|
26
|
+
import {
|
|
27
|
+
createHarness,
|
|
28
|
+
issueAutomaticApprovalResponses,
|
|
29
|
+
issueExplicitReviewResponses,
|
|
30
|
+
issueObservedApprovalResponses,
|
|
31
|
+
requiresExplicitHostReview
|
|
32
|
+
} from "./index-sx1t6dnd.js";
|
|
33
|
+
import {
|
|
34
|
+
PROVIDERS,
|
|
35
|
+
createProviderModel,
|
|
36
|
+
providerDescriptor,
|
|
37
|
+
resolveHarnessConfig
|
|
38
|
+
} from "./index-fwf274vc.js";
|
|
39
|
+
import {
|
|
40
|
+
azureOpenAIApiVersion,
|
|
41
|
+
azureOpenAIDeployments,
|
|
42
|
+
azureOpenAIEndpoint,
|
|
43
|
+
bedrockConfigured,
|
|
44
|
+
bedrockOpenAIBaseURL,
|
|
45
|
+
bedrockRegion,
|
|
46
|
+
bedrockRuntime,
|
|
47
|
+
vertexConfigured,
|
|
48
|
+
vertexRoute
|
|
49
|
+
} from "./index-ctcwrkrc.js";
|
|
50
|
+
import {
|
|
51
|
+
USAGE_LEDGER_KEY,
|
|
52
|
+
formatUsageLedger,
|
|
53
|
+
usagePricingSchema
|
|
54
|
+
} from "./index-6ehtssyz.js";
|
|
55
|
+
import {
|
|
56
|
+
readRegularFileNoFollow
|
|
57
|
+
} from "./index-h7dcah4p.js";
|
|
58
|
+
import {
|
|
59
|
+
serializeStreamEvent,
|
|
60
|
+
serializeStreamResult
|
|
61
|
+
} from "./index-5jxm2wy5.js";
|
|
62
|
+
import {
|
|
63
|
+
normalizeHarnessError
|
|
64
|
+
} from "./index-xwb691v9.js";
|
|
65
|
+
import {
|
|
66
|
+
__require
|
|
67
|
+
} from "./index-1bx83sw4.js";
|
|
68
|
+
|
|
69
|
+
// packages/core/src/cli/routing.ts
|
|
70
|
+
var resolvedRouting = (options) => {
|
|
71
|
+
return resolveHarnessModelRoutes(options.routes);
|
|
72
|
+
};
|
|
73
|
+
var assertRoutePricingIsSafe = (routes, costBudget) => {
|
|
74
|
+
if (routes.size > 0 && costBudget !== undefined) {
|
|
75
|
+
throw new CliUsageError("Cost budgets cannot be combined with model routes until pricing is configured per role.");
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
var withTemporaryHarnessProfiles = async (profiles, configure, operation) => {
|
|
79
|
+
await configure(profiles);
|
|
80
|
+
try {
|
|
81
|
+
return await operation();
|
|
82
|
+
} finally {
|
|
83
|
+
await configure([]);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// packages/core/src/cli/terminal/tool-activity.ts
|
|
88
|
+
import { createRedactionPolicy } from "@zhivex-ai/agents";
|
|
89
|
+
var failureRedaction = createRedactionPolicy({ includeEmails: true });
|
|
90
|
+
var labels = {
|
|
91
|
+
read_file: "Reading a file",
|
|
92
|
+
read_files: "Reading files",
|
|
93
|
+
read_dependency: "Inspecting a dependency",
|
|
94
|
+
search_files: "Searching files",
|
|
95
|
+
search_many: "Searching the project",
|
|
96
|
+
list_files: "Listing files",
|
|
97
|
+
run_check: "Running checks",
|
|
98
|
+
run_environment_command: "Running a command",
|
|
99
|
+
apply_patch: "Preparing edits",
|
|
100
|
+
apply_reviewed_edits: "Preparing reviewed edits",
|
|
101
|
+
apply_reviewed_replacement: "Preparing a reviewed replacement",
|
|
102
|
+
git_diff: "Reviewing changes"
|
|
103
|
+
};
|
|
104
|
+
var summaries = {
|
|
105
|
+
read_file: "reads",
|
|
106
|
+
read_files: "reads",
|
|
107
|
+
read_dependency: "dependency inspections",
|
|
108
|
+
search_files: "searches",
|
|
109
|
+
search_many: "searches",
|
|
110
|
+
list_files: "listings",
|
|
111
|
+
git_diff: "diffs"
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
class ToolActivity {
|
|
115
|
+
write;
|
|
116
|
+
tty;
|
|
117
|
+
columns;
|
|
118
|
+
inputStatus;
|
|
119
|
+
active = 0;
|
|
120
|
+
visible = false;
|
|
121
|
+
label = "Working";
|
|
122
|
+
completed = new Map;
|
|
123
|
+
started = Date.now();
|
|
124
|
+
runStarted = Date.now();
|
|
125
|
+
timer;
|
|
126
|
+
constructor(write, tty, columns = () => 80, inputStatus = () => "") {
|
|
127
|
+
this.write = write;
|
|
128
|
+
this.tty = tty;
|
|
129
|
+
this.columns = columns;
|
|
130
|
+
this.inputStatus = inputStatus;
|
|
131
|
+
}
|
|
132
|
+
phase(label, _step) {
|
|
133
|
+
this.clear();
|
|
134
|
+
this.label = label;
|
|
135
|
+
this.begin();
|
|
136
|
+
}
|
|
137
|
+
start(name) {
|
|
138
|
+
this.active++;
|
|
139
|
+
this.label = labels[name ?? ""] ?? "Running a tool";
|
|
140
|
+
this.begin();
|
|
141
|
+
}
|
|
142
|
+
finish(name, success = true) {
|
|
143
|
+
this.active = Math.max(0, this.active - 1);
|
|
144
|
+
if (success && !["run_check", "run_environment_command"].includes(name) && !name.startsWith("verify_and_apply_") && !editLabels[name]) {
|
|
145
|
+
const label = summaries[name] ?? "other operations";
|
|
146
|
+
this.completed.set(label, (this.completed.get(label) ?? 0) + 1);
|
|
147
|
+
}
|
|
148
|
+
this.label = this.active ? this.label : "Waiting for model response";
|
|
149
|
+
this.begin();
|
|
150
|
+
}
|
|
151
|
+
begin() {
|
|
152
|
+
this.started = Date.now();
|
|
153
|
+
this.render();
|
|
154
|
+
if (this.tty && !this.timer) {
|
|
155
|
+
this.timer = setInterval(() => this.render(), 250);
|
|
156
|
+
this.timer.unref();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
render() {
|
|
160
|
+
if (!this.tty)
|
|
161
|
+
return;
|
|
162
|
+
const elapsed = Math.floor((Date.now() - this.started) / 1000);
|
|
163
|
+
const done = [...this.completed.values()].reduce((sum, count) => sum + count, 0);
|
|
164
|
+
const total = Math.floor((Date.now() - this.runStarted) / 1000);
|
|
165
|
+
const input = this.inputStatus();
|
|
166
|
+
const timing = `${elapsed}s phase · ${total}s total`;
|
|
167
|
+
const text = input.includes("draft:") || !input.startsWith("0 queued") && input ? `… ${input} · ${timing}` : `… ${this.label} · ${timing}${done ? ` · ${done} tools done` : ""}`;
|
|
168
|
+
this.write(`\r\x1B[2K${Array.from(text).slice(0, Math.max(1, this.columns() - 1)).join("")}`);
|
|
169
|
+
this.visible = true;
|
|
170
|
+
}
|
|
171
|
+
pause() {
|
|
172
|
+
this.clear();
|
|
173
|
+
}
|
|
174
|
+
clear() {
|
|
175
|
+
clearInterval(this.timer);
|
|
176
|
+
this.timer = undefined;
|
|
177
|
+
if (this.visible)
|
|
178
|
+
this.write("\r\x1B[2K");
|
|
179
|
+
this.visible = false;
|
|
180
|
+
}
|
|
181
|
+
flush(options) {
|
|
182
|
+
this.clear();
|
|
183
|
+
if ((options?.summary ?? true) && this.completed.size) {
|
|
184
|
+
const details = [...this.completed].map(([label, count]) => `${label}: ${count}`).join(" · ");
|
|
185
|
+
this.write(`✓ Activity · ${details}
|
|
186
|
+
`);
|
|
187
|
+
}
|
|
188
|
+
this.completed.clear();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
var editLabels = {
|
|
192
|
+
apply_patch: "Edits applied",
|
|
193
|
+
apply_reviewed_edits: "Reviewed edits applied",
|
|
194
|
+
apply_reviewed_replacement: "Reviewed replacement applied",
|
|
195
|
+
apply_environment_patch: "Environment changes imported"
|
|
196
|
+
};
|
|
197
|
+
var SAFE_CAUSE = /^(?:file is binary after edit:|Refusing to write a control byte|Stale patch|Replacement requires|Preview requires|The patch |oldText |Content exceeds|proposalId does not match)/;
|
|
198
|
+
var clipCause = (message) => failureRedaction.redactText(sanitizeTerminalText(message)).replace(/\s+/g, " ").trim().slice(0, 240);
|
|
199
|
+
var compactToolResult = (result, options) => {
|
|
200
|
+
if (!result.isError)
|
|
201
|
+
return options?.includeSuccessEdits && editLabels[result.toolName] ? `✓ ${editLabels[result.toolName]}` : undefined;
|
|
202
|
+
const error = result.error && typeof result.error === "object" ? result.error : {};
|
|
203
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
204
|
+
const binaryRead = /^The file appears to be binary and cannot be read as text(?:: ([^.]+))?/.exec(message);
|
|
205
|
+
let reason = "operation failed. Inspect /activity and retry that file.";
|
|
206
|
+
if (message === "Denied by the operator." || message === "Computer action was denied by the approval policy." || /^Tool ".+" was denied by the approval policy\.$/.test(message))
|
|
207
|
+
reason = "rejected by you";
|
|
208
|
+
else if (binaryRead)
|
|
209
|
+
reason = `file is binary${binaryRead[1] ? `: ${binaryRead[1]}` : ""}. Restore the text version, then read it again.`;
|
|
210
|
+
else if (error.code === "TOOL_INPUT_VALIDATION_ERROR")
|
|
211
|
+
reason = "invalid arguments; the assistant can correct and retry";
|
|
212
|
+
else if (error.code === "ENOENT" || /^ENOENT: /.test(message))
|
|
213
|
+
reason = "file not found; list files to locate the correct path";
|
|
214
|
+
else if (message.startsWith("Dependency package or path was not found in ") || message.startsWith("Dependency path was not found in "))
|
|
215
|
+
reason = "dependency path not found; list the package files before retrying";
|
|
216
|
+
else if (message.startsWith("Dependency ") && message.includes(" is not installed in this workspace's node_modules."))
|
|
217
|
+
reason = "dependency not installed; check the project installation";
|
|
218
|
+
else if (message.startsWith("Dependency paths must be package-relative;"))
|
|
219
|
+
reason = "dependency path is outside the permitted boundary; use a package-relative path";
|
|
220
|
+
else if (/^The path is protected by the harness policy: node_modules(?:\/|$)/.test(message))
|
|
221
|
+
reason = "dependency access requires the dependency tools";
|
|
222
|
+
else if (/^The path is protected by the harness policy: /.test(message))
|
|
223
|
+
reason = "path protected by workspace policy";
|
|
224
|
+
else if (message === "Dependency access only permits package.json and TypeScript declaration files.")
|
|
225
|
+
reason = "dependency file type is not permitted";
|
|
226
|
+
else if (message === "Dependency directory links are not allowed.")
|
|
227
|
+
reason = "dependency link is outside the permitted boundary";
|
|
228
|
+
else if (message.startsWith("Dependency directory changed during inspection."))
|
|
229
|
+
reason = "dependency changed during inspection; retry the read";
|
|
230
|
+
else if (SAFE_CAUSE.test(message)) {
|
|
231
|
+
reason = clipCause(message);
|
|
232
|
+
if (!/not changed|reverted|retry|Read the file/i.test(reason))
|
|
233
|
+
reason += " Read the file again before retrying.";
|
|
234
|
+
}
|
|
235
|
+
const operation = labels[result.toolName] ?? "Tool operation";
|
|
236
|
+
return `✗ ${operation} · ${reason}${editLabels[result.toolName] && error.code === "TOOL_INPUT_VALIDATION_ERROR" ? " · edits not applied" : ""}`;
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// packages/core/src/cli/resume-metadata.ts
|
|
240
|
+
var HARNESS_RESUME_METADATA_KEY = "zhivexHarnessResume";
|
|
241
|
+
var HARNESS_RESUME_METADATA_SCHEMA_VERSION = 1;
|
|
242
|
+
var harnessConfigInput = (config) => ({
|
|
243
|
+
schemaVersion: config.schemaVersion,
|
|
244
|
+
provider: config.provider,
|
|
245
|
+
model: config.model,
|
|
246
|
+
...config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {},
|
|
247
|
+
workspace: config.workspace,
|
|
248
|
+
stateDirectory: config.stateDirectory,
|
|
249
|
+
storeBackend: config.storeBackend,
|
|
250
|
+
tenantId: config.scope.tenantId,
|
|
251
|
+
...config.scope.userId ? { userId: config.scope.userId } : {},
|
|
252
|
+
...config.scope.namespace ? { namespace: config.scope.namespace } : {},
|
|
253
|
+
requireVerifiedDelivery: config.requireVerifiedDelivery,
|
|
254
|
+
maxSteps: config.maxSteps,
|
|
255
|
+
timeoutMs: config.timeoutMs,
|
|
256
|
+
...config.unlimitedDuration === undefined ? {} : { unlimitedDuration: config.unlimitedDuration },
|
|
257
|
+
maxToolCalls: config.budget.maxToolCalls,
|
|
258
|
+
maxToolErrors: config.budget.maxToolErrors,
|
|
259
|
+
...config.budget.unlimitedSteps === undefined ? {} : { unlimitedSteps: config.budget.unlimitedSteps },
|
|
260
|
+
...config.budget.unlimitedToolCalls === undefined ? {} : { unlimitedToolCalls: config.budget.unlimitedToolCalls },
|
|
261
|
+
...config.budget.unlimitedTokens !== undefined ? { unlimitedTokens: config.budget.unlimitedTokens } : {},
|
|
262
|
+
maxInputTokens: config.budget.maxInputTokens,
|
|
263
|
+
maxOutputTokens: config.budget.maxOutputTokens,
|
|
264
|
+
maxTotalTokens: config.budget.maxTotalTokens,
|
|
265
|
+
...config.costBudget ? {
|
|
266
|
+
maxCostUsd: config.costBudget.maxCostUsd,
|
|
267
|
+
inputCostPerMillion: config.costBudget.inputCostPer1kTokens * 1000,
|
|
268
|
+
outputCostPerMillion: config.costBudget.outputCostPer1kTokens * 1000
|
|
269
|
+
} : {},
|
|
270
|
+
compactionMaxMessages: config.compaction.maxMessages,
|
|
271
|
+
compactionMaxEstimatedInputTokens: config.compaction.maxEstimatedInputTokens,
|
|
272
|
+
compactionKeepRecentMessages: config.compaction.keepRecentMessages,
|
|
273
|
+
...config.compaction.model ? { compactionModel: config.compaction.model.model, compactionProvider: config.compaction.model.provider } : {},
|
|
274
|
+
allowedChecks: [...config.allowedChecks],
|
|
275
|
+
requiredCapabilities: [...config.requiredCapabilities],
|
|
276
|
+
subagentProfiles: [...config.orchestration.profiles],
|
|
277
|
+
subagentMaxSteps: config.orchestration.childBudget.maxSteps,
|
|
278
|
+
subagentMaxToolCalls: config.orchestration.childBudget.maxToolCalls,
|
|
279
|
+
subagentMaxToolErrors: config.orchestration.childBudget.maxToolErrors,
|
|
280
|
+
subagentMaxInputTokens: config.orchestration.childBudget.maxInputTokens,
|
|
281
|
+
subagentMaxOutputTokens: config.orchestration.childBudget.maxOutputTokens,
|
|
282
|
+
subagentMaxTotalTokens: config.orchestration.childBudget.maxTotalTokens,
|
|
283
|
+
subagentTimeoutMs: config.orchestration.childTimeoutMs,
|
|
284
|
+
maxParallelReviews: config.orchestration.maxParallelReviews,
|
|
285
|
+
projectContext: config.context.enabled,
|
|
286
|
+
contextConfigPath: config.context.configPath,
|
|
287
|
+
executionBackend: config.execution.backend,
|
|
288
|
+
...config.execution.backend === "oci" ? {
|
|
289
|
+
ociRuntime: config.execution.runtime,
|
|
290
|
+
ociImage: config.execution.image,
|
|
291
|
+
ociAllowedCommands: [...config.execution.allowedCommands],
|
|
292
|
+
ociShellMode: config.execution.shellMode,
|
|
293
|
+
ociMaxProcessRuntimeMs: config.execution.maxProcessRuntimeMs,
|
|
294
|
+
ociMaxProcessOutputBytes: config.execution.maxProcessOutputBytes,
|
|
295
|
+
ociMaxMemoryMb: config.execution.maxMemoryMb,
|
|
296
|
+
ociMaxPids: config.execution.maxPids,
|
|
297
|
+
ociMaxCpus: config.execution.maxCpus,
|
|
298
|
+
ociMaxWorkspaceBytes: config.execution.maxWorkspaceBytes,
|
|
299
|
+
ociMaxFileWriteBytes: config.execution.maxFileWriteBytes,
|
|
300
|
+
ociTmpfsMb: config.execution.tmpfsMb
|
|
301
|
+
} : {},
|
|
302
|
+
...config.mcpConfigPath ? { mcpConfigPath: config.mcpConfigPath } : {}
|
|
303
|
+
});
|
|
304
|
+
var persistedCliOptions = (input) => input ? {
|
|
305
|
+
...input,
|
|
306
|
+
...input.allowedChecks ? { allowedChecks: [...input.allowedChecks] } : {},
|
|
307
|
+
...input.requiredCapabilities ? { requiredCapabilities: [...input.requiredCapabilities] } : {},
|
|
308
|
+
...input.subagentProfiles ? { subagentProfiles: [...input.subagentProfiles] } : {},
|
|
309
|
+
...input.ociAllowedCommands ? { ociAllowedCommands: [...input.ociAllowedCommands] } : {}
|
|
310
|
+
} : {};
|
|
311
|
+
var createHarnessResumeMetadata = (config, routes) => ({
|
|
312
|
+
[HARNESS_RESUME_METADATA_KEY]: JSON.parse(JSON.stringify({
|
|
313
|
+
schemaVersion: HARNESS_RESUME_METADATA_SCHEMA_VERSION,
|
|
314
|
+
config,
|
|
315
|
+
...routes && routes.size > 0 ? { routes: serializeHarnessModelRoutes(routes) } : {}
|
|
316
|
+
}))
|
|
317
|
+
});
|
|
318
|
+
var readHarnessResumeDocument = (state) => {
|
|
319
|
+
const value = state.metadata?.[HARNESS_RESUME_METADATA_KEY];
|
|
320
|
+
if (value === undefined)
|
|
321
|
+
return;
|
|
322
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
323
|
+
throw new Error("Persisted harness resume metadata is invalid.");
|
|
324
|
+
}
|
|
325
|
+
const document = value;
|
|
326
|
+
if (document.schemaVersion !== HARNESS_RESUME_METADATA_SCHEMA_VERSION || !document.config || typeof document.config !== "object" || Array.isArray(document.config)) {
|
|
327
|
+
throw new Error("Persisted harness resume metadata is invalid.");
|
|
328
|
+
}
|
|
329
|
+
return document;
|
|
330
|
+
};
|
|
331
|
+
var readHarnessResumeConfig = (state) => {
|
|
332
|
+
const document = readHarnessResumeDocument(state);
|
|
333
|
+
if (!document)
|
|
334
|
+
return;
|
|
335
|
+
try {
|
|
336
|
+
return harnessConfigInput(document.config);
|
|
337
|
+
} catch {
|
|
338
|
+
throw new Error("Persisted harness resume metadata is invalid.");
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
var readHarnessResumeRoutes = (state) => {
|
|
342
|
+
const document = readHarnessResumeDocument(state);
|
|
343
|
+
if (!document?.routes)
|
|
344
|
+
return resolveHarnessModelRoutes();
|
|
345
|
+
if (typeof document.routes !== "object" || Array.isArray(document.routes)) {
|
|
346
|
+
throw new Error("Persisted harness routing metadata is invalid.");
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
const values = Object.entries(document.routes).map(([profile, target]) => {
|
|
350
|
+
if (!target || typeof target !== "object" || Array.isArray(target))
|
|
351
|
+
throw new Error("invalid");
|
|
352
|
+
const route = target;
|
|
353
|
+
if (typeof route.provider !== "string" || typeof route.model !== "string")
|
|
354
|
+
throw new Error("invalid");
|
|
355
|
+
return `${profile}=${route.provider}:${route.model}`;
|
|
356
|
+
});
|
|
357
|
+
return resolveHarnessModelRoutes(values);
|
|
358
|
+
} catch {
|
|
359
|
+
throw new Error("Persisted harness routing metadata is invalid.");
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
var shellArgument = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
363
|
+
var resumeCommand = (runId, config, approve = true) => [
|
|
364
|
+
"zhivex-harness",
|
|
365
|
+
"resume",
|
|
366
|
+
shellArgument(runId),
|
|
367
|
+
approve ? "--approve" : "--deny",
|
|
368
|
+
"--workspace",
|
|
369
|
+
shellArgument(config.workspace),
|
|
370
|
+
"--state-dir",
|
|
371
|
+
shellArgument(config.stateDirectory),
|
|
372
|
+
"--store",
|
|
373
|
+
config.storeBackend,
|
|
374
|
+
"--tenant",
|
|
375
|
+
shellArgument(config.scope.tenantId),
|
|
376
|
+
...config.scope.userId ? ["--user", shellArgument(config.scope.userId)] : [],
|
|
377
|
+
...config.scope.namespace ? ["--namespace", shellArgument(config.scope.namespace)] : []
|
|
378
|
+
].join(" ");
|
|
379
|
+
|
|
380
|
+
// packages/core/src/cli/terminal/activity-stream.ts
|
|
381
|
+
import { createRedactionPolicy as createRedactionPolicy2 } from "@zhivex-ai/agents";
|
|
382
|
+
var redaction = createRedactionPolicy2({ includeEmails: true });
|
|
383
|
+
var SECRETISH = /password|secret|api[_-]?key|token|authorization|bearer/i;
|
|
384
|
+
var EDIT_TOOLS = new Set(["apply_patch", "apply_reviewed_edits", "apply_reviewed_replacement"]);
|
|
385
|
+
var EXPLORE_TOOLS = new Set(["read_file", "read_files", "search_files", "search_many", "list_files", "git_diff", "read_dependency"]);
|
|
386
|
+
var CHECK_TOOLS = new Set(["run_check", "run_environment_command", "run_environment_shell", "run_environment_batch"]);
|
|
387
|
+
var KNOWN_TOOLS = new Set([...EDIT_TOOLS, ...EXPLORE_TOOLS, ...CHECK_TOOLS, "propose_edits", "move_file", "quarantine_file", "restore_file", "apply_environment_patch"]);
|
|
388
|
+
var isCheck = (name) => CHECK_TOOLS.has(name) || name.startsWith("verify_and_apply_");
|
|
389
|
+
var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
390
|
+
var safe = (value, limit = 160) => redaction.redactText(sanitizeTerminalText(value)).replace(/[\r\n\t]/g, " ").trim().slice(0, limit);
|
|
391
|
+
var clipLive = (line) => {
|
|
392
|
+
const clean = line.replace(/[\r\n]/g, " ");
|
|
393
|
+
return clean.length > 240 ? `${clean.slice(0, 239)}…` : clean;
|
|
394
|
+
};
|
|
395
|
+
var emission = (line, children = []) => ({
|
|
396
|
+
live: clipLive(line),
|
|
397
|
+
history: [clipLive(line), ...children.map((child) => child.slice(0, 500))]
|
|
398
|
+
});
|
|
399
|
+
var lineCount = (text) => {
|
|
400
|
+
if (text.length === 0)
|
|
401
|
+
return 0;
|
|
402
|
+
const parts = text.split(`
|
|
403
|
+
`);
|
|
404
|
+
if (text.endsWith(`
|
|
405
|
+
`))
|
|
406
|
+
parts.pop();
|
|
407
|
+
return parts.length;
|
|
408
|
+
};
|
|
409
|
+
var lineRange = (start, end) => {
|
|
410
|
+
const from = typeof start === "number" && Number.isSafeInteger(start) ? start : undefined;
|
|
411
|
+
const to = typeof end === "number" && Number.isSafeInteger(end) ? end : undefined;
|
|
412
|
+
if (from !== undefined && to !== undefined)
|
|
413
|
+
return ` L${from}-${to}`;
|
|
414
|
+
if (from !== undefined && from !== 1)
|
|
415
|
+
return ` L${from}`;
|
|
416
|
+
return "";
|
|
417
|
+
};
|
|
418
|
+
var baseName = (path) => path.split(/[/\\]/).pop() || path;
|
|
419
|
+
var editPath = (name, input) => {
|
|
420
|
+
const record = asRecord(input);
|
|
421
|
+
if (!record)
|
|
422
|
+
return "";
|
|
423
|
+
if (name === "apply_reviewed_replacement" && typeof record.path === "string")
|
|
424
|
+
return record.path;
|
|
425
|
+
if (!Array.isArray(record.changes))
|
|
426
|
+
return typeof record.path === "string" ? record.path : "";
|
|
427
|
+
const paths = record.changes.map((change) => asRecord(change)?.path).filter((path) => typeof path === "string");
|
|
428
|
+
if (paths.length === 1)
|
|
429
|
+
return paths[0] ?? "";
|
|
430
|
+
if (paths.length > 1)
|
|
431
|
+
return paths.join(`
|
|
432
|
+
`);
|
|
433
|
+
return "";
|
|
434
|
+
};
|
|
435
|
+
var editLabel = (path) => path.includes(`
|
|
436
|
+
`) ? `${path.split(`
|
|
437
|
+
`).length} files` : safe(baseName(path), 80);
|
|
438
|
+
var statedIntent = (input) => {
|
|
439
|
+
const record = asRecord(input);
|
|
440
|
+
if (!record)
|
|
441
|
+
return;
|
|
442
|
+
for (const key of ["intent", "reason", "summary", "description"]) {
|
|
443
|
+
const value = record[key];
|
|
444
|
+
if (typeof value === "string" && value.trim() && !SECRETISH.test(value))
|
|
445
|
+
return safe(value.trim().split(`
|
|
446
|
+
`)[0] ?? "", 60);
|
|
447
|
+
}
|
|
448
|
+
return;
|
|
449
|
+
};
|
|
450
|
+
var inferredIntent = (oldText, newText) => {
|
|
451
|
+
const previous = new Set(oldText.split(`
|
|
452
|
+
`).map((line) => line.trim()));
|
|
453
|
+
for (const line of newText.split(`
|
|
454
|
+
`)) {
|
|
455
|
+
const trimmed = line.trim().replace(/\s+/g, " ");
|
|
456
|
+
if (trimmed.length < 8 || trimmed.length > 80 || previous.has(trimmed) || SECRETISH.test(trimmed))
|
|
457
|
+
continue;
|
|
458
|
+
return safe(trimmed, 60);
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
461
|
+
};
|
|
462
|
+
var replacementStats = (input) => {
|
|
463
|
+
const record = asRecord(input);
|
|
464
|
+
if (!record || typeof record.oldText !== "string" || typeof record.newText !== "string")
|
|
465
|
+
return;
|
|
466
|
+
return {
|
|
467
|
+
added: lineCount(record.newText),
|
|
468
|
+
removed: lineCount(record.oldText),
|
|
469
|
+
intent: statedIntent(record) ?? inferredIntent(record.oldText, record.newText)
|
|
470
|
+
};
|
|
471
|
+
};
|
|
472
|
+
var matchedFiles = (output) => {
|
|
473
|
+
const record = asRecord(output);
|
|
474
|
+
if (!record)
|
|
475
|
+
return;
|
|
476
|
+
const paths = new Set;
|
|
477
|
+
const take = (matches) => {
|
|
478
|
+
if (!Array.isArray(matches))
|
|
479
|
+
return false;
|
|
480
|
+
for (const match of matches) {
|
|
481
|
+
const path = asRecord(match)?.path;
|
|
482
|
+
if (typeof path === "string")
|
|
483
|
+
paths.add(path);
|
|
484
|
+
}
|
|
485
|
+
return true;
|
|
486
|
+
};
|
|
487
|
+
const direct = take(record.matches);
|
|
488
|
+
let nested = false;
|
|
489
|
+
let truncated = record.truncated === true;
|
|
490
|
+
if (Array.isArray(record.results)) {
|
|
491
|
+
for (const result of record.results) {
|
|
492
|
+
const item = asRecord(result);
|
|
493
|
+
if (take(item?.matches))
|
|
494
|
+
nested = true;
|
|
495
|
+
if (item?.truncated === true)
|
|
496
|
+
truncated = true;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (!direct && !nested)
|
|
500
|
+
return;
|
|
501
|
+
return { files: paths.size, truncated };
|
|
502
|
+
};
|
|
503
|
+
var readLine = (input) => {
|
|
504
|
+
const record = asRecord(input);
|
|
505
|
+
const path = typeof record?.path === "string" ? safe(record.path) : "a file";
|
|
506
|
+
return `Read ${path}${lineRange(record?.startLine, record?.endLine)}`;
|
|
507
|
+
};
|
|
508
|
+
var readFilesLine = (input) => {
|
|
509
|
+
const files = asRecord(input)?.files;
|
|
510
|
+
if (!Array.isArray(files) || files.length === 0)
|
|
511
|
+
return "Read files";
|
|
512
|
+
const parts = files.slice(0, 3).map((file) => {
|
|
513
|
+
const record = asRecord(file);
|
|
514
|
+
const path = typeof record?.path === "string" ? safe(record.path, 80) : "a file";
|
|
515
|
+
return `${path}${lineRange(record?.startLine, record?.endLine)}`;
|
|
516
|
+
});
|
|
517
|
+
const more = files.length > 3 ? ` · +${files.length - 3} more` : "";
|
|
518
|
+
return `Read ${parts.join(", ")}${more}`;
|
|
519
|
+
};
|
|
520
|
+
var searchLine = (name, input, output) => {
|
|
521
|
+
const record = asRecord(input);
|
|
522
|
+
const queries = Array.isArray(record?.queries) ? record.queries : undefined;
|
|
523
|
+
const firstQuery = queries ? asRecord(queries[0])?.query : record?.query;
|
|
524
|
+
const query = typeof firstQuery === "string" ? JSON.stringify(safe(firstQuery, 80)) : undefined;
|
|
525
|
+
const matches = matchedFiles(output);
|
|
526
|
+
const where = matches === undefined ? "" : matches.files === 0 ? " · no matches" : ` in ${matches.files} file${matches.files === 1 ? "" : "s"}${matches.truncated ? " · more remain" : ""}`;
|
|
527
|
+
if (name === "search_many" && queries && queries.length > 1) {
|
|
528
|
+
return `Searched ${queries.length} queries${query ? ` · ${query}` : ""}${where}`;
|
|
529
|
+
}
|
|
530
|
+
return `Searched ${query ?? "files"}${where}`;
|
|
531
|
+
};
|
|
532
|
+
var exploreItem = (name, input, output) => {
|
|
533
|
+
if (name === "read_file")
|
|
534
|
+
return { kind: "read", files: 1, line: readLine(input) };
|
|
535
|
+
if (name === "read_files") {
|
|
536
|
+
const files = asRecord(input)?.files;
|
|
537
|
+
return { kind: "read", files: Array.isArray(files) ? files.length : 1, line: readFilesLine(input) };
|
|
538
|
+
}
|
|
539
|
+
if (name === "search_files" || name === "search_many")
|
|
540
|
+
return { kind: "search", files: 0, line: searchLine(name, input, output) };
|
|
541
|
+
if (name === "list_files") {
|
|
542
|
+
const path = asRecord(input)?.path;
|
|
543
|
+
return { kind: "list", files: 0, line: `Listed ${typeof path === "string" ? safe(path) : "."}` };
|
|
544
|
+
}
|
|
545
|
+
if (name === "read_dependency") {
|
|
546
|
+
const record = asRecord(input);
|
|
547
|
+
const pkg = record?.package ?? record?.name;
|
|
548
|
+
return { kind: "read", files: 1, line: `Inspected ${typeof pkg === "string" ? safe(pkg, 80) : "a dependency"}` };
|
|
549
|
+
}
|
|
550
|
+
return { kind: "diff", files: 0, line: "Reviewed the git diff" };
|
|
551
|
+
};
|
|
552
|
+
var exploreSummary = (items) => {
|
|
553
|
+
const reads = items.filter((item) => item.kind === "read").reduce((sum, item) => sum + item.files, 0);
|
|
554
|
+
const searches = items.filter((item) => item.kind === "search").length;
|
|
555
|
+
const listings = items.filter((item) => item.kind === "list").length;
|
|
556
|
+
const diffs = items.filter((item) => item.kind === "diff").length;
|
|
557
|
+
const parts = [];
|
|
558
|
+
if (reads)
|
|
559
|
+
parts.push(`${reads} file${reads === 1 ? "" : "s"}`);
|
|
560
|
+
if (searches)
|
|
561
|
+
parts.push(`${searches} search${searches === 1 ? "" : "es"}`);
|
|
562
|
+
if (listings)
|
|
563
|
+
parts.push(`${listings} listing${listings === 1 ? "" : "s"}`);
|
|
564
|
+
if (diffs)
|
|
565
|
+
parts.push(`${diffs} diff${diffs === 1 ? "" : "s"}`);
|
|
566
|
+
const sample = items[0]?.line ?? "activity";
|
|
567
|
+
return `Explored ${parts.join(" · ") || `${items.length} steps`} · ${sample} · /activity`;
|
|
568
|
+
};
|
|
569
|
+
var otherLine = (name, input) => {
|
|
570
|
+
const record = asRecord(input);
|
|
571
|
+
if (name === "move_file" && typeof record?.source === "string" && typeof record.destination === "string") {
|
|
572
|
+
return `Moved ${safe(record.source)} → ${safe(record.destination)}`;
|
|
573
|
+
}
|
|
574
|
+
if (name === "quarantine_file" && typeof record?.path === "string")
|
|
575
|
+
return `Quarantined ${safe(record.path)}`;
|
|
576
|
+
if (name === "restore_file" && typeof record?.destination === "string")
|
|
577
|
+
return `Restored ${safe(record.destination)}`;
|
|
578
|
+
if (name === "apply_environment_patch")
|
|
579
|
+
return "Imported environment changes";
|
|
580
|
+
if (name === "propose_edits") {
|
|
581
|
+
const changes = Array.isArray(record?.changes) ? record.changes : [];
|
|
582
|
+
const first = asRecord(changes[0])?.path;
|
|
583
|
+
if (changes.length === 1 && typeof first === "string")
|
|
584
|
+
return `Proposed edits for ${safe(first)}`;
|
|
585
|
+
if (changes.length > 1)
|
|
586
|
+
return `Proposed edits for ${changes.length} files`;
|
|
587
|
+
return "Proposed edits";
|
|
588
|
+
}
|
|
589
|
+
if (!KNOWN_TOOLS.has(name) && !name.startsWith("verify_and_apply_"))
|
|
590
|
+
return "Ran tool";
|
|
591
|
+
return `Ran ${safe(name.replaceAll("_", " "), 40)}`;
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
class ActivityStream {
|
|
595
|
+
diff;
|
|
596
|
+
calls = new Map;
|
|
597
|
+
explore = [];
|
|
598
|
+
edit = null;
|
|
599
|
+
constructor(diff) {
|
|
600
|
+
this.diff = diff;
|
|
601
|
+
}
|
|
602
|
+
noteCall(call) {
|
|
603
|
+
this.calls.set(call.id, { name: call.name, input: call.input });
|
|
604
|
+
if (this.calls.size > 40) {
|
|
605
|
+
const oldest = this.calls.keys().next().value;
|
|
606
|
+
if (oldest)
|
|
607
|
+
this.calls.delete(oldest);
|
|
608
|
+
}
|
|
609
|
+
if (isCheck(call.name))
|
|
610
|
+
return this.flushPending();
|
|
611
|
+
if (EDIT_TOOLS.has(call.name)) {
|
|
612
|
+
const path = editPath(call.name, call.input) || call.name;
|
|
613
|
+
const flushed = this.edit && this.edit.path !== path ? this.flushEdit() : [];
|
|
614
|
+
return [...this.flushExplore(), ...flushed];
|
|
615
|
+
}
|
|
616
|
+
if (EXPLORE_TOOLS.has(call.name))
|
|
617
|
+
return this.flushEdit();
|
|
618
|
+
return this.flushPending();
|
|
619
|
+
}
|
|
620
|
+
noteResult(result) {
|
|
621
|
+
const call = this.calls.get(result.toolCallId);
|
|
622
|
+
this.calls.delete(result.toolCallId);
|
|
623
|
+
const name = result.toolName || call?.name || "tool";
|
|
624
|
+
const input = call?.input;
|
|
625
|
+
if (result.isError) {
|
|
626
|
+
const line = compactToolResult({ toolName: name, isError: true, error: result.error }) ?? "✗ Tool operation · operation failed. Inspect /activity and retry that file.";
|
|
627
|
+
return [...this.flushPending(), emission(line)];
|
|
628
|
+
}
|
|
629
|
+
if (name.startsWith("verify_and_apply_")) {
|
|
630
|
+
this.appendEdit(name, input);
|
|
631
|
+
return this.flushPending();
|
|
632
|
+
}
|
|
633
|
+
if (isCheck(name))
|
|
634
|
+
return this.flushPending();
|
|
635
|
+
if (EDIT_TOOLS.has(name)) {
|
|
636
|
+
const path = editPath(name, input) || name;
|
|
637
|
+
const flushed = this.edit && this.edit.path !== path ? this.flushEdit() : [];
|
|
638
|
+
this.appendEdit(name, input);
|
|
639
|
+
return [...this.flushExplore(), ...flushed];
|
|
640
|
+
}
|
|
641
|
+
if (EXPLORE_TOOLS.has(name)) {
|
|
642
|
+
const flushed = this.flushEdit();
|
|
643
|
+
this.explore.push(exploreItem(name, input, result.output));
|
|
644
|
+
return flushed;
|
|
645
|
+
}
|
|
646
|
+
return [...this.flushPending(), emission(otherLine(name, input))];
|
|
647
|
+
}
|
|
648
|
+
flush() {
|
|
649
|
+
return this.flushPending();
|
|
650
|
+
}
|
|
651
|
+
flushPending() {
|
|
652
|
+
return [...this.flushExplore(), ...this.flushEdit()];
|
|
653
|
+
}
|
|
654
|
+
flushExplore() {
|
|
655
|
+
if (!this.explore.length)
|
|
656
|
+
return [];
|
|
657
|
+
const items = this.explore;
|
|
658
|
+
this.explore = [];
|
|
659
|
+
if (items.length === 1)
|
|
660
|
+
return [emission(items[0]?.line ?? "Read a file")];
|
|
661
|
+
return [emission(exploreSummary(items), items.map((item) => ` ${item.line}`))];
|
|
662
|
+
}
|
|
663
|
+
flushEdit() {
|
|
664
|
+
if (!this.edit)
|
|
665
|
+
return [];
|
|
666
|
+
const group = this.edit;
|
|
667
|
+
this.edit = null;
|
|
668
|
+
const stats = group.stats ? ` +${group.added} −${group.removed}` : "";
|
|
669
|
+
const intent = group.intent ? `: ${group.intent}` : "";
|
|
670
|
+
const attempts = group.attempts > 1 ? ` · ${group.attempts} attempts` : "";
|
|
671
|
+
return [emission(`Edited ${editLabel(group.path)}${stats}${intent}${attempts}`, group.attempts > 1 ? group.details : [])];
|
|
672
|
+
}
|
|
673
|
+
appendEdit(name, input) {
|
|
674
|
+
const path = editPath(name, input) || name;
|
|
675
|
+
if (!this.edit || this.edit.path !== path) {
|
|
676
|
+
this.edit = { path, added: 0, removed: 0, attempts: 0, stats: true, details: [] };
|
|
677
|
+
}
|
|
678
|
+
const group = this.edit;
|
|
679
|
+
const stats = name === "apply_reviewed_replacement" ? replacementStats(input) : undefined;
|
|
680
|
+
const intent = stats?.intent ?? statedIntent(input);
|
|
681
|
+
group.attempts += 1;
|
|
682
|
+
if (!group.intent && intent)
|
|
683
|
+
group.intent = intent;
|
|
684
|
+
if (stats) {
|
|
685
|
+
group.added += stats.added;
|
|
686
|
+
group.removed += stats.removed;
|
|
687
|
+
this.diff.added += stats.added;
|
|
688
|
+
this.diff.removed += stats.removed;
|
|
689
|
+
group.details.push(` attempt ${group.attempts} +${stats.added} −${stats.removed}${intent ? `: ${intent}` : ""}`);
|
|
690
|
+
} else {
|
|
691
|
+
group.stats = false;
|
|
692
|
+
group.details.push(` attempt ${group.attempts}`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// packages/core/src/cli/terminal/terminal-markdown.ts
|
|
697
|
+
class TerminalMarkdown {
|
|
698
|
+
output;
|
|
699
|
+
color;
|
|
700
|
+
columns;
|
|
701
|
+
pending = "";
|
|
702
|
+
code = false;
|
|
703
|
+
heading = false;
|
|
704
|
+
lineStart = true;
|
|
705
|
+
timer;
|
|
706
|
+
tableLines = [];
|
|
707
|
+
constructor(output, color, columns = () => 80) {
|
|
708
|
+
this.output = output;
|
|
709
|
+
this.color = color;
|
|
710
|
+
this.columns = columns;
|
|
711
|
+
}
|
|
712
|
+
drain(final = false) {
|
|
713
|
+
let rendered = "", activeStyle = 0;
|
|
714
|
+
const emit = (text, style = this.code ? 36 : this.heading ? 1 : 0) => {
|
|
715
|
+
if (this.color && style !== activeStyle) {
|
|
716
|
+
if (activeStyle)
|
|
717
|
+
rendered += "\x1B[0m";
|
|
718
|
+
if (style)
|
|
719
|
+
rendered += `\x1B[${style}m`;
|
|
720
|
+
activeStyle = style;
|
|
721
|
+
}
|
|
722
|
+
rendered += text;
|
|
723
|
+
};
|
|
724
|
+
const finishTable = () => {
|
|
725
|
+
if (!this.tableLines.length)
|
|
726
|
+
return;
|
|
727
|
+
emit(this.tableLines.length > 1 ? renderTerminalTable(this.tableLines, this.columns(), this.color) : this.tableLines[0], 0);
|
|
728
|
+
this.tableLines = [];
|
|
729
|
+
};
|
|
730
|
+
while (this.pending) {
|
|
731
|
+
if (!final && this.pending.length === 1 && /[\uD800-\uDBFF]/.test(this.pending))
|
|
732
|
+
break;
|
|
733
|
+
if (this.lineStart) {
|
|
734
|
+
if (!this.code && (this.pending.startsWith("|") || this.tableLines.length)) {
|
|
735
|
+
const end = this.pending.indexOf(`
|
|
736
|
+
`);
|
|
737
|
+
if (this.pending.startsWith("|") && end < 0 && !final && this.pending.length < 8192)
|
|
738
|
+
break;
|
|
739
|
+
const line = this.pending.slice(0, end < 0 ? this.pending.length : end + 1);
|
|
740
|
+
const count = this.tableLines.length ? tableCells(this.tableLines[0]).length : 0;
|
|
741
|
+
const accepted = (end >= 0 || final) && this.pending.startsWith("|") && line.length <= 8192 && (this.tableLines.length === 0 ? tableCells(line).length > 0 : this.tableLines.length === 1 ? isTableSeparator(line, count) : tableCells(line).length === count);
|
|
742
|
+
if (accepted && this.tableLines.length < 128) {
|
|
743
|
+
this.tableLines.push(line);
|
|
744
|
+
this.pending = this.pending.slice(line.length);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
finishTable();
|
|
748
|
+
}
|
|
749
|
+
if (!final && (/^`{1,2}$/.test(this.pending) || /^#{1,6}$/.test(this.pending)))
|
|
750
|
+
break;
|
|
751
|
+
if (this.pending.startsWith("```")) {
|
|
752
|
+
const end = this.pending.indexOf(`
|
|
753
|
+
`);
|
|
754
|
+
if (end < 0 && !final && this.pending.length < 128)
|
|
755
|
+
break;
|
|
756
|
+
const length = end < 0 ? this.pending.length : end;
|
|
757
|
+
emit(this.pending.slice(0, length), 90);
|
|
758
|
+
this.pending = this.pending.slice(length);
|
|
759
|
+
this.code = !this.code;
|
|
760
|
+
this.lineStart = false;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (!this.code) {
|
|
764
|
+
const heading = /^#{1,6} /.exec(this.pending);
|
|
765
|
+
if (heading) {
|
|
766
|
+
this.heading = true;
|
|
767
|
+
this.pending = this.pending.slice(heading[0].length);
|
|
768
|
+
this.lineStart = false;
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
this.lineStart = false;
|
|
773
|
+
}
|
|
774
|
+
if (this.pending[0] === `
|
|
775
|
+
`) {
|
|
776
|
+
emit(`
|
|
777
|
+
`, 0);
|
|
778
|
+
this.pending = this.pending.slice(1);
|
|
779
|
+
this.lineStart = true;
|
|
780
|
+
this.heading = false;
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
if (this.color && !this.code) {
|
|
784
|
+
if (this.pending === "*" && !final)
|
|
785
|
+
break;
|
|
786
|
+
const marker = this.pending.startsWith("**") ? "**" : this.pending[0] === "`" ? "`" : undefined;
|
|
787
|
+
if (marker) {
|
|
788
|
+
const end = this.pending.indexOf(marker, marker.length);
|
|
789
|
+
const newline = this.pending.indexOf(`
|
|
790
|
+
`);
|
|
791
|
+
if (end > marker.length && (newline < 0 || end < newline)) {
|
|
792
|
+
emit(this.pending.slice(marker.length, end), marker === "`" ? 36 : 1);
|
|
793
|
+
this.pending = this.pending.slice(end + marker.length);
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
if (!final && newline < 0 && this.pending.length < 2048)
|
|
797
|
+
break;
|
|
798
|
+
emit(marker);
|
|
799
|
+
this.pending = this.pending.slice(marker.length);
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
const point = String.fromCodePoint(this.pending.codePointAt(0));
|
|
804
|
+
emit(point);
|
|
805
|
+
this.pending = this.pending.slice(point.length);
|
|
806
|
+
}
|
|
807
|
+
if (final)
|
|
808
|
+
finishTable();
|
|
809
|
+
if (activeStyle)
|
|
810
|
+
rendered += "\x1B[0m";
|
|
811
|
+
if (rendered)
|
|
812
|
+
this.output(rendered);
|
|
813
|
+
}
|
|
814
|
+
write(delta) {
|
|
815
|
+
this.pending += sanitizeTerminalText(delta);
|
|
816
|
+
if (this.pending.includes(`
|
|
817
|
+
`) || this.pending.length >= 2048)
|
|
818
|
+
this.drain();
|
|
819
|
+
if (this.pending && !this.timer) {
|
|
820
|
+
this.timer = setTimeout(() => {
|
|
821
|
+
this.timer = undefined;
|
|
822
|
+
this.drain();
|
|
823
|
+
}, 24);
|
|
824
|
+
this.timer.unref();
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
flush() {
|
|
828
|
+
clearTimeout(this.timer);
|
|
829
|
+
this.timer = undefined;
|
|
830
|
+
this.drain(true);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// packages/core/src/cli/presentation.ts
|
|
835
|
+
import { createInterface } from "node:readline/promises";
|
|
836
|
+
import {
|
|
837
|
+
createRedactionPolicy as createRedactionPolicy3
|
|
838
|
+
} from "@zhivex-ai/agents";
|
|
839
|
+
var CLI_STREAM_ERROR_SEQUENCE = Symbol("cliStreamErrorSequence");
|
|
840
|
+
var terminalErrorRedaction = createRedactionPolicy3({ includeEmails: true });
|
|
841
|
+
var annotateCliStreamError = (error, lastSequence) => {
|
|
842
|
+
const normalized = error instanceof Error ? error : normalizeHarnessError(error);
|
|
843
|
+
Object.defineProperty(normalized, CLI_STREAM_ERROR_SEQUENCE, {
|
|
844
|
+
configurable: true,
|
|
845
|
+
enumerable: false,
|
|
846
|
+
value: (lastSequence ?? 0) + 1
|
|
847
|
+
});
|
|
848
|
+
return normalized;
|
|
849
|
+
};
|
|
850
|
+
var cliStreamErrorSequence = (error) => error && typeof error === "object" && Number.isSafeInteger(error[CLI_STREAM_ERROR_SEQUENCE]) ? error[CLI_STREAM_ERROR_SEQUENCE] : 1;
|
|
851
|
+
var terminalErrorMessage = (error) => terminalErrorRedaction.redactText(error instanceof Error ? error.message : String(error));
|
|
852
|
+
var summarizeApproval = (approval) => {
|
|
853
|
+
return formatApproval(approval);
|
|
854
|
+
};
|
|
855
|
+
var approvalResponses = (approvals, approve, reason) => approvals.map((approval) => ({
|
|
856
|
+
provider: approval.provider,
|
|
857
|
+
approvalRequestId: approval.id,
|
|
858
|
+
approve,
|
|
859
|
+
reason
|
|
860
|
+
}));
|
|
861
|
+
var interactiveApprovalResolver = (automaticallyApprove, ask, ui) => {
|
|
862
|
+
return async (approvals) => {
|
|
863
|
+
if (automaticallyApprove === "restricted")
|
|
864
|
+
return approvalResponses(approvals, false, "Denied by restricted approval mode.");
|
|
865
|
+
if (automaticallyApprove === true || automaticallyApprove === "auto") {
|
|
866
|
+
return approvalResponses(approvals, true, "Approved by automatic mode.");
|
|
867
|
+
}
|
|
868
|
+
const policy = ui?.requireCompleteReview ? undefined : ui?.autoApprove?.();
|
|
869
|
+
if (policy && policy.mode !== "manual") {
|
|
870
|
+
const batch = decideBatch(approvals.map((approval) => ({ name: approval.name, arguments: approval.arguments })), policy);
|
|
871
|
+
if (batch.auto && ui) {
|
|
872
|
+
const { review: _review, select: _select, ...rest } = ui;
|
|
873
|
+
return resolveTerminalApprovals(approvals, {
|
|
874
|
+
ask: async () => "",
|
|
875
|
+
write: () => {
|
|
876
|
+
return;
|
|
877
|
+
},
|
|
878
|
+
...rest
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
if (!ask && (!process.stdin.isTTY || !process.stdout.isTTY))
|
|
883
|
+
return;
|
|
884
|
+
const readline = ask ? undefined : createInterface({ input: process.stdin, output: process.stdout });
|
|
885
|
+
try {
|
|
886
|
+
return await resolveTerminalApprovals(approvals, {
|
|
887
|
+
ask: ask ?? ((text) => readline.question(text)),
|
|
888
|
+
write: (text) => process.stderr.write(text),
|
|
889
|
+
...ui
|
|
890
|
+
});
|
|
891
|
+
} finally {
|
|
892
|
+
readline?.close();
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
};
|
|
896
|
+
var terminalApprovalResolver = (automaticallyApprove, ask, ui, reviewHost) => {
|
|
897
|
+
return async (approvals, state) => {
|
|
898
|
+
const automatic = (approve, reason) => {
|
|
899
|
+
const responses2 = approvalResponses(approvals, approve, reason);
|
|
900
|
+
return reviewHost ? issueAutomaticApprovalResponses(reviewHost, state, responses2, "cli-automatic") : responses2;
|
|
901
|
+
};
|
|
902
|
+
if (automaticallyApprove === "restricted")
|
|
903
|
+
return automatic(false, "Denied by restricted approval mode.");
|
|
904
|
+
if (automaticallyApprove === true || automaticallyApprove === "auto") {
|
|
905
|
+
return automatic(true, "Approved by automatic mode.");
|
|
906
|
+
}
|
|
907
|
+
if (!reviewHost) {
|
|
908
|
+
return interactiveApprovalResolver(automaticallyApprove, ask, ui)(approvals, state);
|
|
909
|
+
}
|
|
910
|
+
const explicit = requiresExplicitHostReview(reviewHost);
|
|
911
|
+
const startedAt = Date.now();
|
|
912
|
+
const snapshot = structuredClone(state);
|
|
913
|
+
const origins = [];
|
|
914
|
+
const effectiveUi = explicit ? {
|
|
915
|
+
...ui?.select && ui.workspace ? { select: ui.select, workspace: ui.workspace } : {},
|
|
916
|
+
requireCompleteReview: true,
|
|
917
|
+
onDecisionOrigin: (origin) => origins.push(origin)
|
|
918
|
+
} : {
|
|
919
|
+
...ui,
|
|
920
|
+
onDecisionOrigin: (origin) => origins.push(origin)
|
|
921
|
+
};
|
|
922
|
+
const responses = await interactiveApprovalResolver(automaticallyApprove, ask, effectiveUi)(explicit ? snapshot.pendingApprovals : approvals, state);
|
|
923
|
+
if (!responses)
|
|
924
|
+
return;
|
|
925
|
+
return explicit ? issueExplicitReviewResponses(reviewHost, snapshot, responses, "cli-terminal", startedAt) : issueObservedApprovalResponses(reviewHost, snapshot, responses, "cli-terminal", origins, startedAt);
|
|
926
|
+
};
|
|
927
|
+
};
|
|
928
|
+
var printTerminalResult = (result, harness, output, tracker) => {
|
|
929
|
+
tracker.markdown?.flush();
|
|
930
|
+
const document = {
|
|
931
|
+
...runResultDocument(result, harness),
|
|
932
|
+
...tracker.policyEvidence ? { policyEvidence: tracker.policyEvidence } : {}
|
|
933
|
+
};
|
|
934
|
+
if (output.jsonl) {
|
|
935
|
+
tracker.sequence = (tracker.sequence ?? 0) + 1;
|
|
936
|
+
process.stdout.write(`${serializeStreamResult(document, tracker.sequence)}
|
|
937
|
+
`);
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
if (output.json) {
|
|
941
|
+
process.stdout.write(`${JSON.stringify(document, null, 2)}
|
|
942
|
+
`);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (!tracker.streamedText && result.outputText) {
|
|
946
|
+
process.stdout.write(sanitizeTerminalText(result.outputText));
|
|
947
|
+
}
|
|
948
|
+
if (result.outputText || tracker.streamedText) {
|
|
949
|
+
process.stdout.write(`
|
|
950
|
+
`);
|
|
951
|
+
}
|
|
952
|
+
process.stderr.write(`
|
|
953
|
+
run ${result.state.runId} · ${result.state.provider}/${result.state.modelId} · ${result.status} · ${result.steps.length} steps · ${harness.workspace.mutationAudit().length} mutations
|
|
954
|
+
`);
|
|
955
|
+
if (result.state.metadata?.[USAGE_LEDGER_KEY])
|
|
956
|
+
process.stderr.write(formatUsageLedger(result.state.metadata[USAGE_LEDGER_KEY]) + `
|
|
957
|
+
`);
|
|
958
|
+
process.stderr.write(formatVerificationSummary(result.toolResults) + `
|
|
959
|
+
`);
|
|
960
|
+
if (result.status === "waiting_approval") {
|
|
961
|
+
for (const approval of result.state.pendingApprovals) {
|
|
962
|
+
process.stderr.write(`
|
|
963
|
+
Pending approval:
|
|
964
|
+
${summarizeApproval(approval)}
|
|
965
|
+
`);
|
|
966
|
+
}
|
|
967
|
+
process.stderr.write(`The state was persisted. Resume with: ${resumeCommand(result.state.runId, harness.config)}
|
|
968
|
+
`);
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
var proseLineOpen = new WeakSet;
|
|
972
|
+
var conversationStarted = new WeakSet;
|
|
973
|
+
var toolActivities = new WeakMap;
|
|
974
|
+
var activityStreams = new WeakMap;
|
|
975
|
+
var lastTerminalFailures = new WeakMap;
|
|
976
|
+
var activityStreamFor = (tracker) => {
|
|
977
|
+
let stream = activityStreams.get(tracker);
|
|
978
|
+
if (!stream) {
|
|
979
|
+
tracker.turnDiff ??= { added: 0, removed: 0 };
|
|
980
|
+
stream = new ActivityStream(tracker.turnDiff);
|
|
981
|
+
activityStreams.set(tracker, stream);
|
|
982
|
+
}
|
|
983
|
+
return stream;
|
|
984
|
+
};
|
|
985
|
+
var emitActivity = (tracker, batch, print) => {
|
|
986
|
+
for (const item of batch) {
|
|
987
|
+
if (print && item.live)
|
|
988
|
+
process.stderr.write(`${item.live}
|
|
989
|
+
`);
|
|
990
|
+
for (const line of item.history)
|
|
991
|
+
tracker.activityHistory?.add(line);
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
var recordActivity = (tracker, event, print) => {
|
|
995
|
+
const stream = activityStreamFor(tracker);
|
|
996
|
+
const batch = event.type === "tool-call" ? stream.noteCall(event.toolCall) : event.type === "tool-result" ? stream.noteResult(event.toolResult) : event.type === "text-delta" || event.type === "agent-run-finish" || event.type === "error" || event.type === "tool-approval-request" || event.type === "agent-approval-request" ? stream.flush() : undefined;
|
|
997
|
+
if (!batch?.length)
|
|
998
|
+
return;
|
|
999
|
+
if (print && batch.some((item) => item.live))
|
|
1000
|
+
toolActivities.get(tracker)?.pause();
|
|
1001
|
+
emitActivity(tracker, batch, print);
|
|
1002
|
+
};
|
|
1003
|
+
var flushToolActivity = (tracker) => {
|
|
1004
|
+
const host = tracker;
|
|
1005
|
+
const stream = activityStreams.get(tracker);
|
|
1006
|
+
if (stream)
|
|
1007
|
+
emitActivity(host, stream.flush(), true);
|
|
1008
|
+
toolActivities.get(tracker)?.flush({ summary: !host.consoleView });
|
|
1009
|
+
};
|
|
1010
|
+
var streamSink = (output, tracker, compact = false) => async (event) => {
|
|
1011
|
+
if (!output.json && !output.jsonl) {
|
|
1012
|
+
if (tracker.consoleView) {
|
|
1013
|
+
recordActivity(tracker, event, compact);
|
|
1014
|
+
tracker.activityHistory?.observe(event, { includeTools: false });
|
|
1015
|
+
} else {
|
|
1016
|
+
tracker.activityHistory?.observe(event);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
if (output.jsonl) {
|
|
1020
|
+
const sequence = (tracker.sequence ?? 0) + 1;
|
|
1021
|
+
const serialized = serializeStreamEvent(event, sequence);
|
|
1022
|
+
if (serialized === undefined)
|
|
1023
|
+
return;
|
|
1024
|
+
tracker.sequence = sequence;
|
|
1025
|
+
process.stdout.write(`${serialized}
|
|
1026
|
+
`);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
if (!output.json && compact && event.type === "agent-run-update")
|
|
1030
|
+
return;
|
|
1031
|
+
if (!output.json && compact) {
|
|
1032
|
+
let activity = toolActivities.get(tracker);
|
|
1033
|
+
if (!activity) {
|
|
1034
|
+
activity = new ToolActivity((text) => {
|
|
1035
|
+
process.stderr.write(text);
|
|
1036
|
+
}, Boolean(process.stderr.isTTY && process.stdout.isTTY && !tracker.consoleView), () => process.stderr.columns || 80, tracker.inputStatus);
|
|
1037
|
+
toolActivities.set(tracker, activity);
|
|
1038
|
+
}
|
|
1039
|
+
if (event.type === "agent-compaction") {
|
|
1040
|
+
tracker.markdown?.flush();
|
|
1041
|
+
if (proseLineOpen.has(tracker)) {
|
|
1042
|
+
process.stdout.write(`
|
|
1043
|
+
`);
|
|
1044
|
+
proseLineOpen.delete(tracker);
|
|
1045
|
+
}
|
|
1046
|
+
activity.phase("Updating context");
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
if (event.type === "agent-step-start") {
|
|
1050
|
+
tracker.markdown?.flush();
|
|
1051
|
+
if (proseLineOpen.has(tracker)) {
|
|
1052
|
+
process.stdout.write(`
|
|
1053
|
+
`);
|
|
1054
|
+
proseLineOpen.delete(tracker);
|
|
1055
|
+
}
|
|
1056
|
+
activity.phase("Waiting for model response", event.stepIndex);
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
if (event.type === "agent-run-start") {
|
|
1060
|
+
lastTerminalFailures.delete(tracker);
|
|
1061
|
+
activity.phase("Waiting for model response", event.currentStep);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
if (event.type === "tool-call") {
|
|
1065
|
+
tracker.markdown?.flush();
|
|
1066
|
+
if (proseLineOpen.has(tracker)) {
|
|
1067
|
+
process.stdout.write(`
|
|
1068
|
+
`);
|
|
1069
|
+
proseLineOpen.delete(tracker);
|
|
1070
|
+
}
|
|
1071
|
+
activity.start(event.toolCall.name);
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
if (event.type === "tool-result") {
|
|
1075
|
+
activity.finish(event.toolResult.toolName, !event.toolResult.isError);
|
|
1076
|
+
const check = ["run_check", "run_environment_command"].includes(event.toolResult.toolName) || event.toolResult.toolName.startsWith("verify_and_apply_");
|
|
1077
|
+
if (!tracker.consoleView) {
|
|
1078
|
+
const detail = compactToolResult(event.toolResult, { includeSuccessEdits: true });
|
|
1079
|
+
if (detail && !check) {
|
|
1080
|
+
activity.pause();
|
|
1081
|
+
tracker.markdown?.flush();
|
|
1082
|
+
if (proseLineOpen.has(tracker)) {
|
|
1083
|
+
process.stdout.write(`
|
|
1084
|
+
`);
|
|
1085
|
+
proseLineOpen.delete(tracker);
|
|
1086
|
+
}
|
|
1087
|
+
process.stderr.write(`${detail}
|
|
1088
|
+
`);
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
if (!check) {
|
|
1093
|
+
activity.pause();
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
activity.pause();
|
|
1097
|
+
} else if (["agent-run-finish", "error", "tool-approval-request", "agent-approval-request"].includes(event.type)) {
|
|
1098
|
+
tracker.markdown?.flush();
|
|
1099
|
+
if (proseLineOpen.has(tracker)) {
|
|
1100
|
+
process.stdout.write(`
|
|
1101
|
+
`);
|
|
1102
|
+
proseLineOpen.delete(tracker);
|
|
1103
|
+
}
|
|
1104
|
+
activity.flush({ summary: !tracker.consoleView });
|
|
1105
|
+
} else if (!["provider-data", "finish", "agent-step-start", "agent-step-finish"].includes(event.type)) {
|
|
1106
|
+
activity.pause();
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
if (!output.json && event.type === "text-delta") {
|
|
1110
|
+
if (compact && !conversationStarted.has(tracker)) {
|
|
1111
|
+
process.stdout.write(terminalSupportsColor(Boolean(process.stdout.isTTY)) ? `
|
|
1112
|
+
\x1B[1mZhivex\x1B[0m
|
|
1113
|
+
` : `
|
|
1114
|
+
Zhivex
|
|
1115
|
+
`);
|
|
1116
|
+
conversationStarted.add(tracker);
|
|
1117
|
+
}
|
|
1118
|
+
if (event.textDelta.endsWith(`
|
|
1119
|
+
`))
|
|
1120
|
+
proseLineOpen.delete(tracker);
|
|
1121
|
+
else if (event.textDelta)
|
|
1122
|
+
proseLineOpen.add(tracker);
|
|
1123
|
+
tracker.streamedText = true;
|
|
1124
|
+
if (process.stdout.isTTY) {
|
|
1125
|
+
tracker.markdown ??= new TerminalMarkdown((text) => {
|
|
1126
|
+
process.stdout.write(text);
|
|
1127
|
+
}, terminalSupportsColor(true), () => process.stdout.columns || 80);
|
|
1128
|
+
tracker.markdown.write(event.textDelta);
|
|
1129
|
+
} else
|
|
1130
|
+
process.stdout.write(sanitizeTerminalText(event.textDelta));
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
if (!output.json) {
|
|
1134
|
+
if (tracker.consoleView && event.type === "agent-run-finish" && event.status === "completed")
|
|
1135
|
+
return;
|
|
1136
|
+
if (compact && ["provider-data", "finish", "agent-run-start", "agent-step-start", "agent-step-finish", "tool-approval-request", "agent-approval-request", "agent-approval-resolved"].includes(event.type))
|
|
1137
|
+
return;
|
|
1138
|
+
if (compact && event.type === "agent-run-finish" && event.status === "waiting_approval")
|
|
1139
|
+
return;
|
|
1140
|
+
tracker.markdown?.flush();
|
|
1141
|
+
proseLineOpen.delete(tracker);
|
|
1142
|
+
let line = formatTerminalEvent(event, {
|
|
1143
|
+
color: terminalSupportsColor(Boolean(process.stderr.isTTY))
|
|
1144
|
+
});
|
|
1145
|
+
if (compact && event.type === "tool-result" && event.toolResult.isError && line?.endsWith(" · error")) {
|
|
1146
|
+
line = compactToolResult(event.toolResult);
|
|
1147
|
+
}
|
|
1148
|
+
if ((event.type === "error" || event.type === "agent-run-finish" && event.status === "failed") && line) {
|
|
1149
|
+
const cause = terminalRunFailure(event.type === "error" ? event.error : event.state.error);
|
|
1150
|
+
if (lastTerminalFailures.get(tracker) === cause)
|
|
1151
|
+
return;
|
|
1152
|
+
lastTerminalFailures.set(tracker, cause);
|
|
1153
|
+
} else if (event.type === "agent-run-start")
|
|
1154
|
+
lastTerminalFailures.delete(tracker);
|
|
1155
|
+
if (line)
|
|
1156
|
+
process.stderr.write(`
|
|
1157
|
+
${line}
|
|
1158
|
+
`);
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
var orchestrationObserver = (json) => async (event) => {
|
|
1162
|
+
if (json)
|
|
1163
|
+
return;
|
|
1164
|
+
if (event.type === "subagent-start") {
|
|
1165
|
+
process.stderr.write(`
|
|
1166
|
+
subagent start · ${event.childAgentId ?? event.toolName}
|
|
1167
|
+
`);
|
|
1168
|
+
} else if (event.type === "subagent-finish") {
|
|
1169
|
+
process.stderr.write(`
|
|
1170
|
+
subagent finish · ${event.childRun.agentId ?? event.childRun.toolName} · ${event.childRun.status}
|
|
1171
|
+
`);
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
|
|
1175
|
+
// packages/core/src/cli/qwen-connection.ts
|
|
1176
|
+
var regions = {
|
|
1177
|
+
singapore: ["Singapore", "ap-southeast-1", "dashscope-intl.aliyuncs.com"],
|
|
1178
|
+
beijing: ["Beijing", "cn-beijing", "dashscope.aliyuncs.com"],
|
|
1179
|
+
"hong-kong": ["Hong Kong", "cn-hongkong", "cn-hongkong.dashscope.aliyuncs.com"],
|
|
1180
|
+
tokyo: ["Tokyo", "ap-northeast-1", ""],
|
|
1181
|
+
frankfurt: ["Frankfurt", "eu-central-1", ""],
|
|
1182
|
+
virginia: ["Virginia", "us-east-1", ""]
|
|
1183
|
+
};
|
|
1184
|
+
function qwenEndpoint(connection) {
|
|
1185
|
+
if (connection.service === "token-plan")
|
|
1186
|
+
return "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
|
|
1187
|
+
if (connection.service !== "api" || !Object.hasOwn(regions, connection.region))
|
|
1188
|
+
throw new Error("Invalid Qwen connection.");
|
|
1189
|
+
const [, region, legacy] = regions[connection.region];
|
|
1190
|
+
if (connection.workspace !== undefined && !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(connection.workspace))
|
|
1191
|
+
throw new Error("Invalid Qwen workspace ID.");
|
|
1192
|
+
const host = connection.workspace ? `${connection.workspace}.${region}.maas.aliyuncs.com` : legacy;
|
|
1193
|
+
if (!host)
|
|
1194
|
+
throw new Error("This Qwen region requires a workspace ID.");
|
|
1195
|
+
return `https://${host}/compatible-mode/v1`;
|
|
1196
|
+
}
|
|
1197
|
+
function decodeQwenCredential(value) {
|
|
1198
|
+
if (!value.startsWith("{"))
|
|
1199
|
+
return { key: value, connection: { service: "api", region: "singapore" } };
|
|
1200
|
+
const parsed = JSON.parse(value);
|
|
1201
|
+
if (parsed.version !== 1 || typeof parsed.key !== "string" || !parsed.connection)
|
|
1202
|
+
throw new Error("Invalid Qwen credential record.");
|
|
1203
|
+
qwenEndpoint(parsed.connection);
|
|
1204
|
+
return { key: parsed.key, connection: parsed.connection };
|
|
1205
|
+
}
|
|
1206
|
+
async function selectQwenConnection(input) {
|
|
1207
|
+
const service = await input.select("Qwen / Service", [
|
|
1208
|
+
{ value: "api", label: "Standard API / Alibaba Cloud Model Studio", detail: "Use the region where your API key was created" },
|
|
1209
|
+
{ value: "token-plan", label: "QwenCloud Token Plan", detail: "Separate subscription endpoint and credential" }
|
|
1210
|
+
]);
|
|
1211
|
+
if (!service)
|
|
1212
|
+
return;
|
|
1213
|
+
if (service === "token-plan")
|
|
1214
|
+
return { service };
|
|
1215
|
+
const region = await input.select("Qwen / API region", Object.entries(regions).map(([value, [label]]) => ({ value, label })));
|
|
1216
|
+
if (!region)
|
|
1217
|
+
return;
|
|
1218
|
+
let workspace;
|
|
1219
|
+
const dedicated = !regions[region][2] || await input.select("Qwen / Endpoint", [
|
|
1220
|
+
{ value: false, label: "DashScope endpoint", detail: "Existing regional API endpoint" },
|
|
1221
|
+
{ value: true, label: "Workspace endpoint", detail: "Enter your workspace ID" },
|
|
1222
|
+
{ value: "cancel", label: "Back" }
|
|
1223
|
+
]);
|
|
1224
|
+
if (dedicated === undefined || dedicated === "cancel")
|
|
1225
|
+
return;
|
|
1226
|
+
if (dedicated) {
|
|
1227
|
+
if (!input.question)
|
|
1228
|
+
throw new Error("Workspace setup requires interactive input.");
|
|
1229
|
+
workspace = (await input.question("Workspace ID (not the API key): ")).trim();
|
|
1230
|
+
if (!workspace)
|
|
1231
|
+
return;
|
|
1232
|
+
}
|
|
1233
|
+
const connection = { service: "api", region, ...workspace ? { workspace } : {} };
|
|
1234
|
+
qwenEndpoint(connection);
|
|
1235
|
+
return connection;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// packages/core/src/cli/cli-credentials.ts
|
|
1239
|
+
class CredentialSetupError extends Error {
|
|
1240
|
+
}
|
|
1241
|
+
var credentialService = "ai.zhivex.harness.cli";
|
|
1242
|
+
var validCredential = (value) => /^[\x21-\x7e]{1,8192}$/.test(value);
|
|
1243
|
+
var nativeCredentialEntry = async (provider) => {
|
|
1244
|
+
if (!PROVIDERS.includes(provider))
|
|
1245
|
+
throw new Error("Unsupported credential provider.");
|
|
1246
|
+
if (!["darwin", "linux"].includes(process.platform) || process.env.ZHIVEX_HARNESS_CREDENTIAL_STORE === "disabled") {
|
|
1247
|
+
throw new Error("Secure credential storage is unavailable.");
|
|
1248
|
+
}
|
|
1249
|
+
const { AsyncEntry } = await import("@napi-rs/keyring");
|
|
1250
|
+
const entry = new AsyncEntry(credentialService, provider, { linux: { store: "secret-service" } });
|
|
1251
|
+
return {
|
|
1252
|
+
getPassword: () => entry.getPassword(AbortSignal.timeout(30000)),
|
|
1253
|
+
setPassword: (value) => entry.setPassword(value, AbortSignal.timeout(30000)),
|
|
1254
|
+
deleteCredential: () => entry.deleteCredential(AbortSignal.timeout(30000))
|
|
1255
|
+
};
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
class CliCredentials {
|
|
1259
|
+
entry;
|
|
1260
|
+
environment;
|
|
1261
|
+
write;
|
|
1262
|
+
temporary = new Map;
|
|
1263
|
+
revision = 0;
|
|
1264
|
+
qwenManaged = false;
|
|
1265
|
+
qwenOverrideAccepted = false;
|
|
1266
|
+
constructor(entry = nativeCredentialEntry, environment = process.env, write = (text) => {
|
|
1267
|
+
process.stderr.write(text);
|
|
1268
|
+
}) {
|
|
1269
|
+
this.entry = entry;
|
|
1270
|
+
this.environment = environment;
|
|
1271
|
+
this.write = write;
|
|
1272
|
+
}
|
|
1273
|
+
environmentKey(provider) {
|
|
1274
|
+
return providerDescriptor(provider).credentialNames.map((name) => this.environment[name]?.trim()).find(Boolean);
|
|
1275
|
+
}
|
|
1276
|
+
validate(value) {
|
|
1277
|
+
if (!validCredential(value))
|
|
1278
|
+
throw new Error("Invalid API key: use 1–8192 printable characters without whitespace.");
|
|
1279
|
+
return value;
|
|
1280
|
+
}
|
|
1281
|
+
async saved(provider) {
|
|
1282
|
+
try {
|
|
1283
|
+
const value = await (await this.entry(provider)).getPassword();
|
|
1284
|
+
if (value == null)
|
|
1285
|
+
return;
|
|
1286
|
+
this.validate(provider === "qwen" ? decodeQwenCredential(value).key : value);
|
|
1287
|
+
return value;
|
|
1288
|
+
} catch {
|
|
1289
|
+
throw new Error("Secure storage is unavailable or locked. Unlock it, use a temporary key, or configure the environment.");
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
destinations = new Map;
|
|
1293
|
+
destination(provider) {
|
|
1294
|
+
return this.destinations.get(provider) ?? "environment-defined or provider default";
|
|
1295
|
+
}
|
|
1296
|
+
sources = new Map;
|
|
1297
|
+
source(provider) {
|
|
1298
|
+
return this.sources.get(provider) ?? "missing";
|
|
1299
|
+
}
|
|
1300
|
+
endpointOverride(provider) {
|
|
1301
|
+
const variables = {
|
|
1302
|
+
anthropic: ["ANTHROPIC_BASE_URL"],
|
|
1303
|
+
openai: ["OPENAI_BASE_URL"],
|
|
1304
|
+
meta: ["META_BASE_URL"],
|
|
1305
|
+
gemini: ["GEMINI_BASE_URL"],
|
|
1306
|
+
qwen: ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID"]
|
|
1307
|
+
};
|
|
1308
|
+
return (variables[provider] ?? []).some((name) => this.environment[name]?.trim());
|
|
1309
|
+
}
|
|
1310
|
+
async inspect(provider) {
|
|
1311
|
+
if (provider === "vertex")
|
|
1312
|
+
return { source: "environment", configured: vertexConfigured(this.environment) };
|
|
1313
|
+
if (provider === "bedrock")
|
|
1314
|
+
return this.inspectBedrock();
|
|
1315
|
+
if (provider === "azure-openai")
|
|
1316
|
+
return this.inspectAzure();
|
|
1317
|
+
if (this.environmentKey(provider) && !(provider === "qwen" && this.qwenManaged))
|
|
1318
|
+
return { source: "environment", configured: true };
|
|
1319
|
+
if (this.endpointOverride(provider) && !(provider === "qwen" && this.qwenOverrideAccepted))
|
|
1320
|
+
return { source: "blocked", configured: false };
|
|
1321
|
+
if (this.temporary.has(provider))
|
|
1322
|
+
return { source: "temporary", configured: true };
|
|
1323
|
+
try {
|
|
1324
|
+
return await this.saved(provider) ? { source: "keychain", configured: true } : { source: "missing", configured: false };
|
|
1325
|
+
} catch {
|
|
1326
|
+
return { source: "unavailable", configured: false };
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
async inspectBedrock() {
|
|
1330
|
+
let runtime;
|
|
1331
|
+
try {
|
|
1332
|
+
runtime = bedrockRuntime(this.environment);
|
|
1333
|
+
} catch {
|
|
1334
|
+
return { source: "environment", configured: false };
|
|
1335
|
+
}
|
|
1336
|
+
if (runtime !== "openai")
|
|
1337
|
+
return { source: "environment", configured: bedrockConfigured(this.environment) };
|
|
1338
|
+
try {
|
|
1339
|
+
bedrockOpenAIBaseURL(this.environment);
|
|
1340
|
+
} catch {
|
|
1341
|
+
return { source: "missing", configured: false };
|
|
1342
|
+
}
|
|
1343
|
+
return this.inspectSecret("bedrock");
|
|
1344
|
+
}
|
|
1345
|
+
async inspectAzure() {
|
|
1346
|
+
try {
|
|
1347
|
+
azureOpenAIEndpoint(this.environment);
|
|
1348
|
+
azureOpenAIApiVersion(this.environment);
|
|
1349
|
+
azureOpenAIDeployments(this.environment);
|
|
1350
|
+
} catch {
|
|
1351
|
+
return { source: "environment", configured: false };
|
|
1352
|
+
}
|
|
1353
|
+
return this.inspectSecret("azure-openai");
|
|
1354
|
+
}
|
|
1355
|
+
async inspectSecret(provider) {
|
|
1356
|
+
if (this.environmentKey(provider))
|
|
1357
|
+
return { source: "environment", configured: true };
|
|
1358
|
+
if (this.temporary.has(provider))
|
|
1359
|
+
return { source: "temporary", configured: true };
|
|
1360
|
+
try {
|
|
1361
|
+
return await this.saved(provider) ? { source: "keychain", configured: true } : { source: "missing", configured: false };
|
|
1362
|
+
} catch {
|
|
1363
|
+
return { source: "unavailable", configured: false };
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
async configure(provider, input) {
|
|
1367
|
+
if (provider === "vertex") {
|
|
1368
|
+
this.write(`Vertex uses Google Application Default Credentials. Configure ADC, GOOGLE_CLOUD_PROJECT and VERTEX_LOCATION in the launching environment; no API key is stored here.
|
|
1369
|
+
`);
|
|
1370
|
+
return vertexConfigured(this.environment);
|
|
1371
|
+
}
|
|
1372
|
+
if (provider === "bedrock") {
|
|
1373
|
+
let runtime;
|
|
1374
|
+
try {
|
|
1375
|
+
runtime = bedrockRuntime(this.environment);
|
|
1376
|
+
} catch {
|
|
1377
|
+
this.write(`BEDROCK_RUNTIME must be converse or openai.
|
|
1378
|
+
`);
|
|
1379
|
+
return false;
|
|
1380
|
+
}
|
|
1381
|
+
if (runtime !== "openai") {
|
|
1382
|
+
this.write(`Amazon Bedrock Converse uses the AWS credential chain. Set AWS_REGION or AWS_DEFAULT_REGION in the launching environment. Optional AWS_PROFILE selects a profile. No API key is stored here, and credentials are not checked.
|
|
1383
|
+
`);
|
|
1384
|
+
return bedrockConfigured(this.environment);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
if (provider === "azure-openai") {
|
|
1388
|
+
try {
|
|
1389
|
+
azureOpenAIEndpoint(this.environment);
|
|
1390
|
+
azureOpenAIApiVersion(this.environment);
|
|
1391
|
+
azureOpenAIDeployments(this.environment);
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
this.write(`${error instanceof Error ? error.message : "Azure OpenAI route is not configured."}
|
|
1394
|
+
`);
|
|
1395
|
+
return false;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
for (;; ) {
|
|
1399
|
+
try {
|
|
1400
|
+
return await this.configureOnce(provider, input);
|
|
1401
|
+
} catch (error) {
|
|
1402
|
+
if (!(error instanceof CredentialSetupError) && !(error instanceof Error && error.name === "AbortError"))
|
|
1403
|
+
throw error;
|
|
1404
|
+
this.write(error instanceof CredentialSetupError ? `${error.message}
|
|
1405
|
+
` : `Key entry cancelled.
|
|
1406
|
+
`);
|
|
1407
|
+
const action = await input.select("Credentials / Recovery", [
|
|
1408
|
+
{ value: "temporary", label: "Use a temporary key", detail: "Enter a key for this CLI session only" },
|
|
1409
|
+
{ value: "retry", label: "Retry credential setup" },
|
|
1410
|
+
{ value: "cancel", label: "Cancel setup" }
|
|
1411
|
+
]);
|
|
1412
|
+
if (!action || action === "cancel")
|
|
1413
|
+
return false;
|
|
1414
|
+
if (action === "temporary") {
|
|
1415
|
+
try {
|
|
1416
|
+
return await this.configureOnce(provider, input, "temporary");
|
|
1417
|
+
} catch (retryError) {
|
|
1418
|
+
if (!(retryError instanceof CredentialSetupError) && !(retryError instanceof Error && retryError.name === "AbortError"))
|
|
1419
|
+
throw retryError;
|
|
1420
|
+
this.write(`Temporary key entry was not completed. Try again or go back.
|
|
1421
|
+
`);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
async configureOnce(provider, input, mode) {
|
|
1428
|
+
if (provider !== "qwen" && this.environmentKey(provider)) {
|
|
1429
|
+
this.write(`An environment key takes precedence. Remove it from the launching shell to use managed credentials.
|
|
1430
|
+
`);
|
|
1431
|
+
}
|
|
1432
|
+
const action = mode ?? await input.select(`Credentials / ${provider}`, [
|
|
1433
|
+
{ value: "save", label: "Save or replace in system keychain" },
|
|
1434
|
+
{ value: "temporary", label: "Temporary key for this CLI session" },
|
|
1435
|
+
{ value: "delete", label: "Remove saved and temporary key" },
|
|
1436
|
+
{ value: "cancel", label: "Back" }
|
|
1437
|
+
]);
|
|
1438
|
+
if (!action || action === "cancel")
|
|
1439
|
+
return false;
|
|
1440
|
+
if (action === "delete") {
|
|
1441
|
+
const confirm = await input.select(`Remove managed key for ${provider}?`, [
|
|
1442
|
+
{ value: false, label: "Keep key" },
|
|
1443
|
+
{ value: true, label: "Remove key" }
|
|
1444
|
+
]);
|
|
1445
|
+
if (!confirm)
|
|
1446
|
+
return false;
|
|
1447
|
+
try {
|
|
1448
|
+
await (await this.entry(provider)).deleteCredential();
|
|
1449
|
+
this.write(`Saved key removed (or already absent).
|
|
1450
|
+
`);
|
|
1451
|
+
} catch {
|
|
1452
|
+
this.write(`Saved key could not be removed: secure storage is unavailable or locked.
|
|
1453
|
+
`);
|
|
1454
|
+
}
|
|
1455
|
+
this.temporary.delete(provider);
|
|
1456
|
+
if (provider === "qwen") {
|
|
1457
|
+
this.qwenManaged = false;
|
|
1458
|
+
this.qwenOverrideAccepted = false;
|
|
1459
|
+
}
|
|
1460
|
+
this.revision++;
|
|
1461
|
+
this.write(`Temporary key cleared. Environment credentials are unchanged.
|
|
1462
|
+
`);
|
|
1463
|
+
return true;
|
|
1464
|
+
}
|
|
1465
|
+
const connection = provider === "qwen" ? await selectQwenConnection(input) : undefined;
|
|
1466
|
+
if (provider === "qwen" && !connection)
|
|
1467
|
+
return false;
|
|
1468
|
+
if (connection)
|
|
1469
|
+
this.write(`Selected Qwen destination: ${qwenEndpoint(connection)}
|
|
1470
|
+
This connection will replace Qwen environment settings for this CLI session.
|
|
1471
|
+
`);
|
|
1472
|
+
let target;
|
|
1473
|
+
if (action === "save") {
|
|
1474
|
+
try {
|
|
1475
|
+
target = await this.entry(provider);
|
|
1476
|
+
} catch {
|
|
1477
|
+
throw new CredentialSetupError("Secure storage is unavailable. Unlock it and retry, or choose temporary use.");
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
let secret = await input.secret("API key (hidden; Enter submits, Ctrl+C cancels): ");
|
|
1481
|
+
if (!secret)
|
|
1482
|
+
return false;
|
|
1483
|
+
try {
|
|
1484
|
+
secret = this.validate(secret);
|
|
1485
|
+
} catch {
|
|
1486
|
+
throw new CredentialSetupError("Invalid API key. Enter printable characters without whitespace.");
|
|
1487
|
+
}
|
|
1488
|
+
if (connection)
|
|
1489
|
+
secret = JSON.stringify({ version: 1, key: secret, connection });
|
|
1490
|
+
if (action === "save") {
|
|
1491
|
+
try {
|
|
1492
|
+
await target.setPassword(secret);
|
|
1493
|
+
} catch {
|
|
1494
|
+
throw new CredentialSetupError("API key was not saved: secure storage is unavailable or locked. No plaintext fallback was used.");
|
|
1495
|
+
}
|
|
1496
|
+
this.temporary.delete(provider);
|
|
1497
|
+
this.write(`API key saved in the system keychain.
|
|
1498
|
+
`);
|
|
1499
|
+
} else {
|
|
1500
|
+
this.temporary.set(provider, secret);
|
|
1501
|
+
this.write(`API key is available only for this CLI session.
|
|
1502
|
+
`);
|
|
1503
|
+
}
|
|
1504
|
+
if (connection) {
|
|
1505
|
+
this.qwenManaged = true;
|
|
1506
|
+
this.qwenOverrideAccepted = true;
|
|
1507
|
+
}
|
|
1508
|
+
this.revision++;
|
|
1509
|
+
return true;
|
|
1510
|
+
}
|
|
1511
|
+
async managedSecret(provider, input) {
|
|
1512
|
+
let key = this.temporary.get(provider);
|
|
1513
|
+
if (!key) {
|
|
1514
|
+
try {
|
|
1515
|
+
key = await this.saved(provider);
|
|
1516
|
+
} catch {
|
|
1517
|
+
this.write(`Secure storage is unavailable or locked; temporary use remains available.
|
|
1518
|
+
`);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
if (!key) {
|
|
1522
|
+
this.write(`No API key available for ${provider}.
|
|
1523
|
+
`);
|
|
1524
|
+
if (!await this.configure(provider, input))
|
|
1525
|
+
throw new CredentialSetupError("Credential setup cancelled. No provider request was sent.");
|
|
1526
|
+
key = this.temporary.get(provider) ?? await this.saved(provider);
|
|
1527
|
+
}
|
|
1528
|
+
if (!key)
|
|
1529
|
+
throw new CredentialSetupError("No API key available. No provider request was sent.");
|
|
1530
|
+
return key;
|
|
1531
|
+
}
|
|
1532
|
+
async bedrockProviderEnvironment(input) {
|
|
1533
|
+
let runtime;
|
|
1534
|
+
try {
|
|
1535
|
+
runtime = bedrockRuntime(this.environment);
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
throw new CredentialSetupError(error instanceof Error ? error.message : "BEDROCK_RUNTIME must be converse or openai.");
|
|
1538
|
+
}
|
|
1539
|
+
if (runtime !== "openai") {
|
|
1540
|
+
try {
|
|
1541
|
+
bedrockRegion(this.environment);
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
throw new CredentialSetupError(error instanceof Error ? error.message : "Bedrock requires a region.");
|
|
1544
|
+
}
|
|
1545
|
+
this.sources.set("bedrock", "environment");
|
|
1546
|
+
return { ...this.environment };
|
|
1547
|
+
}
|
|
1548
|
+
try {
|
|
1549
|
+
bedrockOpenAIBaseURL(this.environment);
|
|
1550
|
+
} catch (error) {
|
|
1551
|
+
throw new CredentialSetupError(error instanceof Error ? error.message : "BEDROCK_OPENAI_BASE_URL is required.");
|
|
1552
|
+
}
|
|
1553
|
+
if (this.environmentKey("bedrock")) {
|
|
1554
|
+
this.sources.set("bedrock", "environment");
|
|
1555
|
+
return { ...this.environment };
|
|
1556
|
+
}
|
|
1557
|
+
const key = await this.managedSecret("bedrock", input);
|
|
1558
|
+
this.sources.set("bedrock", this.temporary.has("bedrock") ? "temporary" : "keychain");
|
|
1559
|
+
return { ...this.environment, BEDROCK_API_KEY: key };
|
|
1560
|
+
}
|
|
1561
|
+
async azureProviderEnvironment(input) {
|
|
1562
|
+
try {
|
|
1563
|
+
azureOpenAIEndpoint(this.environment);
|
|
1564
|
+
azureOpenAIApiVersion(this.environment);
|
|
1565
|
+
azureOpenAIDeployments(this.environment);
|
|
1566
|
+
} catch (error) {
|
|
1567
|
+
throw new CredentialSetupError(error instanceof Error ? error.message : "Azure OpenAI route is not configured.");
|
|
1568
|
+
}
|
|
1569
|
+
if (this.environmentKey("azure-openai")) {
|
|
1570
|
+
this.sources.set("azure-openai", "environment");
|
|
1571
|
+
return { ...this.environment };
|
|
1572
|
+
}
|
|
1573
|
+
const key = await this.managedSecret("azure-openai", input);
|
|
1574
|
+
this.sources.set("azure-openai", this.temporary.has("azure-openai") ? "temporary" : "keychain");
|
|
1575
|
+
return { ...this.environment, AZURE_OPENAI_API_KEY: key };
|
|
1576
|
+
}
|
|
1577
|
+
async providerEnvironment(provider, input) {
|
|
1578
|
+
if (provider === "vertex") {
|
|
1579
|
+
vertexRoute(this.environment);
|
|
1580
|
+
this.sources.set(provider, "environment");
|
|
1581
|
+
return { ...this.environment };
|
|
1582
|
+
}
|
|
1583
|
+
if (provider === "bedrock")
|
|
1584
|
+
return this.bedrockProviderEnvironment(input);
|
|
1585
|
+
if (provider === "azure-openai")
|
|
1586
|
+
return this.azureProviderEnvironment(input);
|
|
1587
|
+
if (this.environmentKey(provider) && !(provider === "qwen" && this.qwenManaged)) {
|
|
1588
|
+
this.destinations.delete(provider);
|
|
1589
|
+
this.sources.set(provider, "environment");
|
|
1590
|
+
return { ...this.environment };
|
|
1591
|
+
}
|
|
1592
|
+
if (provider !== "qwen" && this.endpointOverride(provider)) {
|
|
1593
|
+
throw new CredentialSetupError("Managed keys require the provider's default endpoint. Remove endpoint overrides or supply an explicit environment key.");
|
|
1594
|
+
}
|
|
1595
|
+
let key = this.temporary.get(provider);
|
|
1596
|
+
if (!key) {
|
|
1597
|
+
try {
|
|
1598
|
+
key = await this.saved(provider);
|
|
1599
|
+
} catch {
|
|
1600
|
+
this.write(`Secure storage is unavailable or locked; temporary use remains available.
|
|
1601
|
+
`);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
if (!key) {
|
|
1605
|
+
this.write(`No API key available for ${provider}.
|
|
1606
|
+
`);
|
|
1607
|
+
if (!await this.configure(provider, input))
|
|
1608
|
+
throw new CredentialSetupError("Credential setup cancelled. No provider request was sent.");
|
|
1609
|
+
key = this.temporary.get(provider) ?? await this.saved(provider);
|
|
1610
|
+
}
|
|
1611
|
+
if (!key)
|
|
1612
|
+
throw new CredentialSetupError("No API key available. No provider request was sent.");
|
|
1613
|
+
if (provider === "qwen") {
|
|
1614
|
+
const record = decodeQwenCredential(key);
|
|
1615
|
+
const endpoint = qwenEndpoint(record.connection);
|
|
1616
|
+
if (this.endpointOverride(provider) && !this.qwenOverrideAccepted) {
|
|
1617
|
+
const useManaged = await input.select("Qwen / Environment conflicts with saved connection", [
|
|
1618
|
+
{ value: false, label: "Cancel; keep environment settings" },
|
|
1619
|
+
{ value: true, label: "Use saved connection for this session", detail: endpoint }
|
|
1620
|
+
]);
|
|
1621
|
+
if (!useManaged)
|
|
1622
|
+
throw new CredentialSetupError("Qwen connection selection cancelled. No provider request was sent.");
|
|
1623
|
+
this.qwenOverrideAccepted = true;
|
|
1624
|
+
}
|
|
1625
|
+
const env = { ...this.environment };
|
|
1626
|
+
for (const name2 of ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID", "QWEN_API_KEY", "DASHSCOPE_API_KEY"])
|
|
1627
|
+
delete env[name2];
|
|
1628
|
+
this.destinations.set(provider, endpoint);
|
|
1629
|
+
env.QWEN_BASE_URL = endpoint;
|
|
1630
|
+
env.DASHSCOPE_API_KEY = record.key;
|
|
1631
|
+
this.sources.set(provider, this.temporary.has(provider) ? "temporary" : "keychain");
|
|
1632
|
+
return env;
|
|
1633
|
+
}
|
|
1634
|
+
this.sources.set(provider, this.temporary.has(provider) ? "temporary" : "keychain");
|
|
1635
|
+
const name = providerDescriptor(provider).credentialNames[0];
|
|
1636
|
+
return { ...this.environment, [name]: key };
|
|
1637
|
+
}
|
|
1638
|
+
clear() {
|
|
1639
|
+
this.destinations.clear();
|
|
1640
|
+
this.temporary.clear();
|
|
1641
|
+
this.sources.clear();
|
|
1642
|
+
this.qwenManaged = false;
|
|
1643
|
+
this.qwenOverrideAccepted = false;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
async function credentialModel(config, env, modelFactory) {
|
|
1647
|
+
const { createProviderModel: createProviderModel2 } = await import("./config-hw78440t.js");
|
|
1648
|
+
const { wrapLanguageModel } = await import("@zhivex-ai/core");
|
|
1649
|
+
const secrets = providerDescriptor(config.provider).credentialNames.map((name) => env[name]).filter((value) => !!value);
|
|
1650
|
+
const safeError = (error) => {
|
|
1651
|
+
let message = error instanceof Error ? error.message : "Provider request failed.";
|
|
1652
|
+
for (const secret of secrets)
|
|
1653
|
+
message = message.split(secret).join("[REDACTED]");
|
|
1654
|
+
const safe2 = new Error(message);
|
|
1655
|
+
if (error instanceof Error && error.name === "AbortError")
|
|
1656
|
+
safe2.name = "AbortError";
|
|
1657
|
+
return safe2;
|
|
1658
|
+
};
|
|
1659
|
+
const model = (modelFactory ?? createProviderModel2)(config, env);
|
|
1660
|
+
return wrapLanguageModel(model, [{
|
|
1661
|
+
name: "cli-credential-errors",
|
|
1662
|
+
wrapGenerate: async (_context, next) => {
|
|
1663
|
+
try {
|
|
1664
|
+
return await next();
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
throw safeError(error);
|
|
1667
|
+
}
|
|
1668
|
+
},
|
|
1669
|
+
wrapStream: async (_context, next) => {
|
|
1670
|
+
let events;
|
|
1671
|
+
try {
|
|
1672
|
+
events = await next();
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
throw safeError(error);
|
|
1675
|
+
}
|
|
1676
|
+
return async function* () {
|
|
1677
|
+
try {
|
|
1678
|
+
for await (const event of events) {
|
|
1679
|
+
if (event.type === "error")
|
|
1680
|
+
throw safeError(event.error);
|
|
1681
|
+
yield event;
|
|
1682
|
+
}
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
throw safeError(error);
|
|
1685
|
+
}
|
|
1686
|
+
}();
|
|
1687
|
+
}
|
|
1688
|
+
}]);
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// packages/core/src/cli/configured-harness.ts
|
|
1692
|
+
import path from "node:path";
|
|
1693
|
+
var createConfiguredHarness = async (options, extraProfiles = [], persistedRoutes, credentials) => {
|
|
1694
|
+
const routes = persistedRoutes ?? resolvedRouting(options);
|
|
1695
|
+
const resolvedConfig = resolveHarnessConfig(options);
|
|
1696
|
+
if (options.usageLimitUsd !== undefined && resolvedConfig.costBudget)
|
|
1697
|
+
throw new CliUsageError("Choose one monetary policy: --usage-limit-usd or the legacy cost budget.");
|
|
1698
|
+
assertRoutePricingIsSafe(routes, resolvedConfig.costBudget);
|
|
1699
|
+
const profiles = [...new Set([
|
|
1700
|
+
...options.subagentProfiles ?? [],
|
|
1701
|
+
...extraProfiles,
|
|
1702
|
+
...routes.keys()
|
|
1703
|
+
])];
|
|
1704
|
+
const quietTelemetry = options.json || options.jsonl;
|
|
1705
|
+
const providerEnv = credentials ? await credentials.store.providerEnvironment(resolvedConfig.provider, credentials.input) : undefined;
|
|
1706
|
+
const transportEnv = { ...process.env };
|
|
1707
|
+
const bindTransport = (env) => {
|
|
1708
|
+
for (const name of ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID"]) {
|
|
1709
|
+
if (env[name] === undefined)
|
|
1710
|
+
delete transportEnv[name];
|
|
1711
|
+
else
|
|
1712
|
+
transportEnv[name] = env[name];
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
if (providerEnv && resolvedConfig.provider === "qwen")
|
|
1716
|
+
bindTransport(providerEnv);
|
|
1717
|
+
const routeModels = {};
|
|
1718
|
+
for (const [role, route] of routes) {
|
|
1719
|
+
const routeEnv = credentials ? await credentials.store.providerEnvironment(route.provider, credentials.input) : process.env;
|
|
1720
|
+
if (route.provider === "qwen")
|
|
1721
|
+
bindTransport(routeEnv);
|
|
1722
|
+
routeModels[role] = credentials ? await credentialModel(route, routeEnv) : createProviderModel(route, routeEnv);
|
|
1723
|
+
}
|
|
1724
|
+
const compactionEnv = resolvedConfig.compaction.model && credentials ? await credentials.store.providerEnvironment(resolvedConfig.compaction.model.provider, credentials.input) : undefined;
|
|
1725
|
+
if (compactionEnv && resolvedConfig.compaction.model?.provider === "qwen")
|
|
1726
|
+
bindTransport(compactionEnv);
|
|
1727
|
+
const compactionModelInstance = resolvedConfig.compaction.model && compactionEnv ? await credentialModel(resolvedConfig.compaction.model, compactionEnv) : undefined;
|
|
1728
|
+
const harness = await createHarness({
|
|
1729
|
+
...options,
|
|
1730
|
+
...{ projectMemory: options.projectMemory ?? true },
|
|
1731
|
+
usageAccounting: {
|
|
1732
|
+
...options.pricingFile ? { pricing: usagePricingSchema.parse(JSON.parse((await readRegularFileNoFollow(path.resolve(options.pricingFile), { maxBytes: 128 * 1024, label: "Usage pricing" })).contents.toString("utf8"))) } : {},
|
|
1733
|
+
...options.usageLimitUsd !== undefined ? { limitUsd: options.usageLimitUsd } : {}
|
|
1734
|
+
},
|
|
1735
|
+
subagentProfiles: profiles,
|
|
1736
|
+
subagentModels: routeModels,
|
|
1737
|
+
...compactionModelInstance ? { compactionModelInstance } : {},
|
|
1738
|
+
...providerEnv ? { env: transportEnv, modelInstance: await credentialModel(resolvedConfig, providerEnv) } : {},
|
|
1739
|
+
onTelemetryEvent: orchestrationObserver(quietTelemetry)
|
|
1740
|
+
});
|
|
1741
|
+
return { harness, routes };
|
|
1742
|
+
};
|
|
1743
|
+
|
|
1744
|
+
export { CredentialSetupError, CliCredentials, credentialModel, resolvedRouting, assertRoutePricingIsSafe, withTemporaryHarnessProfiles, ToolActivity, compactToolResult, TerminalMarkdown, HARNESS_RESUME_METADATA_KEY, HARNESS_RESUME_METADATA_SCHEMA_VERSION, harnessConfigInput, persistedCliOptions, createHarnessResumeMetadata, readHarnessResumeConfig, readHarnessResumeRoutes, resumeCommand, annotateCliStreamError, cliStreamErrorSequence, terminalErrorMessage, summarizeApproval, approvalResponses, terminalApprovalResolver, printTerminalResult, flushToolActivity, streamSink, orchestrationObserver, createConfiguredHarness };
|