diff --git a/.github/workflows/stats.yml b/.github/workflows/stats.yml index fed03b68..188996aa 100644 --- a/.github/workflows/stats.yml +++ b/.github/workflows/stats.yml @@ -28,5 +28,5 @@ jobs: git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add STATS.md - git diff --staged --quiet || git commit -m "Update download stats $(date -I)" + git diff --staged --quiet || git commit -m "ignore: update download stats $(date -I)" git push diff --git a/README.md b/README.md index 24841799..cf2aa6fe 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

AI coding agent, built for the terminal.

- View docs + Discord npm Build status

@@ -76,4 +76,4 @@ The other confusingly named repo has no relation to this one. You can [read the --- -**Join our community** [YouTube](https://www.youtube.com/c/sst-dev) | [X.com](https://x.com/SST_dev) +**Join our community** [Discord](https://discord.gg/opencode) | [YouTube](https://www.youtube.com/c/sst-dev) | [X.com](https://x.com/SST_dev) diff --git a/STATS.md b/STATS.md index 256ffb5d..e1e0d5e5 100644 --- a/STATS.md +++ b/STATS.md @@ -1,10 +1,13 @@ # Download Stats -| Date | GitHub Downloads | npm Downloads | Total | -| ---------- | ---------------- | --------------- | --------------- | -| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) | -| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) | -| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) | -| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) | -| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) | -| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) | +| Date | GitHub Downloads | npm Downloads | Total | +| ---------- | ---------------- | --------------- | ---------------- | +| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) | +| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) | +| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) | +| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) | +| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) | +| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) | +| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) | +| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) | +| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) | diff --git a/bun.lock b/bun.lock index 0fec03e8..8066b54a 100644 --- a/bun.lock +++ b/bun.lock @@ -96,30 +96,22 @@ "sharp", "esbuild", ], - "patchedDependencies": { - "ai@4.3.16": "patches/ai@4.3.16.patch", - }, - "overrides": { - "zod": "3.24.2", - }, "catalog": { "@types/node": "22.13.9", - "ai": "4.3.16", + "ai": "5.0.0-beta.7", "typescript": "5.8.2", - "zod": "3.24.2", + "zod": "3.25.49", }, "packages": { "@ai-sdk/amazon-bedrock": ["@ai-sdk/amazon-bedrock@2.2.10", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "@smithy/eventstream-codec": "^4.0.1", "@smithy/util-utf8": "^4.0.0", "aws4fetch": "^1.0.20" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-icLGO7Q0NinnHIPgT+y1QjHVwH4HwV+brWbvM+FfCG2Afpa89PyKa3Ret91kGjZpBgM/xnj1B7K5eM+rRlsXQA=="], "@ai-sdk/anthropic": ["@ai-sdk/anthropic@1.2.12", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-YSzjlko7JvuiyQFmI9RN1tNZdEiZxc+6xld/0tq/VkJaHpEzGAb1yiNxxvmYVcjvfu/PcvCxAAYXmTYQQ63IHQ=="], - "@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="], + "@ai-sdk/gateway": ["@ai-sdk/gateway@1.0.0-beta.3", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.2" }, "peerDependencies": { "zod": "^3.25.49" } }, "sha512-g49gMSkXy94lYvl5LRh438OR/0JCG6ol0jV+iLot7cy5HLltZlGocEuauETBu4b10mDXOd7XIjTEZoQpYFMYLQ=="], - "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="], + "@ai-sdk/provider": ["@ai-sdk/provider@2.0.0-beta.1", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Z8SPncMtS3RsoXITmT7NVwrAq6M44dmw0DoUOYJqNNtCu8iMWuxB8Nxsoqpa0uEEy9R1V1ZThJAXTYgjTUxl3w=="], - "@ai-sdk/react": ["@ai-sdk/react@1.2.12", "", { "dependencies": { "@ai-sdk/provider-utils": "2.2.8", "@ai-sdk/ui-utils": "1.2.11", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.23.8" }, "optionalPeers": ["zod"] }, "sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g=="], - - "@ai-sdk/ui-utils": ["@ai-sdk/ui-utils@1.2.11", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w=="], + "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@3.0.0-beta.2", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.49" } }, "sha512-H4K+4weOVgWqrDDeAbQWoA4U5mN4WrQPHQFdH7ynQYcnhj/pzctU9Q6mGlR5ESMWxaXxazxlOblSITlXo9bahA=="], "@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="], @@ -467,8 +459,6 @@ "@types/debug": ["@types/debug@4.1.12", "", { "dependencies": { "@types/ms": "*" } }, "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ=="], - "@types/diff-match-patch": ["@types/diff-match-patch@1.0.36", "", {}, "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg=="], - "@types/estree": ["@types/estree@1.0.7", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="], "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], @@ -515,7 +505,7 @@ "acorn-walk": ["acorn-walk@8.3.2", "", {}, "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A=="], - "ai": ["ai@4.3.16", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "@ai-sdk/react": "1.2.12", "@ai-sdk/ui-utils": "1.2.11", "@opentelemetry/api": "1.9.0", "jsondiffpatch": "0.6.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.23.8" }, "optionalPeers": ["react"] }, "sha512-KUDwlThJ5tr2Vw0A1ZkbDKNME3wzWhuVfAOwIvFUzl1TPVDFAXDFTXio3p+jaKneB+dKNCvFFlolYmmgHttG1g=="], + "ai": ["ai@5.0.0-beta.7", "", { "dependencies": { "@ai-sdk/gateway": "1.0.0-beta.3", "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.2", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.49" } }, "sha512-oC4KzUJCQPMB7v9rCqL/rVk2ogZvI6lYiXfKjzPYHwa1zIgy329qqRLmAd3mKEDTTG6By1r0zasQu7FKmG+4gw=="], "ansi-align": ["ansi-align@3.0.1", "", { "dependencies": { "string-width": "^4.1.0" } }, "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w=="], @@ -733,8 +723,6 @@ "diff": ["diff@8.0.2", "", {}, "sha512-sSuxWU5j5SR9QQji/o2qMvqRNYRDOcBTgsJ/DeCf4iSN4gW+gNMXM7wFIP+fdXZxoNiAnHUTGjCr+TSWXdRDKg=="], - "diff-match-patch": ["diff-match-patch@1.0.5", "", {}, "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw=="], - "diff3": ["diff3@0.0.3", "", {}, "sha512-iSq8ngPOt0K53A6eVr4d5Kn6GNrM2nQZtC740pzIriHtn4pOQ2lyzEXQMBeVcWERN0ye7fhBsk9PbLLQOnUx/g=="], "direction": ["direction@2.0.1", "", { "bin": { "direction": "cli.js" } }, "sha512-9S6m9Sukh1cZNknO1CWAr2QAWsbKLafQiyM5gZ7VgXHeuaoUwffKN4q6NC4A/Mf9iiPlOXQEKW/Mv/mh9/3YFA=="], @@ -803,7 +791,7 @@ "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], - "eventsource-parser": ["eventsource-parser@3.0.2", "", {}, "sha512-6RxOBZ/cYgd8usLwsEl+EC09Au/9BcmCKYF2/xbml6DNczf7nv0MQb+7BA2F+li6//I+28VNlQR37XfQtcAJuA=="], + "eventsource-parser": ["eventsource-parser@3.0.3", "", {}, "sha512-nVpZkTMM9rF6AQ9gPJpFsNAMt48wIzB5TQgiTLdHiuO8XEDhUgZEhqKlZWXbIzo9VmJ/HvysHqEaVeD5v9TPvA=="], "exit-hook": ["exit-hook@2.2.1", "", {}, "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw=="], @@ -1025,8 +1013,6 @@ "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], - "jsondiffpatch": ["jsondiffpatch@0.6.0", "", { "dependencies": { "@types/diff-match-patch": "^1.0.36", "chalk": "^5.3.0", "diff-match-patch": "^1.0.5" }, "bin": { "jsondiffpatch": "bin/jsondiffpatch.js" } }, "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ=="], - "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], "klona": ["klona@2.0.6", "", {}, "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA=="], @@ -1343,8 +1329,6 @@ "rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="], - "react": ["react@19.1.0", "", {}, "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg=="], - "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], @@ -1529,8 +1513,6 @@ "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], - "swr": ["swr@2.3.3", "", { "dependencies": { "dequal": "^2.0.3", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-dshNvs3ExOqtZ6kJBaAsabhPdHyeY4P2cKwRCniDVifBMoG/SVI7tfLWqPXriVspf2Rg4tPzXJTnwaihIeFw2A=="], - "tar-fs": ["tar-fs@3.0.9", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-XF4w9Xp+ZQgifKakjZYmFdkLoSWd34VGKcsTCwlNWM7QG3ZbaxnTsaBwnjFZqHRf/rROxaR8rXnbtwdvaDI+lA=="], "tar-stream": ["tar-stream@3.1.7", "", { "dependencies": { "b4a": "^1.6.4", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ=="], @@ -1539,8 +1521,6 @@ "thread-stream": ["thread-stream@0.15.2", "", { "dependencies": { "real-require": "^0.1.0" } }, "sha512-UkEhKIg2pD+fjkHQKyJO3yoIvAP3N6RlNFt2dUhcS1FGvCD1cQa1M/PGknCLFIyZdtJOWQjejp7bdNqmN7zwdA=="], - "throttleit": ["throttleit@2.1.0", "", {}, "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw=="], - "tiny-inflate": ["tiny-inflate@1.0.3", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="], "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], @@ -1625,8 +1605,6 @@ "url": ["url@0.10.3", "", { "dependencies": { "punycode": "1.3.2", "querystring": "0.2.0" } }, "sha512-hzSUW2q06EqL1gKM/a+obYHLIO6ct2hwPuviqTTOcfFVc61UbfJ2Q32+uGL/HCPxKqrdGB5QUwIe7UqlDgwsOQ=="], - "use-sync-external-store": ["use-sync-external-store@1.5.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A=="], - "util": ["util@0.12.5", "", { "dependencies": { "inherits": "^2.0.3", "is-arguments": "^1.0.4", "is-generator-function": "^1.0.7", "is-typed-array": "^1.1.3", "which-typed-array": "^1.1.2" } }, "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA=="], "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], @@ -1703,7 +1681,7 @@ "youch": ["youch@3.3.4", "", { "dependencies": { "cookie": "^0.7.1", "mustache": "^4.2.0", "stacktracey": "^2.1.8" } }, "sha512-UeVBXie8cA35DS6+nBkls68xaBBXCye0CNznrhszZjTbRVnJKQuNsyLKBTTL4ln1o1rh2PKtv35twV7irj5SEg=="], - "zod": ["zod@3.24.2", "", {}, "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ=="], + "zod": ["zod@3.25.49", "", {}, "sha512-JMMPMy9ZBk3XFEdbM3iL1brx4NUSejd6xr3ELrrGEfGb355gjhiAWtG3K5o+AViV/3ZfkIrCzXsZn6SbLwTR8Q=="], "zod-openapi": ["zod-openapi@4.2.4", "", { "peerDependencies": { "zod": "^3.21.4" } }, "sha512-tsrQpbpqFCXqVXUzi3TPwFhuMtLN3oNZobOtYnK6/5VkXsNdnIgyNr4r8no4wmYluaxzN3F7iS+8xCW8BmMQ8g=="], @@ -1715,12 +1693,22 @@ "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "@ai-sdk/amazon-bedrock/@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="], + + "@ai-sdk/amazon-bedrock/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="], + "@ai-sdk/amazon-bedrock/aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], + "@ai-sdk/anthropic/@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="], + + "@ai-sdk/anthropic/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="], + "@ampproject/remapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], "@astrojs/mdx/@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.2", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.3.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "shiki": "^3.2.1", "smol-toml": "^1.3.1", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-bO35JbWpVvyKRl7cmSJD822e8YA8ThR/YbUsciWNA7yTcqpIAL2hJDToWP5KcZBWxGT6IOdOkHSXARSNZc4l/Q=="], + "@astrojs/sitemap/zod": ["zod@3.24.2", "", {}, "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ=="], + "@aws-crypto/crc32/tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], "@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], @@ -1739,6 +1727,8 @@ "@jridgewell/gen-mapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], + "@modelcontextprotocol/sdk/zod": ["zod@3.24.2", "", {}, "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ=="], + "@openauthjs/openauth/@standard-schema/spec": ["@standard-schema/spec@1.0.0-beta.3", "", {}, "sha512-0ifF3BjA1E8SY9C+nUew8RefNOIq0cDlYALPty4rhUm8Rrl6tCM8hBT4bhGhx7I7iXD0uAgt50lgo8dD73ACMw=="], "@openauthjs/openauth/aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], @@ -1775,10 +1765,14 @@ "astro/sharp": ["sharp@0.33.5", "", { "dependencies": { "color": "^4.2.3", "detect-libc": "^2.0.3", "semver": "^7.6.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.33.5", "@img/sharp-darwin-x64": "0.33.5", "@img/sharp-libvips-darwin-arm64": "1.0.4", "@img/sharp-libvips-darwin-x64": "1.0.4", "@img/sharp-libvips-linux-arm": "1.0.5", "@img/sharp-libvips-linux-arm64": "1.0.4", "@img/sharp-libvips-linux-s390x": "1.0.4", "@img/sharp-libvips-linux-x64": "1.0.4", "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", "@img/sharp-libvips-linuxmusl-x64": "1.0.4", "@img/sharp-linux-arm": "0.33.5", "@img/sharp-linux-arm64": "0.33.5", "@img/sharp-linux-s390x": "0.33.5", "@img/sharp-linux-x64": "0.33.5", "@img/sharp-linuxmusl-arm64": "0.33.5", "@img/sharp-linuxmusl-x64": "0.33.5", "@img/sharp-wasm32": "0.33.5", "@img/sharp-win32-ia32": "0.33.5", "@img/sharp-win32-x64": "0.33.5" } }, "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw=="], + "astro/zod": ["zod@3.24.2", "", {}, "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ=="], + "babel-plugin-jsx-dom-expressions/@babel/helper-module-imports": ["@babel/helper-module-imports@7.18.6", "", { "dependencies": { "@babel/types": "^7.18.6" } }, "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA=="], "bl/buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], + "eventsource/eventsource-parser": ["eventsource-parser@3.0.2", "", {}, "sha512-6RxOBZ/cYgd8usLwsEl+EC09Au/9BcmCKYF2/xbml6DNczf7nv0MQb+7BA2F+li6//I+28VNlQR37XfQtcAJuA=="], + "express/cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], "get-source/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], @@ -1791,8 +1785,12 @@ "miniflare/sharp": ["sharp@0.33.5", "", { "dependencies": { "color": "^4.2.3", "detect-libc": "^2.0.3", "semver": "^7.6.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.33.5", "@img/sharp-darwin-x64": "0.33.5", "@img/sharp-libvips-darwin-arm64": "1.0.4", "@img/sharp-libvips-darwin-x64": "1.0.4", "@img/sharp-libvips-linux-arm": "1.0.5", "@img/sharp-libvips-linux-arm64": "1.0.4", "@img/sharp-libvips-linux-s390x": "1.0.4", "@img/sharp-libvips-linux-x64": "1.0.4", "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", "@img/sharp-libvips-linuxmusl-x64": "1.0.4", "@img/sharp-linux-arm": "0.33.5", "@img/sharp-linux-arm64": "0.33.5", "@img/sharp-linux-s390x": "0.33.5", "@img/sharp-linux-x64": "0.33.5", "@img/sharp-linuxmusl-arm64": "0.33.5", "@img/sharp-linuxmusl-x64": "0.33.5", "@img/sharp-wasm32": "0.33.5", "@img/sharp-win32-ia32": "0.33.5", "@img/sharp-win32-x64": "0.33.5" } }, "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw=="], + "miniflare/zod": ["zod@3.22.3", "", {}, "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug=="], + "opencontrol/hono": ["hono@4.7.4", "", {}, "sha512-Pst8FuGqz3L7tFF+u9Pu70eI0xa5S3LPUmrNd5Jm8nTHze9FxLTK9Kaj5g/k4UcwuJSXTP65SyHOPLrffpcAJg=="], + "opencontrol/zod": ["zod@3.24.2", "", {}, "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ=="], + "opencontrol/zod-to-json-schema": ["zod-to-json-schema@3.24.3", "", { "peerDependencies": { "zod": "^3.24.1" } }, "sha512-HIAfWdYIt1sssHfYZFCXp4rU1w2r8hVVXYIlmoa0r0gABLs5di3RCqPU5DDROogVz1pAdYBaz7HK5n9pSUNs3A=="], "openid-client/jose": ["jose@4.15.9", "", {}, "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA=="], diff --git a/infra/app.ts b/infra/app.ts index 834936b7..caaea0e9 100644 --- a/infra/app.ts +++ b/infra/app.ts @@ -39,6 +39,8 @@ new sst.cloudflare.x.Astro("Web", { domain, path: "packages/web", environment: { + // For astro config + SST_STAGE: $app.stage, VITE_API_URL: api.url, }, }) diff --git a/opencode.json b/opencode.json index 57b94008..ff206980 100644 --- a/opencode.json +++ b/opencode.json @@ -1,5 +1,11 @@ { "$schema": "https://opencode.ai/config.json", + "mcp": { + "weather": { + "type": "local", + "command": ["opencode", "x", "@h1deya/mcp-server-weather"] + } + }, "experimental": { "hook": { "file_edited": { diff --git a/package.json b/package.json index 09248dcf..7a8c6b07 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "dev": "bun run packages/opencode/src/index.ts", "typecheck": "bun run --filter='*' typecheck", - "stainless": "bun run ./packages/opencode/src/index.ts serve ", + "stainless": "./scripts/stainless", "postinstall": "./scripts/hooks" }, "workspaces": { @@ -17,8 +17,8 @@ "catalog": { "typescript": "5.8.2", "@types/node": "22.13.9", - "zod": "3.24.2", - "ai": "4.3.16" + "zod": "3.25.49", + "ai": "5.0.0-beta.7" } }, "devDependencies": { @@ -31,10 +31,8 @@ }, "license": "MIT", "prettier": { - "semi": false - }, - "overrides": { - "zod": "3.24.2" + "semi": false, + "printWidth": 120 }, "trustedDependencies": [ "esbuild", diff --git a/packages/function/src/api.ts b/packages/function/src/api.ts index 701b9854..be6ef192 100644 --- a/packages/function/src/api.ts +++ b/packages/function/src/api.ts @@ -38,10 +38,7 @@ export class SyncServer extends DurableObject { async publish(key: string, content: any) { const sessionID = await this.getSessionID() - if ( - !key.startsWith(`session/info/${sessionID}`) && - !key.startsWith(`session/message/${sessionID}/`) - ) + if (!key.startsWith(`session/info/${sessionID}`) && !key.startsWith(`session/message/${sessionID}/`)) return new Response("Error: Invalid key", { status: 400 }) // store message @@ -184,8 +181,7 @@ export default { } const id = url.searchParams.get("id") console.log("share_poll", id) - if (!id) - return new Response("Error: Share ID is required", { status: 400 }) + if (!id) return new Response("Error: Share ID is required", { status: 400 }) const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id)) return stub.fetch(request) } @@ -193,8 +189,7 @@ export default { if (request.method === "GET" && method === "share_data") { const id = url.searchParams.get("id") console.log("share_data", id) - if (!id) - return new Response("Error: Share ID is required", { status: 400 }) + if (!id) return new Response("Error: Share ID is required", { status: 400 }) const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id)) const data = await stub.getData() diff --git a/packages/opencode/config.schema.json b/packages/opencode/config.schema.json deleted file mode 100644 index 35dfd6f1..00000000 --- a/packages/opencode/config.schema.json +++ /dev/null @@ -1,369 +0,0 @@ -{ - "type": "object", - "properties": { - "$schema": { - "type": "string", - "description": "JSON schema reference for configuration validation" - }, - "theme": { - "type": "string", - "description": "Theme name to use for the interface" - }, - "keybinds": { - "type": "object", - "properties": { - "leader": { - "type": "string", - "description": "Leader key for keybind combinations" - }, - "help": { - "type": "string", - "description": "Show help dialog" - }, - "editor_open": { - "type": "string", - "description": "Open external editor" - }, - "session_new": { - "type": "string", - "description": "Create a new session" - }, - "session_list": { - "type": "string", - "description": "List all sessions" - }, - "session_share": { - "type": "string", - "description": "Share current session" - }, - "session_interrupt": { - "type": "string", - "description": "Interrupt current session" - }, - "session_compact": { - "type": "string", - "description": "Toggle compact mode for session" - }, - "tool_details": { - "type": "string", - "description": "Show tool details" - }, - "model_list": { - "type": "string", - "description": "List available models" - }, - "theme_list": { - "type": "string", - "description": "List available themes" - }, - "project_init": { - "type": "string", - "description": "Initialize project configuration" - }, - "input_clear": { - "type": "string", - "description": "Clear input field" - }, - "input_paste": { - "type": "string", - "description": "Paste from clipboard" - }, - "input_submit": { - "type": "string", - "description": "Submit input" - }, - "input_newline": { - "type": "string", - "description": "Insert newline in input" - }, - "history_previous": { - "type": "string", - "description": "Navigate to previous history item" - }, - "history_next": { - "type": "string", - "description": "Navigate to next history item" - }, - "messages_page_up": { - "type": "string", - "description": "Scroll messages up by one page" - }, - "messages_page_down": { - "type": "string", - "description": "Scroll messages down by one page" - }, - "messages_half_page_up": { - "type": "string", - "description": "Scroll messages up by half page" - }, - "messages_half_page_down": { - "type": "string", - "description": "Scroll messages down by half page" - }, - "messages_previous": { - "type": "string", - "description": "Navigate to previous message" - }, - "messages_next": { - "type": "string", - "description": "Navigate to next message" - }, - "messages_first": { - "type": "string", - "description": "Navigate to first message" - }, - "messages_last": { - "type": "string", - "description": "Navigate to last message" - }, - "app_exit": { - "type": "string", - "description": "Exit the application" - } - }, - "additionalProperties": false, - "description": "Custom keybind configurations" - }, - "autoshare": { - "type": "boolean", - "description": "Share newly created sessions automatically" - }, - "autoupdate": { - "type": "boolean", - "description": "Automatically update to the latest version" - }, - "disabled_providers": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Disable providers that are loaded automatically" - }, - "model": { - "type": "string", - "description": "Model to use in the format of provider/model, eg anthropic/claude-2" - }, - "provider": { - "type": "object", - "additionalProperties": { - "type": "object", - "properties": { - "api": { - "type": "string" - }, - "name": { - "type": "string" - }, - "env": { - "type": "array", - "items": { - "type": "string" - } - }, - "id": { - "type": "string" - }, - "npm": { - "type": "string" - }, - "models": { - "type": "object", - "additionalProperties": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "attachment": { - "type": "boolean" - }, - "reasoning": { - "type": "boolean" - }, - "temperature": { - "type": "boolean" - }, - "tool_call": { - "type": "boolean" - }, - "cost": { - "type": "object", - "properties": { - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "cache_read": { - "type": "number" - }, - "cache_write": { - "type": "number" - } - }, - "required": ["input", "output"], - "additionalProperties": false - }, - "limit": { - "type": "object", - "properties": { - "context": { - "type": "number" - }, - "output": { - "type": "number" - } - }, - "required": ["context", "output"], - "additionalProperties": false - }, - "id": { - "type": "string" - }, - "options": { - "type": "object", - "additionalProperties": {} - } - }, - "additionalProperties": false - } - }, - "options": { - "type": "object", - "additionalProperties": {} - } - }, - "required": ["models"], - "additionalProperties": false - }, - "description": "Custom provider configurations and model overrides" - }, - "mcp": { - "type": "object", - "additionalProperties": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "const": "local", - "description": "Type of MCP server connection" - }, - "command": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Command and arguments to run the MCP server" - }, - "environment": { - "type": "object", - "additionalProperties": { - "type": "string" - }, - "description": "Environment variables to set when running the MCP server" - }, - "enabled": { - "type": "boolean", - "description": "Enable or disable the MCP server on startup" - } - }, - "required": ["type", "command"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "const": "remote", - "description": "Type of MCP server connection" - }, - "url": { - "type": "string", - "description": "URL of the remote MCP server" - }, - "enabled": { - "type": "boolean", - "description": "Enable or disable the MCP server on startup" - } - }, - "required": ["type", "url"], - "additionalProperties": false - } - ] - }, - "description": "MCP (Model Context Protocol) server configurations" - }, - "instructions": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Additional instruction files or patterns to include" - }, - "experimental": { - "type": "object", - "properties": { - "hook": { - "type": "object", - "properties": { - "file_edited": { - "type": "object", - "additionalProperties": { - "type": "array", - "items": { - "type": "object", - "properties": { - "command": { - "type": "array", - "items": { - "type": "string" - } - }, - "environment": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "required": ["command"], - "additionalProperties": false - } - } - }, - "session_completed": { - "type": "array", - "items": { - "type": "object", - "properties": { - "command": { - "type": "array", - "items": { - "type": "string" - } - }, - "environment": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "required": ["command"], - "additionalProperties": false - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false, - "$schema": "http://json-schema.org/draft-07/schema#" -} diff --git a/packages/opencode/script/publish.ts b/packages/opencode/script/publish.ts index 3f4c2005..53332d20 100755 --- a/packages/opencode/script/publish.ts +++ b/packages/opencode/script/publish.ts @@ -57,8 +57,7 @@ for (const [os, arch] of targets) { 2, ), ) - if (!dry) - await $`cd dist/${name} && bun publish --access public --tag ${npmTag}` + if (!dry) await $`cd dist/${name} && bun publish --access public --tag ${npmTag}` optionalDependencies[name] = version } @@ -82,8 +81,7 @@ await Bun.file(`./dist/${pkg.name}/package.json`).write( 2, ), ) -if (!dry) - await $`cd ./dist/${pkg.name} && bun publish --access public --tag ${npmTag}` +if (!dry) await $`cd ./dist/${pkg.name} && bun publish --access public --tag ${npmTag}` if (!snapshot) { // Github Release @@ -91,15 +89,11 @@ if (!snapshot) { await $`cd dist/${key}/bin && zip -r ../../${key}.zip *` } - const previous = await fetch( - "https://api.github.com/repos/sst/opencode/releases/latest", - ) + const previous = await fetch("https://api.github.com/repos/sst/opencode/releases/latest") .then((res) => res.json()) .then((data) => data.tag_name) - const commits = await fetch( - `https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`, - ) + const commits = await fetch(`https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`) .then((res) => res.json()) .then((data) => data.commits || []) @@ -109,6 +103,7 @@ if (!snapshot) { const lower = x.toLowerCase() return ( !lower.includes("ignore:") && + !lower.includes("chore:") && !lower.includes("ci:") && !lower.includes("wip:") && !lower.includes("docs:") && @@ -117,26 +112,13 @@ if (!snapshot) { }) .join("\n") - if (!dry) - await $`gh release create v${version} --title "v${version}" --notes ${notes} ./dist/*.zip` + if (!dry) await $`gh release create v${version} --title "v${version}" --notes ${notes} ./dist/*.zip` // Calculate SHA values - const arm64Sha = - await $`sha256sum ./dist/opencode-linux-arm64.zip | cut -d' ' -f1` - .text() - .then((x) => x.trim()) - const x64Sha = - await $`sha256sum ./dist/opencode-linux-x64.zip | cut -d' ' -f1` - .text() - .then((x) => x.trim()) - const macX64Sha = - await $`sha256sum ./dist/opencode-darwin-x64.zip | cut -d' ' -f1` - .text() - .then((x) => x.trim()) - const macArm64Sha = - await $`sha256sum ./dist/opencode-darwin-arm64.zip | cut -d' ' -f1` - .text() - .then((x) => x.trim()) + const arm64Sha = await $`sha256sum ./dist/opencode-linux-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim()) + const x64Sha = await $`sha256sum ./dist/opencode-linux-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim()) + const macX64Sha = await $`sha256sum ./dist/opencode-darwin-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim()) + const macArm64Sha = await $`sha256sum ./dist/opencode-darwin-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim()) // AUR package const pkgbuild = [ @@ -170,9 +152,7 @@ if (!snapshot) { for (const pkg of ["opencode", "opencode-bin"]) { await $`rm -rf ./dist/aur-${pkg}` await $`git clone ssh://aur@aur.archlinux.org/${pkg}.git ./dist/aur-${pkg}` - await Bun.file(`./dist/aur-${pkg}/PKGBUILD`).write( - pkgbuild.replace("${pkg}", pkg), - ) + await Bun.file(`./dist/aur-${pkg}/PKGBUILD`).write(pkgbuild.replace("${pkg}", pkg)) await $`cd ./dist/aur-${pkg} && makepkg --printsrcinfo > .SRCINFO` await $`cd ./dist/aur-${pkg} && git add PKGBUILD .SRCINFO` await $`cd ./dist/aur-${pkg} && git commit -m "Update to v${version}"` diff --git a/packages/opencode/script/schema.ts b/packages/opencode/script/schema.ts index 1c0067c7..008c168c 100755 --- a/packages/opencode/script/schema.ts +++ b/packages/opencode/script/schema.ts @@ -4,5 +4,32 @@ import "zod-openapi/extend" import { Config } from "../src/config/config" import { zodToJsonSchema } from "zod-to-json-schema" -const result = zodToJsonSchema(Config.Info) -await Bun.write("config.schema.json", JSON.stringify(result, null, 2)) +const file = process.argv[2] + +const result = zodToJsonSchema(Config.Info, { + /** + * We'll use the `default` values of the field as the only value in `examples`. + * This will ensure no docs are needed to be read, as the configuration is + * self-documenting. + * + * See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.9.5 + */ + postProcess(jsonSchema) { + const schema = jsonSchema as typeof jsonSchema & { + examples?: unknown[] + } + if (schema && typeof schema === "object" && "type" in schema && schema.type === "string" && schema?.default) { + if (!schema.examples) { + schema.examples = [schema.default] + } + + schema.description = [schema.description || "", `default: \`${schema.default}\``] + .filter(Boolean) + .join("\n\n") + .trim() + } + + return jsonSchema + }, +}) +await Bun.write(file, JSON.stringify(result, null, 2)) diff --git a/packages/opencode/src/app/app.ts b/packages/opencode/src/app/app.ts index 6467d252..69ddd2ac 100644 --- a/packages/opencode/src/app/app.ts +++ b/packages/opencode/src/app/app.ts @@ -45,23 +45,14 @@ export namespace App { } export const provideExisting = ctx.provide - export async function provide( - input: Input, - cb: (app: App.Info) => Promise, - ) { + export async function provide(input: Input, cb: (app: App.Info) => Promise) { log.info("creating", { cwd: input.cwd, }) - const git = await Filesystem.findUp(".git", input.cwd).then(([x]) => - x ? path.dirname(x) : undefined, - ) + const git = await Filesystem.findUp(".git", input.cwd).then(([x]) => (x ? path.dirname(x) : undefined)) log.info("git", { git }) - const data = path.join( - Global.Path.data, - "project", - git ? directory(git) : "global", - ) + const data = path.join(Global.Path.data, "project", git ? directory(git) : "global") const stateFile = Bun.file(path.join(data, APP_JSON)) const state = (await stateFile.json().catch(() => ({}))) as { initialized: number diff --git a/packages/opencode/src/auth/anthropic.ts b/packages/opencode/src/auth/anthropic.ts index df4af692..cb38238e 100644 --- a/packages/opencode/src/auth/anthropic.ts +++ b/packages/opencode/src/auth/anthropic.ts @@ -10,14 +10,8 @@ export namespace AuthAnthropic { url.searchParams.set("code", "true") url.searchParams.set("client_id", CLIENT_ID) url.searchParams.set("response_type", "code") - url.searchParams.set( - "redirect_uri", - "https://console.anthropic.com/oauth/code/callback", - ) - url.searchParams.set( - "scope", - "org:create_api_key user:profile user:inference", - ) + url.searchParams.set("redirect_uri", "https://console.anthropic.com/oauth/code/callback") + url.searchParams.set("scope", "org:create_api_key user:profile user:inference") url.searchParams.set("code_challenge", pkce.challenge) url.searchParams.set("code_challenge_method", "S256") url.searchParams.set("state", pkce.verifier) @@ -57,20 +51,17 @@ export namespace AuthAnthropic { const info = await Auth.get("anthropic") if (!info || info.type !== "oauth") return if (info.access && info.expires > Date.now()) return info.access - const response = await fetch( - "https://console.anthropic.com/v1/oauth/token", - { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - grant_type: "refresh_token", - refresh_token: info.refresh, - client_id: CLIENT_ID, - }), + const response = await fetch("https://console.anthropic.com/v1/oauth/token", { + method: "POST", + headers: { + "Content-Type": "application/json", }, - ) + body: JSON.stringify({ + grant_type: "refresh_token", + refresh_token: info.refresh, + client_id: CLIENT_ID, + }), + }) if (!response.ok) return const json = await response.json() await Auth.set("anthropic", { diff --git a/packages/opencode/src/auth/copilot.ts b/packages/opencode/src/auth/copilot.ts index 4bbbaf2c..042f7c35 100644 --- a/packages/opencode/src/auth/copilot.ts +++ b/packages/opencode/src/auth/copilot.ts @@ -4,9 +4,7 @@ import path from "path" export const AuthCopilot = lazy(async () => { const file = Bun.file(path.join(Global.Path.state, "plugin", "copilot.ts")) - const response = fetch( - "https://raw.githubusercontent.com/sst/opencode-github-copilot/refs/heads/main/auth.ts", - ) + const response = fetch("https://raw.githubusercontent.com/sst/opencode-github-copilot/refs/heads/main/auth.ts") .then((x) => Bun.write(file, x)) .catch(() => {}) diff --git a/packages/opencode/src/auth/github-copilot.ts b/packages/opencode/src/auth/github-copilot.ts index c03caa26..ba5274e5 100644 --- a/packages/opencode/src/auth/github-copilot.ts +++ b/packages/opencode/src/auth/github-copilot.ts @@ -122,10 +122,7 @@ export namespace AuthGithubCopilot { return tokenData.token } - export const DeviceCodeError = NamedError.create( - "DeviceCodeError", - z.object({}), - ) + export const DeviceCodeError = NamedError.create("DeviceCodeError", z.object({})) export const TokenExchangeError = NamedError.create( "TokenExchangeError", diff --git a/packages/opencode/src/bun/index.ts b/packages/opencode/src/bun/index.ts index 7a7d89cf..23180e31 100644 --- a/packages/opencode/src/bun/index.ts +++ b/packages/opencode/src/bun/index.ts @@ -8,10 +8,7 @@ import { readableStreamToText } from "bun" export namespace BunProc { const log = Log.create({ service: "bun" }) - export async function run( - cmd: string[], - options?: Bun.SpawnOptions.OptionsObject, - ) { + export async function run(cmd: string[], options?: Bun.SpawnOptions.OptionsObject) { log.info("running", { cmd: [which(), ...cmd], ...options, @@ -26,9 +23,17 @@ export namespace BunProc { BUN_BE_BUN: "1", }, }) - const code = await result.exited; - const stdout = result.stdout ? typeof result.stdout === "number" ? result.stdout : await readableStreamToText(result.stdout) : undefined - const stderr = result.stderr ? typeof result.stderr === "number" ? result.stderr : await readableStreamToText(result.stderr) : undefined + const code = await result.exited + const stdout = result.stdout + ? typeof result.stdout === "number" + ? result.stdout + : await readableStreamToText(result.stdout) + : undefined + const stderr = result.stderr + ? typeof result.stderr === "number" + ? result.stderr + : await readableStreamToText(result.stderr) + : undefined log.info("done", { code, stdout, @@ -61,7 +66,7 @@ export namespace BunProc { if (parsed.dependencies[pkg] === version) return mod parsed.dependencies[pkg] = version await Bun.write(pkgjson, JSON.stringify(parsed, null, 2)) - await BunProc.run(["install", "--registry=https://registry.npmjs.org"], { + await BunProc.run(["install", "--cwd", Global.Path.cache, "--registry=https://registry.npmjs.org"], { cwd: Global.Path.cache, }).catch((e) => { throw new InstallFailedError( diff --git a/packages/opencode/src/bus/index.ts b/packages/opencode/src/bus/index.ts index 8461269a..0353da90 100644 --- a/packages/opencode/src/bus/index.ts +++ b/packages/opencode/src/bus/index.ts @@ -18,10 +18,7 @@ export namespace Bus { const registry = new Map() - export function event( - type: Type, - properties: Properties, - ) { + export function event(type: Type, properties: Properties) { const result = { type, properties, @@ -72,10 +69,7 @@ export namespace Bus { export function subscribe( def: Definition, - callback: (event: { - type: Definition["type"] - properties: z.infer - }) => void, + callback: (event: { type: Definition["type"]; properties: z.infer }) => void, ) { return raw(def.type, callback) } diff --git a/packages/opencode/src/cli/bootstrap.ts b/packages/opencode/src/cli/bootstrap.ts index 9ae274ed..4419773b 100644 --- a/packages/opencode/src/cli/bootstrap.ts +++ b/packages/opencode/src/cli/bootstrap.ts @@ -1,20 +1,15 @@ import { App } from "../app/app" import { ConfigHooks } from "../config/hooks" -import { FileWatcher } from "../file/watch" import { Format } from "../format" import { LSP } from "../lsp" import { Share } from "../share/share" -export async function bootstrap( - input: App.Input, - cb: (app: App.Info) => Promise, -) { +export async function bootstrap(input: App.Input, cb: (app: App.Info) => Promise) { return App.provide(input, async (app) => { Share.init() Format.init() ConfigHooks.init() LSP.init() - FileWatcher.init() return cb(app) }) diff --git a/packages/opencode/src/cli/cmd/auth.ts b/packages/opencode/src/cli/cmd/auth.ts index 9e8da95b..91ec61ea 100644 --- a/packages/opencode/src/cli/cmd/auth.ts +++ b/packages/opencode/src/cli/cmd/auth.ts @@ -15,11 +15,7 @@ export const AuthCommand = cmd({ command: "auth", describe: "manage credentials", builder: (yargs) => - yargs - .command(AuthLoginCommand) - .command(AuthLogoutCommand) - .command(AuthListCommand) - .demandCommand(), + yargs.command(AuthLoginCommand).command(AuthLogoutCommand).command(AuthListCommand).demandCommand(), async handler() {}, }) @@ -31,9 +27,7 @@ export const AuthListCommand = cmd({ UI.empty() const authPath = path.join(Global.Path.data, "auth.json") const homedir = os.homedir() - const displayPath = authPath.startsWith(homedir) - ? authPath.replace(homedir, "~") - : authPath + const displayPath = authPath.startsWith(homedir) ? authPath.replace(homedir, "~") : authPath prompts.intro(`Credentials ${UI.Style.TEXT_DIM}${displayPath}`) const results = await Auth.all().then((x) => Object.entries(x)) const database = await ModelsDev.get() @@ -114,8 +108,7 @@ export const AuthLoginCommand = cmd({ if (provider === "other") { provider = await prompts.text({ message: "Enter provider id", - validate: (x) => - x.match(/^[a-z-]+$/) ? undefined : "a-z and hyphens only", + validate: (x) => (x.match(/^[a-z-]+$/) ? undefined : "a-z and hyphens only"), }) if (prompts.isCancel(provider)) throw new UI.CancelledError() provider = provider.replace(/^@ai-sdk\//, "") @@ -186,17 +179,13 @@ export const AuthLoginCommand = cmd({ await new Promise((resolve) => setTimeout(resolve, 10)) const deviceInfo = await copilot.authorize() - prompts.note( - `Please visit: ${deviceInfo.verification}\nEnter code: ${deviceInfo.user}`, - ) + prompts.note(`Please visit: ${deviceInfo.verification}\nEnter code: ${deviceInfo.user}`) const spinner = prompts.spinner() spinner.start("Waiting for authorization...") while (true) { - await new Promise((resolve) => - setTimeout(resolve, deviceInfo.interval * 1000), - ) + await new Promise((resolve) => setTimeout(resolve, deviceInfo.interval * 1000)) const response = await copilot.poll(deviceInfo.device) if (response.status === "pending") continue if (response.status === "success") { @@ -248,12 +237,7 @@ export const AuthLogoutCommand = cmd({ const providerID = await prompts.select({ message: "Select provider", options: credentials.map(([key, value]) => ({ - label: - (database[key]?.name || key) + - UI.Style.TEXT_DIM + - " (" + - value.type + - ")", + label: (database[key]?.name || key) + UI.Style.TEXT_DIM + " (" + value.type + ")", value: key, })), }) diff --git a/packages/opencode/src/cli/cmd/debug/file.ts b/packages/opencode/src/cli/cmd/debug/file.ts index 021c49db..f773dbd9 100644 --- a/packages/opencode/src/cli/cmd/debug/file.ts +++ b/packages/opencode/src/cli/cmd/debug/file.ts @@ -31,7 +31,6 @@ const FileStatusCommand = cmd({ export const FileCommand = cmd({ command: "file", - builder: (yargs) => - yargs.command(FileReadCommand).command(FileStatusCommand).demandCommand(), + builder: (yargs) => yargs.command(FileReadCommand).command(FileStatusCommand).demandCommand(), async handler() {}, }) diff --git a/packages/opencode/src/cli/cmd/debug/index.ts b/packages/opencode/src/cli/cmd/debug/index.ts index e748183e..886131b6 100644 --- a/packages/opencode/src/cli/cmd/debug/index.ts +++ b/packages/opencode/src/cli/cmd/debug/index.ts @@ -17,9 +17,7 @@ export const DebugCommand = cmd({ command: "wait", async handler() { await bootstrap({ cwd: process.cwd() }, async () => { - await new Promise((resolve) => - setTimeout(resolve, 1_000 * 60 * 60 * 24), - ) + await new Promise((resolve) => setTimeout(resolve, 1_000 * 60 * 60 * 24)) }) }, }) diff --git a/packages/opencode/src/cli/cmd/debug/lsp.ts b/packages/opencode/src/cli/cmd/debug/lsp.ts index d596bf6c..28e01912 100644 --- a/packages/opencode/src/cli/cmd/debug/lsp.ts +++ b/packages/opencode/src/cli/cmd/debug/lsp.ts @@ -5,15 +5,13 @@ import { Log } from "../../../util/log" export const LSPCommand = cmd({ command: "lsp", - builder: (yargs) => - yargs.command(DiagnosticsCommand).command(SymbolsCommand).demandCommand(), + builder: (yargs) => yargs.command(DiagnosticsCommand).command(SymbolsCommand).demandCommand(), async handler() {}, }) const DiagnosticsCommand = cmd({ command: "diagnostics ", - builder: (yargs) => - yargs.positional("file", { type: "string", demandOption: true }), + builder: (yargs) => yargs.positional("file", { type: "string", demandOption: true }), async handler(args) { await bootstrap({ cwd: process.cwd() }, async () => { await LSP.touchFile(args.file, true) @@ -24,11 +22,9 @@ const DiagnosticsCommand = cmd({ export const SymbolsCommand = cmd({ command: "symbols ", - builder: (yargs) => - yargs.positional("query", { type: "string", demandOption: true }), + builder: (yargs) => yargs.positional("query", { type: "string", demandOption: true }), async handler(args) { await bootstrap({ cwd: process.cwd() }, async () => { - await LSP.touchFile("./src/index.ts", true) using _ = Log.Default.time("symbols") const results = await LSP.workspaceSymbol(args.query) console.log(JSON.stringify(results, null, 2)) diff --git a/packages/opencode/src/cli/cmd/debug/ripgrep.ts b/packages/opencode/src/cli/cmd/debug/ripgrep.ts index c7136867..b8005c90 100644 --- a/packages/opencode/src/cli/cmd/debug/ripgrep.ts +++ b/packages/opencode/src/cli/cmd/debug/ripgrep.ts @@ -5,12 +5,7 @@ import { cmd } from "../cmd" export const RipgrepCommand = cmd({ command: "rg", - builder: (yargs) => - yargs - .command(TreeCommand) - .command(FilesCommand) - .command(SearchCommand) - .demandCommand(), + builder: (yargs) => yargs.command(TreeCommand).command(FilesCommand).command(SearchCommand).demandCommand(), async handler() {}, }) @@ -50,7 +45,7 @@ const FilesCommand = cmd({ const files = await Ripgrep.files({ cwd: app.path.cwd, query: args.query, - glob: args.glob, + glob: args.glob ? [args.glob] : undefined, limit: args.limit, }) console.log(files.join("\n")) diff --git a/packages/opencode/src/cli/cmd/debug/snapshot.ts b/packages/opencode/src/cli/cmd/debug/snapshot.ts index a6d129d5..a06048c6 100644 --- a/packages/opencode/src/cli/cmd/debug/snapshot.ts +++ b/packages/opencode/src/cli/cmd/debug/snapshot.ts @@ -4,11 +4,7 @@ import { cmd } from "../cmd" export const SnapshotCommand = cmd({ command: "snapshot", - builder: (yargs) => - yargs - .command(SnapshotCreateCommand) - .command(SnapshotRestoreCommand) - .demandCommand(), + builder: (yargs) => yargs.command(SnapshotCreateCommand).command(SnapshotRestoreCommand).demandCommand(), async handler() {}, }) diff --git a/packages/opencode/src/cli/cmd/generate.ts b/packages/opencode/src/cli/cmd/generate.ts index 0cef1077..d6ed0eb1 100644 --- a/packages/opencode/src/cli/cmd/generate.ts +++ b/packages/opencode/src/cli/cmd/generate.ts @@ -10,9 +10,6 @@ export const GenerateCommand = { const dir = "gen" await fs.rmdir(dir, { recursive: true }).catch(() => {}) await fs.mkdir(dir, { recursive: true }) - await Bun.write( - path.join(dir, "openapi.json"), - JSON.stringify(specs, null, 2), - ) + await Bun.write(path.join(dir, "openapi.json"), JSON.stringify(specs, null, 2)) }, } satisfies CommandModule diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index 1905aa17..218e1ea8 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -2,12 +2,12 @@ import type { Argv } from "yargs" import { Bus } from "../../bus" import { Provider } from "../../provider/provider" import { Session } from "../../session" -import { Message } from "../../session/message" import { UI } from "../ui" import { cmd } from "./cmd" import { Flag } from "../../flag/flag" import { Config } from "../../config/config" import { bootstrap } from "../bootstrap" +import { MessageV2 } from "../../session/message-v2" const TOOL: Record = { todowrite: ["Todo", UI.Style.TEXT_WARNING_BOLD], @@ -54,7 +54,10 @@ export const RunCommand = cmd({ }) }, handler: async (args) => { - const message = args.message.join(" ") + let message = args.message.join(" ") + + if (!process.stdin.isTTY) message += "\n" + (await Bun.stdin.text()) + await bootstrap({ cwd: process.cwd() }, async () => { const session = await (async () => { if (args.continue) { @@ -78,27 +81,19 @@ export const RunCommand = cmd({ UI.empty() UI.println(UI.logo()) UI.empty() - UI.println(UI.Style.TEXT_NORMAL_BOLD + "> ", message) + const displayMessage = message.length > 300 ? message.slice(0, 300) + "..." : message + UI.println(UI.Style.TEXT_NORMAL_BOLD + "> ", displayMessage) UI.empty() const cfg = await Config.get() if (cfg.autoshare || Flag.OPENCODE_AUTO_SHARE || args.share) { await Session.share(session.id) - UI.println( - UI.Style.TEXT_INFO_BOLD + - "~ https://opencode.ai/s/" + - session.id.slice(-8), - ) + UI.println(UI.Style.TEXT_INFO_BOLD + "~ https://opencode.ai/s/" + session.id.slice(-8)) } UI.empty() - const { providerID, modelID } = args.model - ? Provider.parseModel(args.model) - : await Provider.defaultModel() - UI.println( - UI.Style.TEXT_NORMAL_BOLD + "@ ", - UI.Style.TEXT_NORMAL + `${providerID}/${modelID}`, - ) + const { providerID, modelID } = args.model ? Provider.parseModel(args.model) : await Provider.defaultModel() + UI.println(UI.Style.TEXT_NORMAL_BOLD + "@ ", UI.Style.TEXT_NORMAL + `${providerID}/${modelID}`) UI.empty() function printEvent(color: string, type: string, title: string) { @@ -110,24 +105,13 @@ export const RunCommand = cmd({ ) } - Bus.subscribe(Message.Event.PartUpdated, async (evt) => { + Bus.subscribe(MessageV2.Event.PartUpdated, async (evt) => { if (evt.properties.sessionID !== session.id) return const part = evt.properties.part - const message = await Session.getMessage( - evt.properties.sessionID, - evt.properties.messageID, - ) - if ( - part.type === "tool-invocation" && - part.toolInvocation.state === "result" - ) { - const metadata = message.metadata.tool[part.toolInvocation.toolCallId] - const [tool, color] = TOOL[part.toolInvocation.toolName] ?? [ - part.toolInvocation.toolName, - UI.Style.TEXT_INFO_BOLD, - ] - printEvent(color, tool, metadata?.title || "Unknown") + if (part.type === "tool" && part.state.status === "completed") { + const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD] + printEvent(color, tool, part.state.title || "Unknown") } if (part.type === "text") { @@ -141,6 +125,20 @@ export const RunCommand = cmd({ } }) + let errorMsg: string | undefined + Bus.subscribe(Session.Event.Error, async (evt) => { + const { sessionID, error } = evt.properties + if (sessionID !== session.id || !error) return + let err = String(error.name) + + if ("data" in error && error.data && "message" in error.data) { + err = error.data.message + } + errorMsg = errorMsg ? errorMsg + "\n" + err : err + + UI.error(err) + }) + const result = await Session.chat({ sessionID: session.id, providerID, @@ -156,6 +154,7 @@ export const RunCommand = cmd({ if (isPiped) { const match = result.parts.findLast((x) => x.type === "text") if (match) process.stdout.write(match.text) + if (errorMsg) process.stdout.write(errorMsg) } UI.empty() }) diff --git a/packages/opencode/src/cli/cmd/serve.ts b/packages/opencode/src/cli/cmd/serve.ts index f3686f30..6dab38f1 100644 --- a/packages/opencode/src/cli/cmd/serve.ts +++ b/packages/opencode/src/cli/cmd/serve.ts @@ -38,9 +38,7 @@ export const ServeCommand = cmd({ hostname, }) - console.log( - `opencode server listening on http://${server.hostname}:${server.port}`, - ) + console.log(`opencode server listening on http://${server.hostname}:${server.port}`) await new Promise(() => {}) diff --git a/packages/opencode/src/cli/cmd/tui.ts b/packages/opencode/src/cli/cmd/tui.ts index 5cdda83c..1e8d2bbc 100644 --- a/packages/opencode/src/cli/cmd/tui.ts +++ b/packages/opencode/src/cli/cmd/tui.ts @@ -10,15 +10,27 @@ import { Installation } from "../../installation" import { Config } from "../../config/config" import { Bus } from "../../bus" import { Log } from "../../util/log" +import { FileWatcher } from "../../file/watch" export const TuiCommand = cmd({ command: "$0 [project]", describe: "start opencode tui", builder: (yargs) => - yargs.positional("project", { - type: "string", - describe: "path to start opencode in", - }), + yargs + .positional("project", { + type: "string", + describe: "path to start opencode in", + }) + .option("model", { + type: "string", + alias: ["m"], + describe: "model to use in the format of provider/model", + }) + .option("prompt", { + alias: ["p"], + type: "string", + describe: "prompt to use", + }), handler: async (args) => { while (true) { const cwd = args.project ? path.resolve(args.project) : process.cwd() @@ -29,6 +41,7 @@ export const TuiCommand = cmd({ return } const result = await bootstrap({ cwd }, async (app) => { + FileWatcher.init() const providers = await Provider.list() if (Object.keys(providers).length === 0) { return "needs_provider" @@ -40,9 +53,7 @@ export const TuiCommand = cmd({ }) let cmd = ["go", "run", "./main.go"] - let cwd = Bun.fileURLToPath( - new URL("../../../../tui/cmd/opencode", import.meta.url), - ) + let cwd = Bun.fileURLToPath(new URL("../../../../tui/cmd/opencode", import.meta.url)) if (Bun.embeddedFiles.length > 0) { const blob = Bun.embeddedFiles[0] as File let binaryName = blob.name @@ -62,13 +73,18 @@ export const TuiCommand = cmd({ cmd, }) const proc = Bun.spawn({ - cmd: [...cmd, ...process.argv.slice(2)], + cmd: [ + ...cmd, + ...(args.model ? ["--model", args.model] : []), + ...(args.prompt ? ["--prompt", args.prompt] : []), + ], cwd, stdout: "inherit", stderr: "inherit", stdin: "inherit", env: { ...process.env, + CGO_ENABLED: "0", OPENCODE_SERVER: server.url.toString(), OPENCODE_APP_INFO: JSON.stringify(app), }, diff --git a/packages/opencode/src/cli/cmd/upgrade.ts b/packages/opencode/src/cli/cmd/upgrade.ts index 759ab5ae..17d18168 100644 --- a/packages/opencode/src/cli/cmd/upgrade.ts +++ b/packages/opencode/src/cli/cmd/upgrade.ts @@ -27,22 +27,26 @@ export const UpgradeCommand = { const detectedMethod = await Installation.method() const method = (args.method as Installation.Method) ?? detectedMethod if (method === "unknown") { - prompts.log.error( - `opencode is installed to ${process.execPath} and seems to be managed by a package manager`, - ) + prompts.log.error(`opencode is installed to ${process.execPath} and seems to be managed by a package manager`) prompts.outro("Done") return } prompts.log.info("Using method: " + method) const target = args.target ?? (await Installation.latest()) + + if (Installation.VERSION === target) { + prompts.log.warn(`opencode upgrade skipped: ${target} is already installed`) + prompts.outro("Done") + return + } + prompts.log.info(`From ${Installation.VERSION} → ${target}`) const spinner = prompts.spinner() spinner.start("Upgrading...") const err = await Installation.upgrade(method, target).catch((err) => err) if (err) { spinner.stop("Upgrade failed") - if (err instanceof Installation.UpgradeFailedError) - prompts.log.error(err.data.stderr) + if (err instanceof Installation.UpgradeFailedError) prompts.log.error(err.data.stderr) else if (err instanceof Error) prompts.log.error(err.message) prompts.outro("Done") return diff --git a/packages/opencode/src/cli/error.ts b/packages/opencode/src/cli/error.ts index 752ad696..261206a1 100644 --- a/packages/opencode/src/cli/error.ts +++ b/packages/opencode/src/cli/error.ts @@ -5,14 +5,11 @@ import { UI } from "./ui" export function FormatError(input: unknown) { if (MCP.Failed.isInstance(input)) return `MCP server "${input.data.name}" failed. Note, opencode does not support MCP authentication yet.` - if (Config.JsonError.isInstance(input)) - return `Config file at ${input.data.path} is not valid JSON` + if (Config.JsonError.isInstance(input)) return `Config file at ${input.data.path} is not valid JSON` if (Config.InvalidError.isInstance(input)) return [ `Config file at ${input.data.path} is invalid`, - ...(input.data.issues?.map( - (issue) => "↳ " + issue.message + " " + issue.path.join("."), - ) ?? []), + ...(input.data.issues?.map((issue) => "↳ " + issue.message + " " + issue.path.join(".")) ?? []), ].join("\n") if (UI.CancelledError.isInstance(input)) return "" diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index eb67778e..7c248da8 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -29,18 +29,12 @@ export namespace Config { export const McpLocal = z .object({ type: z.literal("local").describe("Type of MCP server connection"), - command: z - .string() - .array() - .describe("Command and arguments to run the MCP server"), + command: z.string().array().describe("Command and arguments to run the MCP server"), environment: z .record(z.string(), z.string()) .optional() .describe("Environment variables to set when running the MCP server"), - enabled: z - .boolean() - .optional() - .describe("Enable or disable the MCP server on startup"), + enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"), }) .strict() .openapi({ @@ -51,10 +45,7 @@ export namespace Config { .object({ type: z.literal("remote").describe("Type of MCP server connection"), url: z.string().describe("URL of the remote MCP server"), - enabled: z - .boolean() - .optional() - .describe("Enable or disable the MCP server on startup"), + enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"), }) .strict() .openapi({ @@ -66,69 +57,43 @@ export namespace Config { export const Keybinds = z .object({ - leader: z - .string() - .optional() - .describe("Leader key for keybind combinations"), - help: z.string().optional().describe("Show help dialog"), - editor_open: z.string().optional().describe("Open external editor"), - session_new: z.string().optional().describe("Create a new session"), - session_list: z.string().optional().describe("List all sessions"), - session_share: z.string().optional().describe("Share current session"), - session_interrupt: z - .string() - .optional() - .describe("Interrupt current session"), - session_compact: z - .string() - .optional() - .describe("Toggle compact mode for session"), - tool_details: z.string().optional().describe("Show tool details"), - model_list: z.string().optional().describe("List available models"), - theme_list: z.string().optional().describe("List available themes"), - project_init: z - .string() - .optional() - .describe("Initialize project configuration"), - input_clear: z.string().optional().describe("Clear input field"), - input_paste: z.string().optional().describe("Paste from clipboard"), - input_submit: z.string().optional().describe("Submit input"), - input_newline: z.string().optional().describe("Insert newline in input"), - history_previous: z - .string() - .optional() - .describe("Navigate to previous history item"), - history_next: z - .string() - .optional() - .describe("Navigate to next history item"), - messages_page_up: z - .string() - .optional() - .describe("Scroll messages up by one page"), - messages_page_down: z - .string() - .optional() - .describe("Scroll messages down by one page"), - messages_half_page_up: z - .string() - .optional() - .describe("Scroll messages up by half page"), + leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"), + app_help: z.string().optional().default("h").describe("Show help dialog"), + editor_open: z.string().optional().default("e").describe("Open external editor"), + session_new: z.string().optional().default("n").describe("Create a new session"), + session_list: z.string().optional().default("l").describe("List all sessions"), + session_share: z.string().optional().default("s").describe("Share current session"), + session_unshare: z.string().optional().default("u").describe("Unshare current session"), + session_interrupt: z.string().optional().default("esc").describe("Interrupt current session"), + session_compact: z.string().optional().default("c").describe("Compact the session"), + tool_details: z.string().optional().default("d").describe("Toggle tool details"), + model_list: z.string().optional().default("m").describe("List available models"), + theme_list: z.string().optional().default("t").describe("List available themes"), + file_list: z.string().optional().default("f").describe("List files"), + file_close: z.string().optional().default("esc").describe("Close file"), + file_search: z.string().optional().default("/").describe("Search file"), + file_diff_toggle: z.string().optional().default("v").describe("Split/unified diff"), + project_init: z.string().optional().default("i").describe("Create/update AGENTS.md"), + input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"), + input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"), + input_submit: z.string().optional().default("enter").describe("Submit input"), + input_newline: z.string().optional().default("shift+enter,ctrl+j").describe("Insert newline in input"), + messages_page_up: z.string().optional().default("pgup").describe("Scroll messages up by one page"), + messages_page_down: z.string().optional().default("pgdown").describe("Scroll messages down by one page"), + messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"), messages_half_page_down: z .string() .optional() + .default("ctrl+alt+d") .describe("Scroll messages down by half page"), - messages_previous: z - .string() - .optional() - .describe("Navigate to previous message"), - messages_next: z.string().optional().describe("Navigate to next message"), - messages_first: z - .string() - .optional() - .describe("Navigate to first message"), - messages_last: z.string().optional().describe("Navigate to last message"), - app_exit: z.string().optional().describe("Exit the application"), + messages_previous: z.string().optional().default("ctrl+up").describe("Navigate to previous message"), + messages_next: z.string().optional().default("ctrl+down").describe("Navigate to next message"), + messages_first: z.string().optional().default("ctrl+g").describe("Navigate to first message"), + messages_last: z.string().optional().default("ctrl+alt+g").describe("Navigate to last message"), + messages_layout_toggle: z.string().optional().default("p").describe("Toggle layout"), + messages_copy: z.string().optional().default("y").describe("Copy message"), + messages_revert: z.string().optional().default("r").describe("Revert message"), + app_exit: z.string().optional().default("ctrl+c,q").describe("Exit the application"), }) .strict() .openapi({ @@ -136,33 +101,14 @@ export namespace Config { }) export const Info = z .object({ - $schema: z - .string() - .optional() - .describe("JSON schema reference for configuration validation"), - theme: z - .string() - .optional() - .describe("Theme name to use for the interface"), + $schema: z.string().optional().describe("JSON schema reference for configuration validation"), + theme: z.string().optional().describe("Theme name to use for the interface"), keybinds: Keybinds.optional().describe("Custom keybind configurations"), - autoshare: z - .boolean() - .optional() - .describe("Share newly created sessions automatically"), - autoupdate: z - .boolean() - .optional() - .describe("Automatically update to the latest version"), - disabled_providers: z - .array(z.string()) - .optional() - .describe("Disable providers that are loaded automatically"), - model: z - .string() - .describe( - "Model to use in the format of provider/model, eg anthropic/claude-2", - ) - .optional(), + autoshare: z.boolean().optional().describe("Share newly created sessions automatically"), + autoupdate: z.boolean().optional().describe("Automatically update to the latest version"), + disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"), + model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(), + log_level: Log.Level.optional().describe("Minimum log level to write to log files"), provider: z .record( ModelsDev.Provider.partial().extend({ @@ -172,14 +118,8 @@ export namespace Config { ) .optional() .describe("Custom provider configurations and model overrides"), - mcp: z - .record(z.string(), Mcp) - .optional() - .describe("MCP (Model Context Protocol) server configurations"), - instructions: z - .array(z.string()) - .optional() - .describe("Additional instruction files or patterns to include"), + mcp: z.record(z.string(), Mcp).optional().describe("MCP (Model Context Protocol) server configurations"), + instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"), experimental: z .object({ hook: z @@ -227,10 +167,7 @@ export namespace Config { if (provider && model) result.model = `${provider}/${model}` result["$schema"] = "https://opencode.ai/config.json" result = mergeDeep(result, rest) - await Bun.write( - path.join(Global.Path.config, "config.json"), - JSON.stringify(result, null, 2), - ) + await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2)) await fs.unlink(path.join(Global.Path.config, "config")) }) .catch(() => {}) diff --git a/packages/opencode/src/config/hooks.ts b/packages/opencode/src/config/hooks.ts index ffa2475f..973575b7 100644 --- a/packages/opencode/src/config/hooks.ts +++ b/packages/opencode/src/config/hooks.ts @@ -22,9 +22,7 @@ export namespace ConfigHooks { command: item.command, }) Bun.spawn({ - cmd: item.command.map((x) => - x.replace("$FILE", payload.properties.file), - ), + cmd: item.command.map((x) => x.replace("$FILE", payload.properties.file)), env: item.environment, cwd: app.path.cwd, stdout: "ignore", diff --git a/packages/opencode/src/file/fzf.ts b/packages/opencode/src/file/fzf.ts index 6d52702f..1376af8c 100644 --- a/packages/opencode/src/file/fzf.ts +++ b/packages/opencode/src/file/fzf.ts @@ -45,10 +45,7 @@ export namespace Fzf { log.info("found", { filepath }) return { filepath } } - filepath = path.join( - Global.Path.bin, - "fzf" + (process.platform === "win32" ? ".exe" : ""), - ) + filepath = path.join(Global.Path.bin, "fzf" + (process.platform === "win32" ? ".exe" : "")) const file = Bun.file(filepath) if (!(await file.exists())) { @@ -56,18 +53,15 @@ export namespace Fzf { const arch = archMap[process.arch as keyof typeof archMap] ?? "amd64" const config = PLATFORM[process.platform as keyof typeof PLATFORM] - if (!config) - throw new UnsupportedPlatformError({ platform: process.platform }) + if (!config) throw new UnsupportedPlatformError({ platform: process.platform }) const version = VERSION - const platformName = - process.platform === "win32" ? "windows" : process.platform + const platformName = process.platform === "win32" ? "windows" : process.platform const filename = `fzf-${version}-${platformName}_${arch}.${config.extension}` const url = `https://github.com/junegunn/fzf/releases/download/v${version}/${filename}` const response = await fetch(url) - if (!response.ok) - throw new DownloadFailedError({ url, status: response.status }) + if (!response.ok) throw new DownloadFailedError({ url, status: response.status }) const buffer = await response.arrayBuffer() const archivePath = path.join(Global.Path.bin, filename) @@ -86,14 +80,11 @@ export namespace Fzf { }) } if (config.extension === "zip") { - const proc = Bun.spawn( - ["unzip", "-j", archivePath, "fzf.exe", "-d", Global.Path.bin], - { - cwd: Global.Path.bin, - stderr: "pipe", - stdout: "ignore", - }, - ) + const proc = Bun.spawn(["unzip", "-j", archivePath, "fzf.exe", "-d", Global.Path.bin], { + cwd: Global.Path.bin, + stderr: "pipe", + stdout: "ignore", + }) await proc.exited if (proc.exitCode !== 0) throw new ExtractionFailedError({ diff --git a/packages/opencode/src/file/index.ts b/packages/opencode/src/file/index.ts index d9e61fa5..b99f35e1 100644 --- a/packages/opencode/src/file/index.ts +++ b/packages/opencode/src/file/index.ts @@ -11,6 +11,19 @@ import { Log } from "../util/log" export namespace File { const log = Log.create({ service: "file" }) + export const Info = z + .object({ + path: z.string(), + added: z.number().int(), + removed: z.number().int(), + status: z.enum(["added", "deleted", "modified"]), + }) + .openapi({ + ref: "File", + }) + + export type Info = z.infer + export const Event = { Edited: Bus.event( "file.edited", @@ -24,20 +37,16 @@ export namespace File { const app = App.info() if (!app.git) return [] - const diffOutput = await $`git diff --numstat HEAD` - .cwd(app.path.cwd) - .quiet() - .nothrow() - .text() + const diffOutput = await $`git diff --numstat HEAD`.cwd(app.path.cwd).quiet().nothrow().text() - const changedFiles = [] + const changedFiles: Info[] = [] if (diffOutput.trim()) { const lines = diffOutput.trim().split("\n") for (const line of lines) { const [added, removed, filepath] = line.split("\t") changedFiles.push({ - file: filepath, + path: filepath, added: added === "-" ? 0 : parseInt(added, 10), removed: removed === "-" ? 0 : parseInt(removed, 10), status: "modified", @@ -45,22 +54,16 @@ export namespace File { } } - const untrackedOutput = await $`git ls-files --others --exclude-standard` - .cwd(app.path.cwd) - .quiet() - .nothrow() - .text() + const untrackedOutput = await $`git ls-files --others --exclude-standard`.cwd(app.path.cwd).quiet().nothrow().text() if (untrackedOutput.trim()) { const untrackedFiles = untrackedOutput.trim().split("\n") for (const filepath of untrackedFiles) { try { - const content = await Bun.file( - path.join(app.path.root, filepath), - ).text() + const content = await Bun.file(path.join(app.path.root, filepath)).text() const lines = content.split("\n").length changedFiles.push({ - file: filepath, + path: filepath, added: lines, removed: 0, status: "added", @@ -72,17 +75,13 @@ export namespace File { } // Get deleted files - const deletedOutput = await $`git diff --name-only --diff-filter=D HEAD` - .cwd(app.path.cwd) - .quiet() - .nothrow() - .text() + const deletedOutput = await $`git diff --name-only --diff-filter=D HEAD`.cwd(app.path.cwd).quiet().nothrow().text() if (deletedOutput.trim()) { const deletedFiles = deletedOutput.trim().split("\n") for (const filepath of deletedFiles) { changedFiles.push({ - file: filepath, + path: filepath, added: 0, removed: 0, // Could get original line count but would require another git command status: "deleted", @@ -92,7 +91,7 @@ export namespace File { return changedFiles.map((x) => ({ ...x, - file: path.relative(app.path.cwd, path.join(app.path.root, x.file)), + path: path.relative(app.path.cwd, path.join(app.path.root, x.path)), })) } @@ -112,11 +111,7 @@ export namespace File { filepath: rel, }) if (diff !== "unmodified") { - const original = await $`git show HEAD:${rel}` - .cwd(app.path.root) - .quiet() - .nothrow() - .text() + const original = await $`git show HEAD:${rel}`.cwd(app.path.root).quiet().nothrow().text() const patch = createPatch(file, original, content, "old", "new", { context: Infinity, }) diff --git a/packages/opencode/src/file/ripgrep.ts b/packages/opencode/src/file/ripgrep.ts index a975d34b..05ebbe7d 100644 --- a/packages/opencode/src/file/ripgrep.ts +++ b/packages/opencode/src/file/ripgrep.ts @@ -34,25 +34,27 @@ export namespace Ripgrep { export const Match = z.object({ type: z.literal("match"), - data: z.object({ - path: z.object({ - text: z.string(), - }), - lines: z.object({ - text: z.string(), - }), - line_number: z.number(), - absolute_offset: z.number(), - submatches: z.array( - z.object({ - match: z.object({ - text: z.string(), - }), - start: z.number(), - end: z.number(), + data: z + .object({ + path: z.object({ + text: z.string(), }), - ), - }), + lines: z.object({ + text: z.string(), + }), + line_number: z.number(), + absolute_offset: z.number(), + submatches: z.array( + z.object({ + match: z.object({ + text: z.string(), + }), + start: z.number(), + end: z.number(), + }), + ), + }) + .openapi({ ref: "Match" }), }) const End = z.object({ @@ -122,15 +124,11 @@ export namespace Ripgrep { const state = lazy(async () => { let filepath = Bun.which("rg") if (filepath) return { filepath } - filepath = path.join( - Global.Path.bin, - "rg" + (process.platform === "win32" ? ".exe" : ""), - ) + filepath = path.join(Global.Path.bin, "rg" + (process.platform === "win32" ? ".exe" : "")) const file = Bun.file(filepath) if (!(await file.exists())) { - const platformKey = - `${process.arch}-${process.platform}` as keyof typeof PLATFORM + const platformKey = `${process.arch}-${process.platform}` as keyof typeof PLATFORM const config = PLATFORM[platformKey] if (!config) throw new UnsupportedPlatformError({ platform: platformKey }) @@ -139,8 +137,7 @@ export namespace Ripgrep { const url = `https://github.com/BurntSushi/ripgrep/releases/download/${version}/${filename}` const response = await fetch(url) - if (!response.ok) - throw new DownloadFailedError({ url, status: response.status }) + if (!response.ok) throw new DownloadFailedError({ url, status: response.status }) const buffer = await response.arrayBuffer() const archivePath = path.join(Global.Path.bin, filename) @@ -164,14 +161,11 @@ export namespace Ripgrep { }) } if (config.extension === "zip") { - const proc = Bun.spawn( - ["unzip", "-j", archivePath, "*/rg.exe", "-d", Global.Path.bin], - { - cwd: Global.Path.bin, - stderr: "pipe", - stdout: "ignore", - }, - ) + const proc = Bun.spawn(["unzip", "-j", archivePath, "*/rg.exe", "-d", Global.Path.bin], { + cwd: Global.Path.bin, + stderr: "pipe", + stdout: "ignore", + }) await proc.exited if (proc.exitCode !== 0) throw new ExtractionFailedError({ @@ -193,17 +187,16 @@ export namespace Ripgrep { return filepath } - export async function files(input: { - cwd: string - query?: string - glob?: string - limit?: number - }) { - const commands = [ - `${await filepath()} --files --hidden --glob='!.git/*' ${input.glob ? `--glob='${input.glob}'` : ``}`, - ] - if (input.query) - commands.push(`${await Fzf.filepath()} --filter=${input.query}`) + export async function files(input: { cwd: string; query?: string; glob?: string[]; limit?: number }) { + const commands = [`${$.escape(await filepath())} --files --follow --hidden --glob='!.git/*'`] + + if (input.glob) { + for (const g of input.glob) { + commands[0] += ` --glob='${g}'` + } + } + + if (input.query) commands.push(`${await Fzf.filepath()} --filter=${input.query}`) if (input.limit) commands.push(`head -n ${input.limit}`) const joined = commands.join(" | ") const result = await $`${{ raw: joined }}`.cwd(input.cwd).nothrow().text() @@ -310,18 +303,8 @@ export namespace Ripgrep { return lines.join("\n") } - export async function search(input: { - cwd: string - pattern: string - glob?: string[] - limit?: number - }) { - const args = [ - `${await filepath()}`, - "--json", - "--hidden", - "--glob='!.git/*'", - ] + export async function search(input: { cwd: string; pattern: string; glob?: string[]; limit?: number }) { + const args = [`${await filepath()}`, "--json", "--hidden", "--glob='!.git/*'"] if (input.glob) { for (const g of input.glob) { diff --git a/packages/opencode/src/file/time.ts b/packages/opencode/src/file/time.ts index 908efdcc..453259e8 100644 --- a/packages/opencode/src/file/time.ts +++ b/packages/opencode/src/file/time.ts @@ -27,10 +27,7 @@ export namespace FileTime { export async function assert(sessionID: string, filepath: string) { const time = get(sessionID, filepath) - if (!time) - throw new Error( - `You must read the file ${filepath} before overwriting it. Use the Read tool first`, - ) + if (!time) throw new Error(`You must read the file ${filepath} before overwriting it. Use the Read tool first`) const stats = await Bun.file(filepath).stat() if (stats.mtime.getTime() > time.getTime()) { throw new Error( diff --git a/packages/opencode/src/file/watch.ts b/packages/opencode/src/file/watch.ts index 1d12168f..6546f64d 100644 --- a/packages/opencode/src/file/watch.ts +++ b/packages/opencode/src/file/watch.ts @@ -21,23 +21,20 @@ export namespace FileWatcher { "file.watcher", () => { const app = App.use() + if (!app.info.git) return {} try { - const watcher = fs.watch( - app.info.path.cwd, - { recursive: true }, - (event, file) => { - log.info("change", { file, event }) - if (!file) return - // for some reason async local storage is lost here - // https://github.com/oven-sh/bun/issues/20754 - App.provideExisting(app, async () => { - Bus.publish(Event.Updated, { - file, - event, - }) + const watcher = fs.watch(app.info.path.cwd, { recursive: true }, (event, file) => { + log.info("change", { file, event }) + if (!file) return + // for some reason async local storage is lost here + // https://github.com/oven-sh/bun/issues/20754 + App.provideExisting(app, async () => { + Bus.publish(Event.Updated, { + file, + event, }) - }, - ) + }) + }) return { watcher } } catch { return {} diff --git a/packages/opencode/src/format/formatter.ts b/packages/opencode/src/format/formatter.ts index 60ca6a32..3f24debf 100644 --- a/packages/opencode/src/format/formatter.ts +++ b/packages/opencode/src/format/formatter.ts @@ -94,21 +94,7 @@ export const zig: Info = { export const clang: Info = { name: "clang-format", command: ["clang-format", "-i", "$FILE"], - extensions: [ - ".c", - ".cc", - ".cpp", - ".cxx", - ".c++", - ".h", - ".hh", - ".hpp", - ".hxx", - ".h++", - ".ino", - ".C", - ".H", - ], + extensions: [".c", ".cc", ".cpp", ".cxx", ".c++", ".h", ".hh", ".hpp", ".hxx", ".h++", ".ino", ".C", ".H"], async enabled() { return Bun.which("clang-format") !== null }, diff --git a/packages/opencode/src/id/id.ts b/packages/opencode/src/id/id.ts index cf9a3042..b705ff2c 100644 --- a/packages/opencode/src/id/id.ts +++ b/packages/opencode/src/id/id.ts @@ -26,11 +26,7 @@ export namespace Identifier { return generateID(prefix, true, given) } - function generateID( - prefix: keyof typeof prefixes, - descending: boolean, - given?: string, - ): string { + function generateID(prefix: keyof typeof prefixes, descending: boolean, given?: string): string { if (!given) { return generateNewID(prefix, descending) } @@ -42,8 +38,7 @@ export namespace Identifier { } function randomBase62(length: number): string { - const chars = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" let result = "" const bytes = randomBytes(length) for (let i = 0; i < length; i++) { @@ -52,10 +47,7 @@ export namespace Identifier { return result } - function generateNewID( - prefix: keyof typeof prefixes, - descending: boolean, - ): string { + function generateNewID(prefix: keyof typeof prefixes, descending: boolean): string { const currentTimestamp = Date.now() if (currentTimestamp !== lastTimestamp) { @@ -73,11 +65,6 @@ export namespace Identifier { timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff)) } - return ( - prefixes[prefix] + - "_" + - timeBytes.toString("hex") + - randomBase62(LENGTH - 12) - ) + return prefixes[prefix] + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12) } } diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index 3ca40ce7..6206f230 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -40,6 +40,24 @@ const cli = yargs(hideBin(process.argv)) }) .middleware(async () => { await Log.init({ print: process.argv.includes("--print-logs") }) + + try { + const { Config } = await import("./config/config") + const { App } = await import("./app/app") + + App.provide({ cwd: process.cwd() }, async () => { + const cfg = await Config.get() + if (cfg.log_level) { + Log.setLevel(cfg.log_level as Log.Level) + } else { + const defaultLevel = Installation.isDev() ? "DEBUG" : "INFO" + Log.setLevel(defaultLevel) + } + }) + } catch (e) { + Log.Default.error("failed to load config", { error: e }) + } + Log.Default.info("opencode", { version: Installation.VERSION, args: process.argv.slice(2), @@ -55,10 +73,7 @@ const cli = yargs(hideBin(process.argv)) .command(ServeCommand) .command(ModelsCommand) .fail((msg) => { - if ( - msg.startsWith("Unknown argument") || - msg.startsWith("Not enough non-option arguments") - ) { + if (msg.startsWith("Unknown argument") || msg.startsWith("Not enough non-option arguments")) { cli.showHelp("log") } }) @@ -97,10 +112,7 @@ try { Log.Default.error("fatal", data) const formatted = FormatError(e) if (formatted) UI.error(formatted) - if (formatted === undefined) - UI.error( - "Unexpected error, check log file at " + Log.file() + " for more details", - ) + if (formatted === undefined) UI.error("Unexpected error, check log file at " + Log.file() + " for more details") process.exitCode = 1 } diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index 4af5c807..9dfe2243 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -135,8 +135,7 @@ export namespace Installation { }) } - export const VERSION = - typeof OPENCODE_VERSION === "string" ? OPENCODE_VERSION : "dev" + export const VERSION = typeof OPENCODE_VERSION === "string" ? OPENCODE_VERSION : "dev" export async function latest() { return fetch("https://api.github.com/repos/sst/opencode/releases/latest") diff --git a/packages/opencode/src/lsp/client.ts b/packages/opencode/src/lsp/client.ts index 5aff437d..0d34b869 100644 --- a/packages/opencode/src/lsp/client.ts +++ b/packages/opencode/src/lsp/client.ts @@ -1,9 +1,5 @@ import path from "path" -import { - createMessageConnection, - StreamMessageReader, - StreamMessageWriter, -} from "vscode-jsonrpc/node" +import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node" import type { Diagnostic as VSCodeDiagnostic } from "vscode-languageserver-types" import { App } from "../app/app" import { Log } from "../util/log" @@ -38,45 +34,54 @@ export namespace LSPClient { ), } - export async function create(serverID: string, server: LSPServer.Handle) { + export async function create(input: { serverID: string; server: LSPServer.Handle; root: string }) { const app = App.info() - log.info("starting client", { id: serverID }) + const l = log.clone().tag("serverID", input.serverID) + l.info("starting client") const connection = createMessageConnection( - new StreamMessageReader(server.process.stdout), - new StreamMessageWriter(server.process.stdin), + new StreamMessageReader(input.server.process.stdout), + new StreamMessageWriter(input.server.process.stdin), ) const diagnostics = new Map() connection.onNotification("textDocument/publishDiagnostics", (params) => { const path = new URL(params.uri).pathname - log.info("textDocument/publishDiagnostics", { + l.info("textDocument/publishDiagnostics", { path, }) const exists = diagnostics.has(path) diagnostics.set(path, params.diagnostics) - if (!exists && serverID === "typescript") return - Bus.publish(Event.Diagnostics, { path, serverID }) + if (!exists && input.serverID === "typescript") return + Bus.publish(Event.Diagnostics, { path, serverID: input.serverID }) + }) + connection.onRequest("window/workDoneProgress/create", (params) => { + l.info("window/workDoneProgress/create", params) + return null }) connection.onRequest("workspace/configuration", async () => { return [{}] }) connection.listen() - log.info("sending initialize", { id: serverID }) + l.info("sending initialize") await withTimeout( connection.sendRequest("initialize", { - processId: server.process.pid, + rootUri: "file://" + input.root, + processId: input.server.process.pid, workspaceFolders: [ { name: "workspace", - uri: "file://" + app.path.cwd, + uri: "file://" + input.root, }, ], initializationOptions: { - ...server.initialization, + ...input.server.initialization, }, capabilities: { + window: { + workDoneProgress: true, + }, workspace: { configuration: true, }, @@ -93,9 +98,9 @@ export namespace LSPClient { }), 5_000, ).catch((err) => { - log.error("initialize error", { error: err }) + l.error("initialize error", { error: err }) throw new InitializeError( - { serverID }, + { serverID: input.serverID }, { cause: err, }, @@ -103,26 +108,22 @@ export namespace LSPClient { }) await connection.sendNotification("initialized", {}) - log.info("initialized", { - serverID, - }) const files: { [path: string]: number } = {} const result = { + root: input.root, get serverID() { - return serverID + return input.serverID }, get connection() { return connection }, notify: { async open(input: { path: string }) { - input.path = path.isAbsolute(input.path) - ? input.path - : path.resolve(app.path.cwd, input.path) + input.path = path.isAbsolute(input.path) ? input.path : path.resolve(app.path.cwd, input.path) const file = Bun.file(input.path) const text = await file.text() const version = files[input.path] @@ -154,18 +155,13 @@ export namespace LSPClient { return diagnostics }, async waitForDiagnostics(input: { path: string }) { - input.path = path.isAbsolute(input.path) - ? input.path - : path.resolve(app.path.cwd, input.path) + input.path = path.isAbsolute(input.path) ? input.path : path.resolve(app.path.cwd, input.path) log.info("waiting for diagnostics", input) let unsub: () => void return await withTimeout( new Promise((resolve) => { unsub = Bus.subscribe(Event.Diagnostics, (event) => { - if ( - event.properties.path === input.path && - event.properties.serverID === result.serverID - ) { + if (event.properties.path === input.path && event.properties.serverID === result.serverID) { log.info("got diagnostics", input) unsub?.() resolve() @@ -180,13 +176,19 @@ export namespace LSPClient { }) }, async shutdown() { - log.info("shutting down", { serverID }) + l.info("shutting down") connection.end() connection.dispose() - log.info("shutdown", { serverID }) + input.server.process.kill() + l.info("shutdown") }, } + if (input.server.onInitialized) { + await input.server.onInitialized(result) + } + l.info("initialized") + return result } } diff --git a/packages/opencode/src/lsp/index.ts b/packages/opencode/src/lsp/index.ts index 88e549bb..6fea09d7 100644 --- a/packages/opencode/src/lsp/index.ts +++ b/packages/opencode/src/lsp/index.ts @@ -3,8 +3,8 @@ import { Log } from "../util/log" import { LSPClient } from "./client" import path from "path" import { LSPServer } from "./server" -import { Ripgrep } from "../file/ripgrep" import { z } from "zod" +import { Filesystem } from "../util/filesystem" export namespace LSP { const log = Log.create({ service: "lsp" }) @@ -28,7 +28,7 @@ export namespace LSP { }), }) .openapi({ - ref: "LSP.Symbol", + ref: "Symbol", }) export type Symbol = z.infer @@ -36,31 +36,39 @@ export namespace LSP { "lsp", async (app) => { log.info("initializing") - const clients = new Map() + const clients: LSPClient.Info[] = [] + for (const server of Object.values(LSPServer)) { - for (const extension of server.extensions) { - const [file] = await Ripgrep.files({ - cwd: app.path.cwd, - glob: "*" + extension, + const roots = await server.roots(app) + + for (const root of roots) { + if (!Filesystem.overlaps(app.path.cwd, root)) continue + log.info("", { + root, + serverID: server.id, }) - if (!file) continue - const handle = await server.spawn(App.info()) + const handle = await server.spawn(App.info(), root) if (!handle) break - const client = await LSPClient.create(server.id, handle).catch( - (err) => log.error("", { error: err }), - ) + const client = await LSPClient.create({ + serverID: server.id, + server: handle, + root, + }).catch((err) => { + handle.process.kill() + log.error("", { error: err }) + }) if (!client) break - clients.set(server.id, client) - break + clients.push(client) } } + log.info("initialized") return { clients, } }, async (state) => { - for (const client of state.clients.values()) { + for (const client of state.clients) { await client.shutdown() } }, @@ -77,9 +85,7 @@ export namespace LSP { .map((x) => x.id) await run(async (client) => { if (!matches.includes(client.serverID)) return - const wait = waitForDiagnostics - ? client.waitForDiagnostics({ path: input }) - : Promise.resolve() + const wait = waitForDiagnostics ? client.waitForDiagnostics({ path: input }) : Promise.resolve() await client.notify.open({ path: input }) return wait }) @@ -97,11 +103,7 @@ export namespace LSP { return results } - export async function hover(input: { - file: string - line: number - character: number - }) { + export async function hover(input: { file: string; line: number; character: number }) { return run((client) => { return client.connection.sendRequest("textDocument/hover", { textDocument: { @@ -117,16 +119,17 @@ export namespace LSP { export async function workspaceSymbol(query: string) { return run((client) => - client.connection.sendRequest("workspace/symbol", { - query, - }), + client.connection + .sendRequest("workspace/symbol", { + query, + }) + .then((result: any) => result.slice(0, 10)) + .catch(() => []), ).then((result) => result.flat() as LSP.Symbol[]) } - async function run( - input: (client: LSPClient.Info) => Promise, - ): Promise { - const clients = await state().then((x) => [...x.clients.values()]) + async function run(input: (client: LSPClient.Info) => Promise): Promise { + const clients = await state().then((x) => x.clients) const tasks = clients.map((x) => input(x)) return Promise.all(tasks) } diff --git a/packages/opencode/src/lsp/language.ts b/packages/opencode/src/lsp/language.ts index 6c0da51b..61686bd9 100644 --- a/packages/opencode/src/lsp/language.ts +++ b/packages/opencode/src/lsp/language.ts @@ -94,4 +94,6 @@ export const LANGUAGE_EXTENSIONS: Record = { ".yml": "yaml", ".mjs": "javascript", ".cjs": "javascript", + ".zig": "zig", + ".zon": "zig", } as const diff --git a/packages/opencode/src/lsp/server.ts b/packages/opencode/src/lsp/server.ts index 39a23f0f..1a3f711c 100644 --- a/packages/opencode/src/lsp/server.ts +++ b/packages/opencode/src/lsp/server.ts @@ -6,6 +6,10 @@ import { Log } from "../util/log" import { BunProc } from "../bun" import { $ } from "bun" import fs from "fs/promises" +import { unique } from "remeda" +import { Ripgrep } from "../file/ripgrep" +import type { LSPClient } from "./client" +import { withTimeout } from "../util/timeout" export namespace LSPServer { const log = Log.create({ service: "lsp.server" }) @@ -13,33 +17,44 @@ export namespace LSPServer { export interface Handle { process: ChildProcessWithoutNullStreams initialization?: Record + onInitialized?: (lsp: LSPClient.Info) => Promise + } + + type RootsFunction = (app: App.Info) => Promise + + const SimpleRoots = (patterns: string[]): RootsFunction => { + return async (app) => { + const files = await Ripgrep.files({ + glob: patterns.map(p => `**/${p}`), + cwd: app.path.root, + }) + const dirs = files.map((file) => path.dirname(file)) + return unique(dirs).map((dir) => path.join(app.path.root, dir)) + } } export interface Info { id: string extensions: string[] - spawn(app: App.Info): Promise + global?: boolean + roots: (app: App.Info) => Promise + spawn(app: App.Info, root: string): Promise } export const Typescript: Info = { id: "typescript", + roots: async (app) => [app.path.root], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"], - async spawn(app) { - const tsserver = await Bun.resolve( - "typescript/lib/tsserver.js", - app.path.cwd, - ).catch(() => {}) + async spawn(app, root) { + const tsserver = await Bun.resolve("typescript/lib/tsserver.js", app.path.cwd).catch(() => {}) if (!tsserver) return - const proc = spawn( - BunProc.which(), - ["x", "typescript-language-server", "--stdio"], - { - env: { - ...process.env, - BUN_BE_BUN: "1", - }, + const proc = spawn(BunProc.which(), ["x", "typescript-language-server", "--stdio"], { + cwd: root, + env: { + ...process.env, + BUN_BE_BUN: "1", }, - ) + }) return { process: proc, initialization: { @@ -47,14 +62,32 @@ export namespace LSPServer { path: tsserver, }, }, + // tsserver sucks and won't start processing codebase until you open a file + onInitialized: async (lsp) => { + const [hint] = await Ripgrep.files({ + cwd: lsp.root, + glob: ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"], + limit: 1, + }) + const wait = new Promise(async (resolve) => { + const notif = lsp.connection.onNotification("$/progress", (params) => { + if (params.value.kind !== "end") return + notif.dispose() + resolve() + }) + await lsp.notify.open({ path: path.join(lsp.root, hint) }) + }) + await withTimeout(wait, 5_000) + }, } }, } export const Gopls: Info = { id: "golang", + roots: SimpleRoots(["go.mod", "go.sum"]), extensions: [".go"], - async spawn() { + async spawn(_, root) { let bin = Bun.which("gopls", { PATH: process.env["PATH"] + ":" + Global.Path.bin, }) @@ -73,24 +106,24 @@ export namespace LSPServer { log.error("Failed to install gopls") return } - bin = path.join( - Global.Path.bin, - "gopls" + (process.platform === "win32" ? ".exe" : ""), - ) + bin = path.join(Global.Path.bin, "gopls" + (process.platform === "win32" ? ".exe" : "")) log.info(`installed gopls`, { bin, }) } return { - process: spawn(bin!), + process: spawn(bin!, { + cwd: root, + }), } }, } export const RubyLsp: Info = { id: "ruby-lsp", + roots: SimpleRoots(["Gemfile"]), extensions: [".rb", ".rake", ".gemspec", ".ru"], - async spawn() { + async spawn(_, root) { let bin = Bun.which("ruby-lsp", { PATH: process.env["PATH"] + ":" + Global.Path.bin, }) @@ -113,16 +146,15 @@ export namespace LSPServer { log.error("Failed to install ruby-lsp") return } - bin = path.join( - Global.Path.bin, - "ruby-lsp" + (process.platform === "win32" ? ".exe" : ""), - ) + bin = path.join(Global.Path.bin, "ruby-lsp" + (process.platform === "win32" ? ".exe" : "")) log.info(`installed ruby-lsp`, { bin, }) } return { - process: spawn(bin!, ["--stdio"]), + process: spawn(bin!, ["--stdio"], { + cwd: root, + }), } }, } @@ -130,17 +162,22 @@ export namespace LSPServer { export const Pyright: Info = { id: "pyright", extensions: [".py", ".pyi"], - async spawn() { - const proc = spawn( - BunProc.which(), - ["x", "pyright-langserver", "--stdio"], - { - env: { - ...process.env, - BUN_BE_BUN: "1", - }, + roots: SimpleRoots([ + "pyproject.toml", + "setup.py", + "setup.cfg", + "requirements.txt", + "Pipfile", + "pyrightconfig.json", + ]), + async spawn(_, root) { + const proc = spawn(BunProc.which(), ["x", "pyright-langserver", "--stdio"], { + cwd: root, + env: { + ...process.env, + BUN_BE_BUN: "1", }, - ) + }) return { process: proc, } @@ -150,7 +187,8 @@ export namespace LSPServer { export const ElixirLS: Info = { id: "elixir-ls", extensions: [".ex", ".exs"], - async spawn() { + roots: SimpleRoots(["mix.exs", "mix.lock"]), + async spawn(_, root) { let binary = Bun.which("elixir-ls") if (!binary) { const elixirLsPath = path.join(Global.Path.bin, "elixir-ls") @@ -158,9 +196,7 @@ export namespace LSPServer { Global.Path.bin, "elixir-ls-master", "release", - process.platform === "win32" - ? "language_server.bar" - : "language_server.sh", + process.platform === "win32" ? "language_server.bar" : "language_server.sh", ) if (!(await Bun.file(binary).exists())) { @@ -172,9 +208,7 @@ export namespace LSPServer { log.info("downloading elixir-ls from GitHub releases") - const response = await fetch( - "https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip", - ) + const response = await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip") if (!response.ok) return const zipPath = path.join(Global.Path.bin, "elixir-ls.zip") await Bun.file(zipPath).write(response) @@ -198,7 +232,114 @@ export namespace LSPServer { } return { - process: spawn(binary), + process: spawn(binary, { + cwd: root, + }), + } + }, + } + + export const Zls: Info = { + id: "zls", + extensions: [".zig", ".zon"], + roots: SimpleRoots(["build.zig"]), + async spawn(_, root) { + let bin = Bun.which("zls", { + PATH: process.env["PATH"] + ":" + Global.Path.bin, + }) + + if (!bin) { + const zig = Bun.which("zig") + if (!zig) { + log.error("Zig is required to use zls. Please install Zig first.") + return + } + + log.info("downloading zls from GitHub releases") + + const releaseResponse = await fetch("https://api.github.com/repos/zigtools/zls/releases/latest") + if (!releaseResponse.ok) { + log.error("Failed to fetch zls release info") + return + } + + const release = await releaseResponse.json() + + const platform = process.platform + const arch = process.arch + let assetName = "" + + let zlsArch: string = arch + if (arch === "arm64") zlsArch = "aarch64" + else if (arch === "x64") zlsArch = "x86_64" + else if (arch === "ia32") zlsArch = "x86" + + let zlsPlatform: string = platform + if (platform === "darwin") zlsPlatform = "macos" + else if (platform === "win32") zlsPlatform = "windows" + + const ext = platform === "win32" ? "zip" : "tar.xz" + + assetName = `zls-${zlsArch}-${zlsPlatform}.${ext}` + + const supportedCombos = [ + "zls-x86_64-linux.tar.xz", + "zls-x86_64-macos.tar.xz", + "zls-x86_64-windows.zip", + "zls-aarch64-linux.tar.xz", + "zls-aarch64-macos.tar.xz", + "zls-aarch64-windows.zip", + "zls-x86-linux.tar.xz", + "zls-x86-windows.zip", + ] + + if (!supportedCombos.includes(assetName)) { + log.error(`Platform ${platform} and architecture ${arch} is not supported by zls`) + return + } + + const asset = release.assets.find((a: any) => a.name === assetName) + if (!asset) { + log.error(`Could not find asset ${assetName} in latest zls release`) + return + } + + const downloadUrl = asset.browser_download_url + const downloadResponse = await fetch(downloadUrl) + if (!downloadResponse.ok) { + log.error("Failed to download zls") + return + } + + const tempPath = path.join(Global.Path.bin, assetName) + await Bun.file(tempPath).write(downloadResponse) + + if (ext === "zip") { + await $`unzip -o -q ${tempPath}`.cwd(Global.Path.bin).nothrow() + } else { + await $`tar -xf ${tempPath}`.cwd(Global.Path.bin).nothrow() + } + + await fs.rm(tempPath, { force: true }) + + bin = path.join(Global.Path.bin, "zls" + (platform === "win32" ? ".exe" : "")) + + if (!(await Bun.file(bin).exists())) { + log.error("Failed to extract zls binary") + return + } + + if (platform !== "win32") { + await $`chmod +x ${bin}`.nothrow() + } + + log.info(`installed zls`, { bin }) + } + + return { + process: spawn(bin, { + cwd: root, + }), } }, } diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index f05d15ce..920db882 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -91,8 +91,7 @@ export namespace Provider { if (!info || info.type !== "oauth") return if (!info.access || info.expires < Date.now()) { const tokens = await copilot.access(info.refresh) - if (!tokens) - throw new Error("GitHub Copilot authentication expired") + if (!tokens) throw new Error("GitHub Copilot authentication expired") await Auth.set("github-copilot", { type: "oauth", ...tokens, @@ -100,25 +99,27 @@ export namespace Provider { info.access = tokens.access } let isAgentCall = false + let isVisionRequest = false try { - const body = - typeof init.body === "string" - ? JSON.parse(init.body) - : init.body + const body = typeof init.body === "string" ? JSON.parse(init.body) : init.body if (body?.messages) { - isAgentCall = body.messages.some( + isAgentCall = body.messages.some((msg: any) => msg.role && ["tool", "assistant"].includes(msg.role)) + isVisionRequest = body.messages.some( (msg: any) => - msg.role && ["tool", "assistant"].includes(msg.role), + Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"), ) } } catch {} - const headers = { + const headers: Record = { ...init.headers, ...copilot.HEADERS, Authorization: `Bearer ${info.access}`, "Openai-Intent": "conversation-edits", "X-Initiator": isAgentCall ? "agent" : "user", } + if (isVisionRequest) { + headers["Copilot-Vision-Request"] = "true" + } delete headers["x-api-key"] return fetch(input, { ...init, @@ -138,14 +139,11 @@ export namespace Provider { } }, "amazon-bedrock": async () => { - if (!process.env["AWS_PROFILE"] && !process.env["AWS_ACCESS_KEY_ID"]) - return { autoload: false } + if (!process.env["AWS_PROFILE"] && !process.env["AWS_ACCESS_KEY_ID"]) return { autoload: false } const region = process.env["AWS_REGION"] ?? "us-east-1" - const { fromNodeProviderChain } = await import( - await BunProc.install("@aws-sdk/credential-providers") - ) + const { fromNodeProviderChain } = await import(await BunProc.install("@aws-sdk/credential-providers")) return { autoload: true, options: { @@ -157,9 +155,7 @@ export namespace Provider { switch (regionPrefix) { case "us": { - const modelRequiresPrefix = ["claude", "deepseek"].some((m) => - modelID.includes(m), - ) + const modelRequiresPrefix = ["claude", "deepseek"].some((m) => modelID.includes(m)) if (modelRequiresPrefix) { modelID = `${regionPrefix}.${modelID}` } @@ -174,25 +170,18 @@ export namespace Provider { "eu-south-1", "eu-south-2", ].some((r) => region.includes(r)) - const modelRequiresPrefix = [ - "claude", - "nova-lite", - "nova-micro", - "llama3", - "pixtral", - ].some((m) => modelID.includes(m)) + const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) => + modelID.includes(m), + ) if (regionRequiresPrefix && modelRequiresPrefix) { modelID = `${regionPrefix}.${modelID}` } break } case "ap": { - const modelRequiresPrefix = [ - "claude", - "nova-lite", - "nova-micro", - "nova-pro", - ].some((m) => modelID.includes(m)) + const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) => + modelID.includes(m), + ) if (modelRequiresPrefix) { regionPrefix = "apac" modelID = `${regionPrefix}.${modelID}` @@ -230,10 +219,7 @@ export namespace Provider { options: Record } } = {} - const models = new Map< - string, - { info: ModelsDev.Model; language: LanguageModel } - >() + const models = new Map() const sdk = new Map() log.info("init") @@ -308,9 +294,7 @@ export namespace Provider { database[providerID] = parsed } - const disabled = await Config.get().then( - (cfg) => new Set(cfg.disabled_providers ?? []), - ) + const disabled = await Config.get().then((cfg) => new Set(cfg.disabled_providers ?? [])) // load env for (const [providerID, provider] of Object.entries(database)) { if (disabled.has(providerID)) continue @@ -337,12 +321,7 @@ export namespace Provider { if (disabled.has(providerID)) continue const result = await fn(database[providerID]) if (result && (result.autoload || providers[providerID])) { - mergeProvider( - providerID, - result.options ?? {}, - "custom", - result.getModel, - ) + mergeProvider(providerID, result.options ?? {}, "custom", result.getModel) } } @@ -379,7 +358,7 @@ export namespace Provider { const existing = s.sdk.get(provider.id) if (existing) return existing const pkg = provider.npm ?? provider.id - const mod = await import(await BunProc.install(pkg, "latest")) + const mod = await import(await BunProc.install(pkg, "beta")) const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!] const loaded = fn(s.providers[provider.id]?.options) s.sdk.set(provider.id, loaded) @@ -406,9 +385,7 @@ export namespace Provider { const sdk = await getSDK(provider.info) try { - const language = provider.getModel - ? await provider.getModel(sdk, modelID) - : sdk.languageModel(modelID) + const language = provider.getModel ? await provider.getModel(sdk, modelID) : sdk.languageModel(modelID) log.info("found", { providerID, modelID }) s.models.set(key, { info, @@ -435,10 +412,7 @@ export namespace Provider { export function sort(models: ModelsDev.Model[]) { return sortBy( models, - [ - (model) => priority.findIndex((filter) => model.id.includes(filter)), - "desc", - ], + [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"], [(model) => (model.id.includes("latest") ? 0 : 1), "asc"], [(model) => model.id, "desc"], ) @@ -449,11 +423,7 @@ export namespace Provider { if (cfg.model) return parseModel(cfg.model) const provider = await list() .then((val) => Object.values(val)) - .then((x) => - x.find( - (p) => !cfg.provider || Object.keys(cfg.provider).includes(p.info.id), - ), - ) + .then((x) => x.find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.info.id))) if (!provider) throw new Error("no providers found") const [model] = sort(Object.values(provider.info.models)) if (!model) throw new Error("no models found") @@ -536,9 +506,11 @@ export namespace Provider { if (schema instanceof z.ZodUnion) { return z.union( - schema.options.map((option: z.ZodTypeAny) => - optionalToNullable(option), - ) as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]], + schema.options.map((option: z.ZodTypeAny) => optionalToNullable(option)) as [ + z.ZodTypeAny, + z.ZodTypeAny, + ...z.ZodTypeAny[], + ], ) } diff --git a/packages/opencode/src/provider/transform.ts b/packages/opencode/src/provider/transform.ts index d5e140b3..433e9f41 100644 --- a/packages/opencode/src/provider/transform.ts +++ b/packages/opencode/src/provider/transform.ts @@ -1,22 +1,21 @@ -import type { LanguageModelV1Prompt } from "ai" +import type { ModelMessage } from "ai" import { unique } from "remeda" export namespace ProviderTransform { - export function message( - msgs: LanguageModelV1Prompt, - providerID: string, - modelID: string, - ) { + export function message(msgs: ModelMessage[], providerID: string, modelID: string) { if (providerID === "anthropic" || modelID.includes("anthropic")) { const system = msgs.filter((msg) => msg.role === "system").slice(0, 2) const final = msgs.filter((msg) => msg.role !== "system").slice(-2) for (const msg of unique([...system, ...final])) { - msg.providerMetadata = { - ...msg.providerMetadata, + msg.providerOptions = { + ...msg.providerOptions, anthropic: { cacheControl: { type: "ephemeral" }, }, + openaiCompatible: { + cache_control: { type: "ephemeral" }, + }, } } } @@ -25,8 +24,8 @@ export namespace ProviderTransform { const final = msgs.filter((msg) => msg.role !== "system").slice(-2) for (const msg of unique([...system, ...final])) { - msg.providerMetadata = { - ...msg.providerMetadata, + msg.providerOptions = { + ...msg.providerOptions, bedrock: { cachePoint: { type: "ephemeral" }, }, diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index df645cd8..38a80897 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -6,7 +6,6 @@ import { streamSSE } from "hono/streaming" import { Session } from "../session" import { resolver, validator as zValidator } from "hono-openapi/zod" import { z } from "zod" -import { Message } from "../session/message" import { Provider } from "../provider/provider" import { App } from "../app/app" import { mapValues } from "remeda" @@ -16,6 +15,7 @@ import { Ripgrep } from "../file/ripgrep" import { Config } from "../config/config" import { File } from "../file" import { LSP } from "../lsp" +import { MessageV2 } from "../session/message-v2" const ERRORS = { 400: { @@ -51,12 +51,9 @@ export namespace Server { status: 400, }) } - return c.json( - new NamedError.Unknown({ message: err.toString() }).toObject(), - { - status: 400, - }, - ) + return c.json(new NamedError.Unknown({ message: err.toString() }).toObject(), { + status: 400, + }) }) .use(async (c, next) => { log.info("request", { @@ -407,7 +404,7 @@ export namespace Server { description: "List of messages", content: { "application/json": { - schema: resolver(Message.Info.array()), + schema: resolver(MessageV2.Info.array()), }, }, }, @@ -433,7 +430,7 @@ export namespace Server { description: "Created message", content: { "application/json": { - schema: resolver(Message.Info), + schema: resolver(MessageV2.Assistant), }, }, }, @@ -450,7 +447,7 @@ export namespace Server { z.object({ providerID: z.string(), modelID: z.string(), - parts: Message.MessagePart.array(), + parts: MessageV2.UserPart.array(), }), ), async (c) => { @@ -481,15 +478,10 @@ export namespace Server { }, }), async (c) => { - const providers = await Provider.list().then((x) => - mapValues(x, (item) => item.info), - ) + const providers = await Provider.list().then((x) => mapValues(x, (item) => item.info)) return c.json({ providers: Object.values(providers), - default: mapValues( - providers, - (item) => Provider.sort(Object.values(item.models))[0].id, - ), + default: mapValues(providers, (item) => Provider.sort(Object.values(item.models))[0].id), }) }, ) @@ -566,7 +558,7 @@ export namespace Server { description: "Symbols", content: { "application/json": { - schema: resolver(z.unknown().array()), + schema: resolver(LSP.Symbol.array()), }, }, }, @@ -629,16 +621,7 @@ export namespace Server { description: "File status", content: { "application/json": { - schema: resolver( - z - .object({ - file: z.string(), - added: z.number().int(), - removed: z.number().int(), - status: z.enum(["added", "deleted", "modified"]), - }) - .array(), - ), + schema: resolver(File.Info.array()), }, }, }, @@ -649,6 +632,55 @@ export namespace Server { return c.json(content) }, ) + .post( + "/log", + describeRoute({ + description: "Write a log entry to the server logs", + responses: { + 200: { + description: "Log entry written successfully", + content: { + "application/json": { + schema: resolver(z.boolean()), + }, + }, + }, + }, + }), + zValidator( + "json", + z.object({ + service: z.string().openapi({ description: "Service name for the log entry" }), + level: z.enum(["debug", "info", "error", "warn"]).openapi({ description: "Log level" }), + message: z.string().openapi({ description: "Log message" }), + extra: z + .record(z.string(), z.any()) + .optional() + .openapi({ description: "Additional metadata for the log entry" }), + }), + ), + async (c) => { + const { service, level, message, extra } = c.req.valid("json") + const logger = Log.create({ service }) + + switch (level) { + case "debug": + logger.debug(message, extra) + break + case "info": + logger.info(message, extra) + break + case "error": + logger.error(message, extra) + break + case "warn": + logger.warn(message, extra) + break + } + + return c.json(true) + }, + ) return result } diff --git a/packages/opencode/src/session/index.ts b/packages/opencode/src/session/index.ts index f4e80ce9..a1a1d183 100644 --- a/packages/opencode/src/session/index.ts +++ b/packages/opencode/src/session/index.ts @@ -1,19 +1,17 @@ -import path from "node:path" +import path from "path" import { Decimal } from "decimal.js" import { z, ZodSchema } from "zod" import { generateText, LoadAPIKeyError, - convertToCoreMessages, streamText, tool, wrapLanguageModel, type Tool as AITool, type LanguageModelUsage, - type CoreMessage, - type UIMessage, type ProviderMetadata, - type Attachment, + type ModelMessage, + stepCountIs, } from "ai" import PROMPT_INITIALIZE from "../session/prompt/initialize.txt" @@ -34,9 +32,9 @@ import { Storage } from "../storage/storage" import type { Tool } from "../tool/tool" import { Log } from "../util/log" import { NamedError } from "../util/error" -import { Message } from "./message" import { SystemPrompt } from "./system" import { FileTime } from "../file/time" +import { MessageV2 } from "./message-v2" export namespace Session { const log = Log.create({ service: "session" }) @@ -101,7 +99,8 @@ export namespace Session { Error: Bus.event( "session.error", z.object({ - error: Message.Info.shape.metadata.shape.error, + sessionID: z.string().optional(), + error: MessageV2.Assistant.shape.error, }), ), } @@ -110,7 +109,7 @@ export namespace Session { "session", () => { const sessions = new Map() - const messages = new Map() + const messages = new Map() const pending = new Map() return { @@ -131,9 +130,7 @@ export namespace Session { id: Identifier.descending("session"), version: Installation.VERSION, parentID, - title: - (parentID ? "Child session - " : "New Session - ") + - new Date().toISOString(), + title: (parentID ? "Child session - " : "New Session - ") + new Date().toISOString(), time: { created: Date.now(), updated: Date.now(), @@ -211,10 +208,10 @@ export namespace Session { } export async function messages(sessionID: string) { - const result = [] as Message.Info[] + const result = [] as MessageV2.Info[] const list = Storage.list("session/message/" + sessionID) for await (const p of list) { - const read = await Storage.readJSON(p) + const read = await Storage.readJSON(p) result.push(read) } result.sort((a, b) => (a.id > b.id ? 1 : -1)) @@ -222,9 +219,7 @@ export namespace Session { } export async function getMessage(sessionID: string, messageID: string) { - return Storage.readJSON( - "session/message/" + sessionID + "/" + messageID, - ) + return Storage.readJSON("session/message/" + sessionID + "/" + messageID) } export async function* list() { @@ -275,12 +270,9 @@ export namespace Session { } } - async function updateMessage(msg: Message.Info) { - await Storage.writeJSON( - "session/message/" + msg.metadata.sessionID + "/" + msg.id, - msg, - ) - Bus.publish(Message.Event.Updated, { + async function updateMessage(msg: MessageV2.Info) { + await Storage.writeJSON("session/message/" + msg.sessionID + "/" + msg.id, msg) + Bus.publish(MessageV2.Event.Updated, { info: msg, }) } @@ -289,10 +281,11 @@ export namespace Session { sessionID: string providerID: string modelID: string - parts: Message.MessagePart[] + parts: MessageV2.UserPart[] system?: string[] tools?: Tool.Info[] }) { + using abort = lock(input.sessionID) const l = log.clone().tag("session", input.sessionID) l.info("chatting") const model = await Provider.getModel(input.providerID, input.modelID) @@ -302,14 +295,9 @@ export namespace Session { if (session.revert) { const trimmed = [] for (const msg of msgs) { - if ( - msg.id > session.revert.messageID || - (msg.id === session.revert.messageID && session.revert.part === 0) - ) { - await Storage.remove( - "session/message/" + input.sessionID + "/" + msg.id, - ) - await Bus.publish(Message.Event.Removed, { + if (msg.id > session.revert.messageID || (msg.id === session.revert.messageID && session.revert.part === 0)) { + await Storage.remove("session/message/" + input.sessionID + "/" + msg.id) + await Bus.publish(MessageV2.Event.Removed, { sessionID: input.sessionID, messageID: msg.id, }) @@ -328,22 +316,15 @@ export namespace Session { }) } - const previous = msgs.at(-1) + const previous = msgs.at(-1) as MessageV2.Assistant // auto summarize if too long - if (previous?.metadata.assistant) { + if (previous) { const tokens = - previous.metadata.assistant.tokens.input + - previous.metadata.assistant.tokens.cache.read + - previous.metadata.assistant.tokens.cache.write + - previous.metadata.assistant.tokens.output + previous.tokens.input + previous.tokens.cache.read + previous.tokens.cache.write + previous.tokens.output if ( model.info.limit.context && - tokens > - Math.max( - (model.info.limit.context - (model.info.limit.output ?? 0)) * 0.9, - 0, - ) + tokens > Math.max((model.info.limit.context - (model.info.limit.output ?? 0)) * 0.9, 0) ) { await summarize({ sessionID: input.sessionID, @@ -354,16 +335,12 @@ export namespace Session { } } - using abort = lock(input.sessionID) - - const lastSummary = msgs.findLast( - (msg) => msg.metadata.assistant?.summary === true, - ) + const lastSummary = msgs.findLast((msg) => msg.role === "assistant" && msg.summary === true) if (lastSummary) msgs = msgs.filter((msg) => msg.id >= lastSummary.id) const app = App.info() input.parts = await Promise.all( - input.parts.map(async (part): Promise => { + input.parts.map(async (part): Promise => { if (part.type === "file") { const url = new URL(part.url) switch (url.protocol) { @@ -371,13 +348,13 @@ export namespace Session { const filepath = path.join(app.path.cwd, url.pathname) let file = Bun.file(filepath) - if (part.mediaType === "text/plain") { + if (part.mime === "text/plain") { let text = await file.text() const range = { start: url.searchParams.get("start"), end: url.searchParams.get("end"), } - if (range.start != null && part.mediaType === "text/plain") { + if (range.start != null && part.mime === "text/plain") { const lines = text.split("\n") const start = parseInt(range.start) const end = range.end ? parseInt(range.end) : lines.length @@ -387,12 +364,7 @@ export namespace Session { return [ { type: "text", - text: [ - "Called the Read tool on " + url.pathname, - "", - text, - "", - ].join("\n"), + text: ["Called the Read tool on " + url.pathname, "", text, ""].join("\n"), }, ] } @@ -400,14 +372,12 @@ export namespace Session { return [ { type: "text", - text: ["Called the Read tool on " + url.pathname].join("\n"), + text: `Called the Read tool with the following input: {\"filePath\":\"${url.pathname}\"}`, }, { type: "file", - url: - `data:${part.mediaType};base64,` + - Buffer.from(await file.bytes()).toString("base64url"), - mediaType: part.mediaType, + url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"), + mime: part.mime, filename: part.filename!, }, ] @@ -418,20 +388,24 @@ export namespace Session { ).then((x) => x.flat()) if (msgs.length === 0 && !session.parentID) { generateText({ - maxTokens: input.providerID === "google" ? 1024 : 20, + maxOutputTokens: input.providerID === "google" ? 1024 : 20, providerOptions: model.info.options, messages: [ ...SystemPrompt.title(input.providerID).map( - (x): CoreMessage => ({ + (x): ModelMessage => ({ role: "system", content: x, }), ), - ...convertToCoreMessages([ + ...MessageV2.toModelMessage([ { + id: Identifier.ascending("message"), role: "user", - content: "", - parts: toParts(input.parts).parts, + sessionID: input.sessionID, + parts: input.parts, + time: { + created: Date.now(), + }, }, ]), ], @@ -445,55 +419,44 @@ export namespace Session { }) .catch(() => {}) } - const snapshot = await Snapshot.create(input.sessionID) - const msg: Message.Info = { - role: "user", + const msg: MessageV2.Info = { id: Identifier.ascending("message"), + role: "user", + sessionID: input.sessionID, parts: input.parts, - metadata: { - time: { - created: Date.now(), - }, - sessionID: input.sessionID, - tool: {}, - snapshot, + time: { + created: Date.now(), }, } await updateMessage(msg) msgs.push(msg) - const system = input.system ?? SystemPrompt.provider(input.providerID) + const system = input.system ?? SystemPrompt.provider(input.providerID, input.modelID) system.push(...(await SystemPrompt.environment())) system.push(...(await SystemPrompt.custom())) - const next: Message.Info = { + const next: MessageV2.Info = { id: Identifier.ascending("message"), role: "assistant", parts: [], - metadata: { - snapshot, - assistant: { - system, - path: { - cwd: app.path.cwd, - root: app.path.root, - }, - cost: 0, - tokens: { - input: 0, - output: 0, - reasoning: 0, - cache: { read: 0, write: 0 }, - }, - modelID: input.modelID, - providerID: input.providerID, - }, - time: { - created: Date.now(), - }, - sessionID: input.sessionID, - tool: {}, + system, + path: { + cwd: app.path.cwd, + root: app.path.root, }, + cost: 0, + tokens: { + input: 0, + output: 0, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + modelID: input.modelID, + providerID: input.providerID, + time: { + created: Date.now(), + }, + sessionID: input.sessionID, } await updateMessage(next) const tools: Record = {} @@ -502,48 +465,29 @@ export namespace Session { tools[item.id.replaceAll(".", "_")] = tool({ id: item.id as any, description: item.description, - parameters: item.parameters as ZodSchema, + inputSchema: item.parameters as ZodSchema, async execute(args, opts) { - const start = Date.now() - try { - const result = await item.execute(args, { - sessionID: input.sessionID, - abort: abort.signal, - messageID: next.id, - metadata: async (val) => { - next.metadata.tool[opts.toolCallId] = { - ...val, - time: { - start: 0, - end: 0, - }, - } - await updateMessage(next) - }, - }) - next.metadata!.tool![opts.toolCallId] = { - ...result.metadata, - snapshot: await Snapshot.create(input.sessionID), - time: { - start, - end: Date.now(), - }, - } - await updateMessage(next) - return result.output - } catch (e: any) { - next.metadata!.tool![opts.toolCallId] = { - error: true, - message: e.toString(), - title: e.toString(), - snapshot: await Snapshot.create(input.sessionID), - time: { - start, - end: Date.now(), - }, - } - await updateMessage(next) - return e.toString() + const result = await item.execute(args, { + sessionID: input.sessionID, + abort: abort.signal, + messageID: next.id, + metadata: async (val) => { + const match = next.parts.find( + (p): p is MessageV2.ToolPart => p.type === "tool" && p.id === opts.toolCallId, + ) + if (match && match.state.status === "running") { + match.state.title = val.title + match.state.metadata = val.metadata + } + await updateMessage(next) + }, + }) + return result + }, + toModelOutput(result) { + return { + type: "text", + value: result.output, } }, }) @@ -553,109 +497,44 @@ export namespace Session { const execute = item.execute if (!execute) continue item.execute = async (args, opts) => { - const start = Date.now() - try { - const result = await execute(args, opts) - next.metadata!.tool![opts.toolCallId] = { - ...result.metadata, - snapshot: await Snapshot.create(input.sessionID), - time: { - start, - end: Date.now(), - }, - } - await updateMessage(next) - return result.content - .filter((x: any) => x.type === "text") - .map((x: any) => x.text) - .join("\n\n") - } catch (e: any) { - next.metadata!.tool![opts.toolCallId] = { - error: true, - message: e.toString(), - snapshot: await Snapshot.create(input.sessionID), - title: "mcp", - time: { - start, - end: Date.now(), - }, - } - await updateMessage(next) - return e.toString() + const result = await execute(args, opts) + const output = result.content + .filter((x: any) => x.type === "text") + .map((x: any) => x.text) + .join("\n\n") + + return { + output, + } + } + item.toModelOutput = (result) => { + return { + type: "text", + value: result.output, } } tools[key] = item } - let text: Message.TextPart | undefined + let text: MessageV2.TextPart = { + type: "text", + text: "", + } const result = streamText({ - onStepFinish: async (step) => { - log.info("step finish", { finishReason: step.finishReason }) - const assistant = next.metadata!.assistant! - const usage = getUsage(model.info, step.usage, step.providerMetadata) - assistant.cost += usage.cost - assistant.tokens = usage.tokens - await updateMessage(next) - if (text) { - Bus.publish(Message.Event.PartUpdated, { - part: text, - messageID: next.id, - sessionID: next.metadata.sessionID, - }) - } - text = undefined - }, - onError(err) { - log.error("callback error", err) - switch (true) { - case LoadAPIKeyError.isInstance(err.error): - next.metadata.error = new Provider.AuthError( - { - providerID: input.providerID, - message: err.error.message, - }, - { cause: err.error }, - ).toObject() - break - case err.error instanceof Error: - next.metadata.error = new NamedError.Unknown( - { message: err.error.toString() }, - { cause: err.error }, - ).toObject() - break - default: - next.metadata.error = new NamedError.Unknown( - { message: JSON.stringify(err.error) }, - { cause: err.error }, - ) - } - Bus.publish(Event.Error, { - error: next.metadata.error, - }) - }, - // async prepareStep(step) { - // next.parts.push({ - // type: "step-start", - // }) - // await updateMessage(next) - // return step - // }, - toolCallStreaming: true, + onError() {}, maxRetries: 10, - maxTokens: Math.max(0, model.info.limit.output) || undefined, + maxOutputTokens: Math.max(0, model.info.limit.output) || undefined, abortSignal: abort.signal, - maxSteps: 1000, + stopWhen: stepCountIs(1000), providerOptions: model.info.options, messages: [ ...system.map( - (x): CoreMessage => ({ + (x): ModelMessage => ({ role: "system", content: x, }), ), - ...convertToCoreMessages( - msgs.map(toUIMessage).filter((x) => x.parts.length > 0), - ), + ...MessageV2.toModelMessage(msgs), ], temperature: model.info.temperature ? 0 : undefined, tools: model.info.tool_call === false ? undefined : tools, @@ -665,11 +544,8 @@ export namespace Session { { async transformParams(args) { if (args.type === "stream") { - args.params.prompt = ProviderTransform.message( - args.params.prompt, - input.providerID, - input.modelID, - ) + // @ts-expect-error + args.params.prompt = ProviderTransform.message(args.params.prompt, input.providerID, input.modelID) } return args.params }, @@ -683,122 +559,161 @@ export namespace Session { type: value.type, }) switch (value.type) { - case "step-start": + case "start": + break + + case "tool-input-start": + next.parts.push({ + type: "tool", + tool: value.toolName, + id: value.id, + state: { + status: "pending", + }, + }) + Bus.publish(MessageV2.Event.PartUpdated, { + part: next.parts[next.parts.length - 1], + sessionID: next.sessionID, + messageID: next.id, + }) + break + + case "tool-input-delta": + break + + case "tool-call": { + const match = next.parts.find( + (p): p is MessageV2.ToolPart => p.type === "tool" && p.id === value.toolCallId, + ) + if (match) { + match.state = { + status: "running", + input: value.input, + time: { + start: Date.now(), + }, + } + Bus.publish(MessageV2.Event.PartUpdated, { + part: match, + sessionID: next.sessionID, + messageID: next.id, + }) + } + break + } + case "tool-result": { + const match = next.parts.find( + (p): p is MessageV2.ToolPart => p.type === "tool" && p.id === value.toolCallId, + ) + if (match && match.state.status === "running") { + match.state = { + status: "completed", + input: value.input, + output: value.output.output, + metadata: value.output.metadata, + title: value.output.title, + time: { + start: match.state.time.start, + end: Date.now(), + }, + } + Bus.publish(MessageV2.Event.PartUpdated, { + part: match, + sessionID: next.sessionID, + messageID: next.id, + }) + } + break + } + + case "tool-error": { + const match = next.parts.find( + (p): p is MessageV2.ToolPart => p.type === "tool" && p.id === value.toolCallId, + ) + if (match && match.state.status === "running") { + match.state = { + status: "error", + input: value.input, + error: (value.error as any).toString(), + time: { + start: match.state.time.start, + end: Date.now(), + }, + } + Bus.publish(MessageV2.Event.PartUpdated, { + part: match, + sessionID: next.sessionID, + messageID: next.id, + }) + } + break + } + + case "error": + throw value.error + + case "start-step": next.parts.push({ type: "step-start", }) break - case "text-delta": - if (!text) { - text = { - type: "text", - text: value.textDelta, - } - next.parts.push(text) - break - } else text.text += value.textDelta + + case "finish-step": + const usage = getUsage(model.info, value.usage, value.providerMetadata) + next.cost += usage.cost + next.tokens = usage.tokens break - case "tool-call": { - const [match] = next.parts.flatMap((p) => - p.type === "tool-invocation" && - p.toolInvocation.toolCallId === value.toolCallId - ? [p] - : [], - ) - if (!match) break - match.toolInvocation.args = value.args - match.toolInvocation.state = "call" - Bus.publish(Message.Event.PartUpdated, { - part: match, - messageID: next.id, - sessionID: next.metadata.sessionID, - }) - break - } - - case "tool-call-streaming-start": - next.parts.push({ - type: "tool-invocation", - toolInvocation: { - state: "partial-call", - toolName: value.toolName, - toolCallId: value.toolCallId, - args: {}, - }, - }) - Bus.publish(Message.Event.PartUpdated, { - part: next.parts[next.parts.length - 1], - messageID: next.id, - sessionID: next.metadata.sessionID, - }) - break - - case "tool-call-delta": - continue - - // for some reason ai sdk claims to not send this part but it does - // @ts-expect-error - case "tool-result": - const match = next.parts.find( - (p) => - p.type === "tool-invocation" && - // @ts-expect-error - p.toolInvocation.toolCallId === value.toolCallId, - ) - if (match && match.type === "tool-invocation") { - match.toolInvocation = { - // @ts-expect-error - args: value.args, - // @ts-expect-error - toolCallId: value.toolCallId, - // @ts-expect-error - toolName: value.toolName, - state: "result", - // @ts-expect-error - result: value.result as string, - } - Bus.publish(Message.Event.PartUpdated, { - part: match, - messageID: next.id, - sessionID: next.metadata.sessionID, - }) + case "text-start": + text = { + type: "text", + text: "", } break - case "finish": - log.info("message finish", { - reason: value.finishReason, - }) - const assistant = next.metadata!.assistant! - const usage = getUsage( - model.info, - value.usage, - value.providerMetadata, - ) - assistant.cost += usage.cost - await updateMessage(next) - if (value.finishReason === "length") - throw new Message.OutputLengthError({}) + case "text": + if (text.text === "") next.parts.push(text) + text.text += value.text break + + case "text-end": + Bus.publish(MessageV2.Event.PartUpdated, { + part: text, + sessionID: next.sessionID, + messageID: next.id, + }) + break + + case "finish": + next.time.completed = Date.now() + break + default: l.info("unhandled", { - type: value.type, + ...value, }) continue } await updateMessage(next) } - } catch (e: any) { - log.error("stream error", { + } catch (e) { + log.error("", { error: e, }) switch (true) { - case Message.OutputLengthError.isInstance(e): - next.metadata.error = e + case e instanceof DOMException && e.name === "AbortError": + next.error = new MessageV2.AbortedError( + { message: e.message }, + { + cause: e, + }, + ).toObject() + break + case MessageV2.OutputLengthError.isInstance(e): + next.error = e break case LoadAPIKeyError.isInstance(e): - next.metadata.error = new Provider.AuthError( + next.error = new Provider.AuthError( { providerID: input.providerID, message: e.message, @@ -807,43 +722,37 @@ export namespace Session { ).toObject() break case e instanceof Error: - next.metadata.error = new NamedError.Unknown( - { message: e.toString() }, - { cause: e }, - ).toObject() + next.error = new NamedError.Unknown({ message: e.toString() }, { cause: e }).toObject() break default: - next.metadata.error = new NamedError.Unknown( - { message: JSON.stringify(e) }, - { cause: e }, - ) + next.error = new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e }) } Bus.publish(Event.Error, { - error: next.metadata.error, + sessionID: next.sessionID, + error: next.error, }) } - next.metadata!.time.completed = Date.now() for (const part of next.parts) { - if ( - part.type === "tool-invocation" && - part.toolInvocation.state !== "result" - ) { - part.toolInvocation = { - ...part.toolInvocation, - state: "result", - result: "request was aborted", + if (part.type === "tool" && part.state.status !== "completed") { + part.state = { + status: "error", + error: "Tool execution aborted", + time: { + start: Date.now(), + end: Date.now(), + }, + input: {}, } } } + next.time.completed = Date.now() await updateMessage(next) return next } - export async function revert(input: { - sessionID: string - messageID: string - part: number - }) { + export async function revert(_input: { sessionID: string; messageID: string; part: number }) { + // TODO + /* const message = await getMessage(input.sessionID, input.messageID) if (!message) return const part = message.parts[input.part] @@ -871,77 +780,66 @@ export namespace Session { snapshot, } }) + */ } export async function unrevert(sessionID: string) { const session = await get(sessionID) if (!session) return if (!session.revert) return - if (session.revert.snapshot) - await Snapshot.restore(sessionID, session.revert.snapshot) + if (session.revert.snapshot) await Snapshot.restore(sessionID, session.revert.snapshot) update(sessionID, (draft) => { draft.revert = undefined }) } - export async function summarize(input: { - sessionID: string - providerID: string - modelID: string - }) { + export async function summarize(input: { sessionID: string; providerID: string; modelID: string }) { using abort = lock(input.sessionID) const msgs = await messages(input.sessionID) - const lastSummary = msgs.findLast( - (msg) => msg.metadata.assistant?.summary === true, - )?.id + const lastSummary = msgs.findLast((msg) => msg.role === "assistant" && msg.summary === true)?.id const filtered = msgs.filter((msg) => !lastSummary || msg.id >= lastSummary) const model = await Provider.getModel(input.providerID, input.modelID) const app = App.info() const system = SystemPrompt.summarize(input.providerID) - const next: Message.Info = { + const next: MessageV2.Info = { id: Identifier.ascending("message"), role: "assistant", parts: [], - metadata: { - tool: {}, - sessionID: input.sessionID, - assistant: { - system, - path: { - cwd: app.path.cwd, - root: app.path.root, - }, - summary: true, - cost: 0, - modelID: input.modelID, - providerID: input.providerID, - tokens: { - input: 0, - output: 0, - reasoning: 0, - cache: { read: 0, write: 0 }, - }, - }, - time: { - created: Date.now(), - }, + sessionID: input.sessionID, + system, + path: { + cwd: app.path.cwd, + root: app.path.root, + }, + summary: true, + cost: 0, + modelID: input.modelID, + providerID: input.providerID, + tokens: { + input: 0, + output: 0, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + time: { + created: Date.now(), }, } await updateMessage(next) - let text: Message.TextPart | undefined + let text: MessageV2.TextPart | undefined const result = streamText({ abortSignal: abort.signal, model: model.language, messages: [ ...system.map( - (x): CoreMessage => ({ + (x): ModelMessage => ({ role: "system", content: x, }), ), - ...convertToCoreMessages(filtered.map(toUIMessage)), + ...MessageV2.toModelMessage(filtered), { role: "user", content: [ @@ -953,45 +851,80 @@ export namespace Session { }, ], onStepFinish: async (step) => { - const assistant = next.metadata!.assistant! const usage = getUsage(model.info, step.usage, step.providerMetadata) - assistant.cost += usage.cost - assistant.tokens = usage.tokens + next.cost += usage.cost + next.tokens = usage.tokens await updateMessage(next) if (text) { - Bus.publish(Message.Event.PartUpdated, { + Bus.publish(MessageV2.Event.PartUpdated, { part: text, messageID: next.id, - sessionID: next.metadata.sessionID, + sessionID: next.sessionID, }) } text = undefined }, async onFinish(input) { - const assistant = next.metadata!.assistant! const usage = getUsage(model.info, input.usage, input.providerMetadata) - assistant.cost += usage.cost - assistant.tokens = usage.tokens - next.metadata!.time.completed = Date.now() + next.cost += usage.cost + next.tokens = usage.tokens + next.time.completed = Date.now() await updateMessage(next) }, }) - for await (const value of result.fullStream) { - switch (value.type) { - case "text-delta": - if (!text) { - text = { - type: "text", - text: value.textDelta, - } - next.parts.push(text) - } else text.text += value.textDelta - - await updateMessage(next) - break + try { + for await (const value of result.fullStream) { + switch (value.type) { + case "text": + if (!text) { + text = { + type: "text", + text: value.text, + } + next.parts.push(text) + } else text.text += value.text + await updateMessage(next) + break + } } + } catch (e: any) { + log.error("summarize stream error", { + error: e, + }) + switch (true) { + case e instanceof DOMException && e.name === "AbortError": + next.error = new MessageV2.AbortedError( + { message: e.message }, + { + cause: e, + }, + ).toObject() + break + case MessageV2.OutputLengthError.isInstance(e): + next.error = e + break + case LoadAPIKeyError.isInstance(e): + next.error = new Provider.AuthError( + { + providerID: input.providerID, + message: e.message, + }, + { cause: e }, + ).toObject() + break + case e instanceof Error: + next.error = new NamedError.Unknown({ message: e.toString() }, { cause: e }).toObject() + break + default: + next.error = new NamedError.Unknown({ message: JSON.stringify(e) }, { cause: e }).toObject() + } + Bus.publish(Event.Error, { + error: next.error, + }) } + next.time.completed = Date.now() + await updateMessage(next) } function lock(sessionID: string) { @@ -1011,40 +944,25 @@ export namespace Session { } } - function getUsage( - model: ModelsDev.Model, - usage: LanguageModelUsage, - metadata?: ProviderMetadata, - ) { + function getUsage(model: ModelsDev.Model, usage: LanguageModelUsage, metadata?: ProviderMetadata) { const tokens = { - input: usage.promptTokens ?? 0, - output: usage.completionTokens ?? 0, + input: usage.inputTokens ?? 0, + output: usage.outputTokens ?? 0, reasoning: 0, cache: { write: (metadata?.["anthropic"]?.["cacheCreationInputTokens"] ?? // @ts-expect-error metadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ?? 0) as number, - read: (metadata?.["anthropic"]?.["cacheReadInputTokens"] ?? - // @ts-expect-error - metadata?.["bedrock"]?.["usage"]?.["cacheReadInputTokens"] ?? - 0) as number, + read: usage.cachedInputTokens ?? 0, }, } return { cost: new Decimal(0) .add(new Decimal(tokens.input).mul(model.cost.input).div(1_000_000)) .add(new Decimal(tokens.output).mul(model.cost.output).div(1_000_000)) - .add( - new Decimal(tokens.cache.read) - .mul(model.cost.cache_read ?? 0) - .div(1_000_000), - ) - .add( - new Decimal(tokens.cache.write) - .mul(model.cost.cache_write ?? 0) - .div(1_000_000), - ) + .add(new Decimal(tokens.cache.read).mul(model.cost.cache_read ?? 0).div(1_000_000)) + .add(new Decimal(tokens.cache.write).mul(model.cost.cache_write ?? 0).div(1_000_000)) .toNumber(), tokens, } @@ -1056,11 +974,7 @@ export namespace Session { } } - export async function initialize(input: { - sessionID: string - modelID: string - providerID: string - }) { + export async function initialize(input: { sessionID: string; modelID: string; providerID: string }) { const app = App.info() await Session.chat({ sessionID: input.sessionID, @@ -1076,63 +990,3 @@ export namespace Session { await App.initialize() } } - -function toUIMessage(msg: Message.Info): UIMessage { - if (msg.role === "assistant") { - return { - id: msg.id, - role: "assistant", - content: "", - ...toParts(msg.parts), - } - } - - if (msg.role === "user") { - return { - id: msg.id, - role: "user", - content: "", - ...toParts(msg.parts), - } - } - - throw new Error("not implemented") -} - -function toParts(parts: Message.MessagePart[]) { - const result: { - parts: UIMessage["parts"] - experimental_attachments: Attachment[] - } = { - parts: [], - experimental_attachments: [], - } - for (const part of parts) { - switch (part.type) { - case "text": - result.parts.push({ type: "text", text: part.text }) - break - case "file": - result.experimental_attachments.push({ - url: part.url, - contentType: part.mediaType, - name: part.filename, - }) - break - case "tool-invocation": - result.parts.push({ - type: "tool-invocation", - toolInvocation: part.toolInvocation, - }) - break - case "step-start": - result.parts.push({ - type: "step-start", - }) - break - default: - break - } - } - return result -} diff --git a/packages/opencode/src/session/message-v2.ts b/packages/opencode/src/session/message-v2.ts new file mode 100644 index 00000000..8b09e68e --- /dev/null +++ b/packages/opencode/src/session/message-v2.ts @@ -0,0 +1,404 @@ +import z from "zod" +import { Bus } from "../bus" +import { Provider } from "../provider/provider" +import { NamedError } from "../util/error" +import { Message } from "./message" +import { convertToModelMessages, type ModelMessage, type UIMessage } from "ai" + +export namespace MessageV2 { + export const OutputLengthError = NamedError.create("MessageOutputLengthError", z.object({})) + export const AbortedError = NamedError.create("MessageAbortedError", z.object({})) + + export const ToolStatePending = z + .object({ + status: z.literal("pending"), + }) + .openapi({ + ref: "ToolStatePending", + }) + + export type ToolStatePending = z.infer + + export const ToolStateRunning = z + .object({ + status: z.literal("running"), + input: z.any(), + title: z.string().optional(), + metadata: z.record(z.any()).optional(), + time: z.object({ + start: z.number(), + }), + }) + .openapi({ + ref: "ToolStateRunning", + }) + export type ToolStateRunning = z.infer + + export const ToolStateCompleted = z + .object({ + status: z.literal("completed"), + input: z.record(z.any()), + output: z.string(), + title: z.string(), + metadata: z.record(z.any()), + time: z.object({ + start: z.number(), + end: z.number(), + }), + }) + .openapi({ + ref: "ToolStateCompleted", + }) + export type ToolStateCompleted = z.infer + + export const ToolStateError = z + .object({ + status: z.literal("error"), + input: z.record(z.any()), + error: z.string(), + time: z.object({ + start: z.number(), + end: z.number(), + }), + }) + .openapi({ + ref: "ToolStateError", + }) + export type ToolStateError = z.infer + + export const ToolState = z + .discriminatedUnion("status", [ToolStatePending, ToolStateRunning, ToolStateCompleted, ToolStateError]) + .openapi({ + ref: "ToolState", + }) + + export const TextPart = z + .object({ + type: z.literal("text"), + text: z.string(), + }) + .openapi({ + ref: "TextPart", + }) + export type TextPart = z.infer + + export const ToolPart = z + .object({ + type: z.literal("tool"), + id: z.string(), + tool: z.string(), + state: ToolState, + }) + .openapi({ + ref: "ToolPart", + }) + export type ToolPart = z.infer + + export const FilePart = z + .object({ + type: z.literal("file"), + mime: z.string(), + filename: z.string().optional(), + url: z.string(), + }) + .openapi({ + ref: "FilePart", + }) + export type FilePart = z.infer + + export const StepStartPart = z + .object({ + type: z.literal("step-start"), + }) + .openapi({ + ref: "StepStartPart", + }) + export type StepStartPart = z.infer + + const Base = z.object({ + id: z.string(), + sessionID: z.string(), + }) + + export const UserPart = z.discriminatedUnion("type", [TextPart, FilePart]).openapi({ + ref: "UserMessagePart", + }) + export type UserPart = z.infer + + export const User = Base.extend({ + role: z.literal("user"), + parts: z.array(UserPart), + time: z.object({ + created: z.number(), + }), + }).openapi({ + ref: "UserMessage", + }) + export type User = z.infer + + export const AssistantPart = z.discriminatedUnion("type", [TextPart, ToolPart, StepStartPart]).openapi({ + ref: "AssistantMessagePart", + }) + export type AssistantPart = z.infer + + export const Assistant = Base.extend({ + role: z.literal("assistant"), + parts: z.array(AssistantPart), + time: z.object({ + created: z.number(), + completed: z.number().optional(), + }), + error: z + .discriminatedUnion("name", [ + Provider.AuthError.Schema, + NamedError.Unknown.Schema, + OutputLengthError.Schema, + AbortedError.Schema, + ]) + .optional(), + system: z.string().array(), + modelID: z.string(), + providerID: z.string(), + path: z.object({ + cwd: z.string(), + root: z.string(), + }), + cost: z.number(), + summary: z.boolean().optional(), + tokens: z.object({ + input: z.number(), + output: z.number(), + reasoning: z.number(), + cache: z.object({ + read: z.number(), + write: z.number(), + }), + }), + }).openapi({ + ref: "AssistantMessage", + }) + export type Assistant = z.infer + + export const Info = z.discriminatedUnion("role", [User, Assistant]).openapi({ + ref: "Message", + }) + export type Info = z.infer + + export const Event = { + Updated: Bus.event( + "message.updated", + z.object({ + info: Info, + }), + ), + Removed: Bus.event( + "message.removed", + z.object({ + sessionID: z.string(), + messageID: z.string(), + }), + ), + PartUpdated: Bus.event( + "message.part.updated", + z.object({ + part: AssistantPart, + sessionID: z.string(), + messageID: z.string(), + }), + ), + } + + export function fromV1(v1: Message.Info) { + if (v1.role === "assistant") { + const result: Assistant = { + id: v1.id, + sessionID: v1.metadata.sessionID, + role: "assistant", + time: { + created: v1.metadata.time.created, + completed: v1.metadata.time.completed, + }, + cost: v1.metadata.assistant!.cost, + path: v1.metadata.assistant!.path, + summary: v1.metadata.assistant!.summary, + tokens: v1.metadata.assistant!.tokens, + modelID: v1.metadata.assistant!.modelID, + providerID: v1.metadata.assistant!.providerID, + system: v1.metadata.assistant!.system, + error: v1.metadata.error, + parts: v1.parts.flatMap((part): AssistantPart[] => { + if (part.type === "text") { + return [ + { + type: "text", + text: part.text, + }, + ] + } + if (part.type === "step-start") { + return [ + { + type: "step-start", + }, + ] + } + if (part.type === "tool-invocation") { + return [ + { + type: "tool", + id: part.toolInvocation.toolCallId, + tool: part.toolInvocation.toolName, + state: (() => { + if (part.toolInvocation.state === "partial-call") { + return { + status: "pending", + } + } + + const { title, time, ...metadata } = v1.metadata.tool[part.toolInvocation.toolCallId] ?? {} + if (part.toolInvocation.state === "call") { + return { + status: "running", + input: part.toolInvocation.args, + time: { + start: time?.start, + }, + } + } + + if (part.toolInvocation.state === "result") { + return { + status: "completed", + input: part.toolInvocation.args, + output: part.toolInvocation.result, + title, + time, + metadata, + } + } + throw new Error("unknown tool invocation state") + })(), + }, + ] + } + return [] + }), + } + return result + } + + if (v1.role === "user") { + const result: User = { + id: v1.id, + sessionID: v1.metadata.sessionID, + role: "user", + time: { + created: v1.metadata.time.created, + }, + parts: v1.parts.flatMap((part): UserPart[] => { + if (part.type === "text") { + return [ + { + type: "text", + text: part.text, + }, + ] + } + if (part.type === "file") { + return [ + { + type: "file", + mime: part.mediaType, + filename: part.filename, + url: part.url, + }, + ] + } + return [] + }), + } + return result + } + } + + export function toModelMessage(input: Info[]): ModelMessage[] { + const result: UIMessage[] = [] + + for (const msg of input) { + if (msg.parts.length === 0) continue + if (msg.role === "user") { + result.push({ + id: msg.id, + role: "user", + parts: msg.parts.flatMap((part): UIMessage["parts"] => { + if (part.type === "text") + return [ + { + type: "text", + text: part.text, + }, + ] + if (part.type === "file") + return [ + { + type: "file", + url: part.url, + mediaType: part.mime, + filename: part.filename, + }, + ] + return [] + }), + }) + } + + if (msg.role === "assistant") { + result.push({ + id: msg.id, + role: "assistant", + parts: msg.parts.flatMap((part): UIMessage["parts"] => { + if (part.type === "text") + return [ + { + type: "text", + text: part.text, + }, + ] + if (part.type === "step-start") + return [ + { + type: "step-start", + }, + ] + if (part.type === "tool") { + if (part.state.status === "completed") + return [ + { + type: ("tool-" + part.tool) as `tool-${string}`, + state: "output-available", + toolCallId: part.id, + input: part.state.input, + output: part.state.output, + }, + ] + if (part.state.status === "error") + return [ + { + type: ("tool-" + part.tool) as `tool-${string}`, + state: "output-error", + toolCallId: part.id, + input: part.state.input, + errorText: part.state.error, + }, + ] + } + + return [] + }), + }) + } + } + + return convertToModelMessages(result) + } +} diff --git a/packages/opencode/src/session/message.ts b/packages/opencode/src/session/message.ts index 2d319e87..34b522fc 100644 --- a/packages/opencode/src/session/message.ts +++ b/packages/opencode/src/session/message.ts @@ -1,13 +1,9 @@ import z from "zod" -import { Bus } from "../bus" import { Provider } from "../provider/provider" import { NamedError } from "../util/error" export namespace Message { - export const OutputLengthError = NamedError.create( - "MessageOutputLengthError", - z.object({}), - ) + export const OutputLengthError = NamedError.create("MessageOutputLengthError", z.object({})) export const ToolCall = z .object({ @@ -49,11 +45,9 @@ export namespace Message { }) export type ToolResult = z.infer - export const ToolInvocation = z - .discriminatedUnion("state", [ToolCall, ToolPartialCall, ToolResult]) - .openapi({ - ref: "ToolInvocation", - }) + export const ToolInvocation = z.discriminatedUnion("state", [ToolCall, ToolPartialCall, ToolResult]).openapi({ + ref: "ToolInvocation", + }) export type ToolInvocation = z.infer export const TextPart = z @@ -122,14 +116,7 @@ export namespace Message { export type StepStartPart = z.infer export const MessagePart = z - .discriminatedUnion("type", [ - TextPart, - ReasoningPart, - ToolInvocationPart, - SourceUrlPart, - FilePart, - StepStartPart, - ]) + .discriminatedUnion("type", [TextPart, ReasoningPart, ToolInvocationPart, SourceUrlPart, FilePart, StepStartPart]) .openapi({ ref: "MessagePart", }) @@ -197,28 +184,4 @@ export namespace Message { ref: "Message", }) export type Info = z.infer - - export const Event = { - Updated: Bus.event( - "message.updated", - z.object({ - info: Info, - }), - ), - Removed: Bus.event( - "message.removed", - z.object({ - sessionID: z.string(), - messageID: z.string(), - }), - ), - PartUpdated: Bus.event( - "message.part.updated", - z.object({ - part: MessagePart, - sessionID: z.string(), - messageID: z.string(), - }), - ), - } } diff --git a/packages/opencode/src/session/prompt/beast.txt b/packages/opencode/src/session/prompt/beast.txt new file mode 100644 index 00000000..52b5558c --- /dev/null +++ b/packages/opencode/src/session/prompt/beast.txt @@ -0,0 +1,95 @@ +You are an agent known as opencode - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. + +Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough. + +You MUST iterate and keep going until the problem is solved. + +I want you to fully solve this autonomously before coming back to me. + +Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn. + +Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why. + +If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is. + +Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided. + +You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. + +# Workflow + +1. Understand the problem deeply. Carefully read the issue and think critically about what is required. +2. Investigate the codebase. Explore relevant files, search for key functions, and gather context. +3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly. +4. Implement the fix incrementally. Make small, testable code changes. +5. Debug as needed. Use debugging techniques to isolate and resolve issues. +6. Test frequently. Run tests after each change to verify correctness. +7. Iterate until the root cause is fixed and all tests pass. +8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete. + +Refer to the detailed sections below for more information on each step. + +## 1. Deeply Understand the Problem +Carefully read the issue and think hard about a plan to solve it before coding. + +## 2. Codebase Investigation +- Explore relevant files and directories. +- Search for key functions, classes, or variables related to the issue. +- Read and understand relevant code snippets. +- Identify the root cause of the problem. +- Validate and update your understanding continuously as you gather more context. + +## 3. Fetch Provided URLs +- If the user provides a URL, use the `functions.fetch_webpage` tool to retrieve the content of the provided URL. +- After fetching, review the content returned by the fetch tool. +- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links. +- Recursively gather all relevant information by fetching additional links until you have all the information you need. + +## 4. Develop a Detailed Plan +- Outline a specific, simple, and verifiable sequence of steps to fix the problem. +- Create a todo list in markdown format to track your progress. +- Each time you complete a step, check it off using `[x]` syntax. +- Each time you check off a step, display the updated todo list to the user. +- Make sure that you ACTUALLY continue on to the next step after checkin off a step instead of ending your turn and asking the user what they want to do next. + +## 5. Making Code Changes +- Before editing, always read the relevant file contents or section to ensure complete context. +- Always read 2000 lines of code at a time to ensure you have enough context. +- If a patch is not applied correctly, attempt to reapply it. +- Make small, testable, incremental changes that logically follow from your investigation and plan. + +## 6. Debugging +- Make code changes only if you have high confidence they can solve the problem +- When debugging, try to determine the root cause rather than addressing symptoms +- Debug for as long as needed to identify the root cause and identify a fix +- Use the #problems tool to check for any problems in the code +- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening +- To test hypotheses, you can also add test statements or functions +- Revisit your assumptions if unexpected behavior occurs. + +# Fetch Webpage +Use the `webfetch` tool when the user provides a URL. Follow these steps exactly. + +1. Use the `webfetch` tool to retrieve the content of the provided URL. +2. After fetching, review the content returned by the fetch tool. +3. If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links. +4. Go back to step 2 and repeat until you have all the information you need. + +IMPORTANT: Recursively fetching links is crucial. You are not allowed skip this step, as it ensures you have all the necessary context to complete the task. + +# How to create a Todo List +Use the following format to create a todo list: +```markdown +- [ ] Step 1: Description of the first step +- [ ] Step 2: Description of the second step +- [ ] Step 3: Description of the third step +``` + +Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above. + +# Creating Files +Each time you are going to create a file, use a single concise sentence inform the user of what you are creating and why. + +# Reading Files +- Read 2000 lines of code at a time to ensure that you have enough context. +- Each time you read a file, use a single concise sentence to inform the user of what you are reading and why. diff --git a/packages/opencode/src/session/system.ts b/packages/opencode/src/session/system.ts index 722964ea..4dc22765 100644 --- a/packages/opencode/src/session/system.ts +++ b/packages/opencode/src/session/system.ts @@ -7,23 +7,16 @@ import path from "path" import os from "os" import PROMPT_ANTHROPIC from "./prompt/anthropic.txt" +import PROMPT_BEAST from "./prompt/beast.txt" import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt" import PROMPT_SUMMARIZE from "./prompt/summarize.txt" import PROMPT_TITLE from "./prompt/title.txt" export namespace SystemPrompt { - export function provider(providerID: string) { - const result = [] - switch (providerID) { - case "anthropic": - result.push(PROMPT_ANTHROPIC_SPOOF.trim()) - result.push(PROMPT_ANTHROPIC) - break - default: - result.push(PROMPT_ANTHROPIC) - break - } - return result + export function provider(providerID: string, modelID: string) { + if (providerID === "anthropic") return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_ANTHROPIC] + if (modelID.includes("gpt-")) return [PROMPT_BEAST] + return [PROMPT_ANTHROPIC] } export async function environment() { diff --git a/packages/opencode/src/share/share.ts b/packages/opencode/src/share/share.ts index a5080969..2996e4d9 100644 --- a/packages/opencode/src/share/share.ts +++ b/packages/opencode/src/share/share.ts @@ -53,9 +53,7 @@ export namespace Share { export const URL = process.env["OPENCODE_API"] ?? - (Installation.isSnapshot() || Installation.isDev() - ? "https://api.dev.opencode.ai" - : "https://api.opencode.ai") + (Installation.isSnapshot() || Installation.isDev() ? "https://api.dev.opencode.ai" : "https://api.opencode.ai") export async function create(sessionID: string) { return fetch(`${URL}/share_create`, { diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index 1bbb870f..608eb89c 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -55,9 +55,7 @@ export namespace Snapshot { log.info("restore", { commit }) const app = App.info() const git = gitdir(sessionID) - await $`git --git-dir=${git} checkout ${commit} --force` - .quiet() - .cwd(app.path.root) + await $`git --git-dir=${git} checkout ${commit} --force`.quiet().cwd(app.path.root) } function gitdir(sessionID: string) { diff --git a/packages/opencode/src/storage/storage.ts b/packages/opencode/src/storage/storage.ts index eee33a09..001eee0a 100644 --- a/packages/opencode/src/storage/storage.ts +++ b/packages/opencode/src/storage/storage.ts @@ -4,44 +4,80 @@ import { Bus } from "../bus" import path from "path" import z from "zod" import fs from "fs/promises" +import { MessageV2 } from "../session/message-v2" export namespace Storage { const log = Log.create({ service: "storage" }) export const Event = { - Write: Bus.event( - "storage.write", - z.object({ key: z.string(), content: z.any() }), - ), + Write: Bus.event("storage.write", z.object({ key: z.string(), content: z.any() })), } - const state = App.state("storage", () => { + type Migration = (dir: string) => Promise + + const MIGRATIONS: Migration[] = [ + async (dir: string) => { + try { + const files = new Bun.Glob("session/message/*/*.json").scanSync({ + cwd: dir, + absolute: true, + }) + for (const file of files) { + const content = await Bun.file(file).json() + if (!content.metadata) continue + log.info("migrating to v2 message", { file }) + try { + const result = MessageV2.fromV1(content) + await Bun.write(file, JSON.stringify(result, null, 2)) + } catch (e) { + await fs.rename(file, file.replace("storage", "broken")) + } + } + } catch {} + }, + ] + + const state = App.state("storage", async () => { const app = App.info() - const dir = path.join(app.path.data, "storage") - log.info("init", { path: dir }) + const dir = path.normalize(path.join(app.path.data, "storage")) + await fs.mkdir(dir, { recursive: true }) + const migration = await Bun.file(path.join(dir, "migration")) + .json() + .then((x) => parseInt(x)) + .catch(() => 0) + for (let index = migration; index < MIGRATIONS.length; index++) { + log.info("running migration", { index }) + const migration = MIGRATIONS[index] + await migration(dir) + await Bun.write(path.join(dir, "migration"), (index + 1).toString()) + } return { dir, } }) export async function remove(key: string) { - const target = path.join(state().dir, key + ".json") + const dir = await state().then((x) => x.dir) + const target = path.join(dir, key + ".json") await fs.unlink(target).catch(() => {}) } export async function removeDir(key: string) { - const target = path.join(state().dir, key) + const dir = await state().then((x) => x.dir) + const target = path.join(dir, key) await fs.rm(target, { recursive: true, force: true }).catch(() => {}) } export async function readJSON(key: string) { - return Bun.file(path.join(state().dir, key + ".json")).json() as Promise + const dir = await state().then((x) => x.dir) + return Bun.file(path.join(dir, key + ".json")).json() as Promise } export async function writeJSON(key: string, content: T) { - const target = path.join(state().dir, key + ".json") + const dir = await state().then((x) => x.dir) + const target = path.join(dir, key + ".json") const tmp = target + Date.now() + ".tmp" - await Bun.write(tmp, JSON.stringify(content)) + await Bun.write(tmp, JSON.stringify(content, null, 2)) await fs.rename(tmp, target).catch(() => {}) await fs.unlink(tmp).catch(() => {}) Bus.publish(Event.Write, { key, content }) @@ -49,9 +85,10 @@ export namespace Storage { const glob = new Bun.Glob("**/*") export async function* list(prefix: string) { + const dir = await state().then((x) => x.dir) try { for await (const item of glob.scan({ - cwd: path.join(state().dir, prefix), + cwd: path.join(dir, prefix), onlyFiles: true, })) { const result = path.join(prefix, item.slice(0, -5)) diff --git a/packages/opencode/src/tool/bash.ts b/packages/opencode/src/tool/bash.ts index 620a8c8d..050a5a97 100644 --- a/packages/opencode/src/tool/bash.ts +++ b/packages/opencode/src/tool/bash.ts @@ -12,12 +12,7 @@ export const BashTool = Tool.define({ description: DESCRIPTION, parameters: z.object({ command: z.string().describe("The command to execute"), - timeout: z - .number() - .min(0) - .max(MAX_TIMEOUT) - .describe("Optional timeout in milliseconds") - .optional(), + timeout: z.number().min(0).max(MAX_TIMEOUT).describe("Optional timeout in milliseconds").optional(), description: z .string() .describe( @@ -41,21 +36,14 @@ export const BashTool = Tool.define({ const stderr = await new Response(process.stderr).text() return { + title: params.command, metadata: { stderr, stdout, exit: process.exitCode, description: params.description, - title: params.command, }, - output: [ - ``, - stdout ?? "", - ``, - ``, - stderr ?? "", - ``, - ].join("\n"), + output: [``, stdout ?? "", ``, ``, stderr ?? "", ``].join("\n"), } }, }) diff --git a/packages/opencode/src/tool/edit.ts b/packages/opencode/src/tool/edit.ts index 8c9043e6..7e8d733d 100644 --- a/packages/opencode/src/tool/edit.ts +++ b/packages/opencode/src/tool/edit.ts @@ -20,15 +20,8 @@ export const EditTool = Tool.define({ parameters: z.object({ filePath: z.string().describe("The absolute path to the file to modify"), oldString: z.string().describe("The text to replace"), - newString: z - .string() - .describe( - "The text to replace it with (must be different from old_string)", - ), - replaceAll: z - .boolean() - .optional() - .describe("Replace all occurrences of old_string (default false)"), + newString: z.string().describe("The text to replace it with (must be different from old_string)"), + replaceAll: z.boolean().optional().describe("Replace all occurrences of old_string (default false)"), }), async execute(params, ctx) { if (!params.filePath) { @@ -40,9 +33,7 @@ export const EditTool = Tool.define({ } const app = App.info() - const filepath = path.isAbsolute(params.filePath) - ? params.filePath - : path.join(app.path.cwd, params.filePath) + const filepath = path.isAbsolute(params.filePath) ? params.filePath : path.join(app.path.cwd, params.filePath) await Permission.ask({ id: "edit", @@ -70,17 +61,11 @@ export const EditTool = Tool.define({ const file = Bun.file(filepath) const stats = await file.stat().catch(() => {}) if (!stats) throw new Error(`File ${filepath} not found`) - if (stats.isDirectory()) - throw new Error(`Path is a directory, not a file: ${filepath}`) + if (stats.isDirectory()) throw new Error(`Path is a directory, not a file: ${filepath}`) await FileTime.assert(ctx.sessionID, filepath) contentOld = await file.text() - contentNew = replace( - contentOld, - params.oldString, - params.newString, - params.replaceAll, - ) + contentNew = replace(contentOld, params.oldString, params.newString, params.replaceAll) await file.write(contentNew) await Bus.publish(File.Event.Edited, { file: filepath, @@ -88,9 +73,7 @@ export const EditTool = Tool.define({ contentNew = await file.text() })() - const diff = trimDiff( - createTwoFilesPatch(filepath, filepath, contentOld, contentNew), - ) + const diff = trimDiff(createTwoFilesPatch(filepath, filepath, contentOld, contentNew)) FileTime.read(ctx.sessionID, filepath) @@ -110,17 +93,14 @@ export const EditTool = Tool.define({ metadata: { diagnostics, diff, - title: `${path.relative(app.path.root, filepath)}`, }, + title: `${path.relative(app.path.root, filepath)}`, output, } }, }) -export type Replacer = ( - content: string, - find: string, -) => Generator +export type Replacer = (content: string, find: string) => Generator export const SimpleReplacer: Replacer = function* (_content, find) { yield find @@ -208,10 +188,7 @@ export const BlockAnchorReplacer: Replacer = function* (content, find) { } } -export const WhitespaceNormalizedReplacer: Replacer = function* ( - content, - find, -) { +export const WhitespaceNormalizedReplacer: Replacer = function* (content, find) { const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim() const normalizedFind = normalizeWhitespace(find) @@ -229,9 +206,7 @@ export const WhitespaceNormalizedReplacer: Replacer = function* ( // Find the actual substring in the original line that matches const words = find.trim().split(/\s+/) if (words.length > 0) { - const pattern = words - .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) - .join("\\s+") + const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+") try { const regex = new RegExp(pattern) const match = line.match(regex) @@ -270,9 +245,7 @@ export const IndentationFlexibleReplacer: Replacer = function* (content, find) { }), ) - return lines - .map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))) - .join("\n") + return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n") } const normalizedFind = removeIndentation(find) @@ -423,10 +396,7 @@ export const ContextAwareReplacer: Replacer = function* (content, find) { } } - if ( - totalNonEmptyLines === 0 || - matchingLines / totalNonEmptyLines >= 0.5 - ) { + if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) { yield block break // Only match the first occurrence } @@ -473,12 +443,7 @@ function trimDiff(diff: string): string { return trimmedLines.join("\n") } -export function replace( - content: string, - oldString: string, - newString: string, - replaceAll = false, -): string { +export function replace(content: string, oldString: string, newString: string, replaceAll = false): string { if (oldString === newString) { throw new Error("oldString and newString must be different") } @@ -502,11 +467,7 @@ export function replace( } const lastIndex = content.lastIndexOf(search) if (index !== lastIndex) continue - return ( - content.substring(0, index) + - newString + - content.substring(index + search.length) - ) + return content.substring(0, index) + newString + content.substring(index + search.length) } } throw new Error("oldString not found in content or was found multiple times") diff --git a/packages/opencode/src/tool/glob.ts b/packages/opencode/src/tool/glob.ts index 70d5df47..6496099e 100644 --- a/packages/opencode/src/tool/glob.ts +++ b/packages/opencode/src/tool/glob.ts @@ -20,16 +20,14 @@ export const GlobTool = Tool.define({ async execute(params) { const app = App.info() let search = params.path ?? app.path.cwd - search = path.isAbsolute(search) - ? search - : path.resolve(app.path.cwd, search) + search = path.isAbsolute(search) ? search : path.resolve(app.path.cwd, search) const limit = 100 const files = [] let truncated = false for (const file of await Ripgrep.files({ cwd: search, - glob: params.pattern, + glob: [params.pattern], })) { if (files.length >= limit) { truncated = true @@ -53,17 +51,15 @@ export const GlobTool = Tool.define({ output.push(...files.map((f) => f.path)) if (truncated) { output.push("") - output.push( - "(Results are truncated. Consider using a more specific path or pattern.)", - ) + output.push("(Results are truncated. Consider using a more specific path or pattern.)") } } return { + title: path.relative(app.path.root, search), metadata: { count: files.length, truncated, - title: path.relative(app.path.root, search), }, output: output.join("\n"), } diff --git a/packages/opencode/src/tool/grep.ts b/packages/opencode/src/tool/grep.ts index e4ceec5e..cd28fb48 100644 --- a/packages/opencode/src/tool/grep.ts +++ b/packages/opencode/src/tool/grep.ts @@ -9,21 +9,9 @@ export const GrepTool = Tool.define({ id: "grep", description: DESCRIPTION, parameters: z.object({ - pattern: z - .string() - .describe("The regex pattern to search for in file contents"), - path: z - .string() - .optional() - .describe( - "The directory to search in. Defaults to the current working directory.", - ), - include: z - .string() - .optional() - .describe( - 'File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")', - ), + pattern: z.string().describe("The regex pattern to search for in file contents"), + path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."), + include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'), }), async execute(params) { if (!params.pattern) { @@ -51,7 +39,8 @@ export const GrepTool = Tool.define({ if (exitCode === 1) { return { - metadata: { matches: 0, truncated: false, title: params.pattern }, + title: params.pattern, + metadata: { matches: 0, truncated: false }, output: "No files found", } } @@ -93,7 +82,8 @@ export const GrepTool = Tool.define({ if (finalMatches.length === 0) { return { - metadata: { matches: 0, truncated: false, title: params.pattern }, + title: params.pattern, + metadata: { matches: 0, truncated: false }, output: "No files found", } } @@ -114,16 +104,14 @@ export const GrepTool = Tool.define({ if (truncated) { outputLines.push("") - outputLines.push( - "(Results are truncated. Consider using a more specific path or pattern.)", - ) + outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)") } return { + title: params.pattern, metadata: { matches: finalMatches.length, truncated, - title: params.pattern, }, output: outputLines.join("\n"), } diff --git a/packages/opencode/src/tool/ls.ts b/packages/opencode/src/tool/ls.ts index bfceba85..a2c585a0 100644 --- a/packages/opencode/src/tool/ls.ts +++ b/packages/opencode/src/tool/ls.ts @@ -16,6 +16,8 @@ export const IGNORE_PATTERNS = [ "obj/", ".idea/", ".vscode/", + ".zig-cache/", + "zig-out", ] const LIMIT = 100 @@ -24,16 +26,8 @@ export const ListTool = Tool.define({ id: "list", description: DESCRIPTION, parameters: z.object({ - path: z - .string() - .describe( - "The absolute path to the directory to list (must be absolute, not relative)", - ) - .optional(), - ignore: z - .array(z.string()) - .describe("List of glob patterns to ignore") - .optional(), + path: z.string().describe("The absolute path to the directory to list (must be absolute, not relative)").optional(), + ignore: z.array(z.string()).describe("List of glob patterns to ignore").optional(), }), async execute(params) { const app = App.info() @@ -44,8 +38,7 @@ export const ListTool = Tool.define({ for await (const file of glob.scan({ cwd: searchPath, dot: true })) { if (IGNORE_PATTERNS.some((p) => file.includes(p))) continue - if (params.ignore?.some((pattern) => new Bun.Glob(pattern).match(file))) - continue + if (params.ignore?.some((pattern) => new Bun.Glob(pattern).match(file))) continue files.push(file) if (files.length >= LIMIT) break } @@ -99,10 +92,10 @@ export const ListTool = Tool.define({ const output = `${searchPath}/\n` + renderDir(".", 0) return { + title: path.relative(app.path.root, searchPath), metadata: { count: files.length, truncated: files.length >= LIMIT, - title: path.relative(app.path.root, searchPath), }, output, } diff --git a/packages/opencode/src/tool/lsp-diagnostics.ts b/packages/opencode/src/tool/lsp-diagnostics.ts index 97ae7a26..fc9699bf 100644 --- a/packages/opencode/src/tool/lsp-diagnostics.ts +++ b/packages/opencode/src/tool/lsp-diagnostics.ts @@ -13,20 +13,16 @@ export const LspDiagnosticTool = Tool.define({ }), execute: async (args) => { const app = App.info() - const normalized = path.isAbsolute(args.path) - ? args.path - : path.join(app.path.cwd, args.path) + const normalized = path.isAbsolute(args.path) ? args.path : path.join(app.path.cwd, args.path) await LSP.touchFile(normalized, true) const diagnostics = await LSP.diagnostics() const file = diagnostics[normalized] return { + title: path.relative(app.path.root, normalized), metadata: { diagnostics, - title: path.relative(app.path.root, normalized), }, - output: file?.length - ? file.map(LSP.Diagnostic.pretty).join("\n") - : "No errors found", + output: file?.length ? file.map(LSP.Diagnostic.pretty).join("\n") : "No errors found", } }, }) diff --git a/packages/opencode/src/tool/lsp-hover.ts b/packages/opencode/src/tool/lsp-hover.ts index f5031f85..bb94ddb3 100644 --- a/packages/opencode/src/tool/lsp-hover.ts +++ b/packages/opencode/src/tool/lsp-hover.ts @@ -15,9 +15,7 @@ export const LspHoverTool = Tool.define({ }), execute: async (args) => { const app = App.info() - const file = path.isAbsolute(args.file) - ? args.file - : path.join(app.path.cwd, args.file) + const file = path.isAbsolute(args.file) ? args.file : path.join(app.path.cwd, args.file) await LSP.touchFile(file, true) const result = await LSP.hover({ ...args, @@ -25,14 +23,9 @@ export const LspHoverTool = Tool.define({ }) return { + title: path.relative(app.path.root, file) + ":" + args.line + ":" + args.character, metadata: { result, - title: - path.relative(app.path.root, file) + - ":" + - args.line + - ":" + - args.character, }, output: JSON.stringify(result, null, 2), } diff --git a/packages/opencode/src/tool/multiedit.ts b/packages/opencode/src/tool/multiedit.ts index f8d0f16c..041893b9 100644 --- a/packages/opencode/src/tool/multiedit.ts +++ b/packages/opencode/src/tool/multiedit.ts @@ -10,9 +10,7 @@ export const MultiEditTool = Tool.define({ description: DESCRIPTION, parameters: z.object({ filePath: z.string().describe("The absolute path to the file to modify"), - edits: z - .array(EditTool.parameters) - .describe("Array of edit operations to perform sequentially on the file"), + edits: z.array(EditTool.parameters).describe("Array of edit operations to perform sequentially on the file"), }), async execute(params, ctx) { const results = [] @@ -30,9 +28,9 @@ export const MultiEditTool = Tool.define({ } const app = App.info() return { + title: path.relative(app.path.root, params.filePath), metadata: { results: results.map((r) => r.metadata), - title: path.relative(app.path.root, params.filePath), }, output: results.at(-1)!.output, } diff --git a/packages/opencode/src/tool/patch.ts b/packages/opencode/src/tool/patch.ts index 6266d163..11cc56c9 100644 --- a/packages/opencode/src/tool/patch.ts +++ b/packages/opencode/src/tool/patch.ts @@ -6,9 +6,7 @@ import { FileTime } from "../file/time" import DESCRIPTION from "./patch.txt" const PatchParams = z.object({ - patchText: z - .string() - .describe("The full patch text that describes all changes to be made"), + patchText: z.string().describe("The full patch text that describes all changes to be made"), }) interface Change { @@ -42,10 +40,7 @@ function identifyFilesNeeded(patchText: string): string[] { const files: string[] = [] const lines = patchText.split("\n") for (const line of lines) { - if ( - line.startsWith("*** Update File:") || - line.startsWith("*** Delete File:") - ) { + if (line.startsWith("*** Update File:") || line.startsWith("*** Delete File:")) { const filePath = line.split(":", 2)[1]?.trim() if (filePath) files.push(filePath) } @@ -65,10 +60,7 @@ function identifyFilesAdded(patchText: string): string[] { return files } -function textToPatch( - patchText: string, - _currentFiles: Record, -): [PatchOperation[], number] { +function textToPatch(patchText: string, _currentFiles: Record): [PatchOperation[], number] { const operations: PatchOperation[] = [] const lines = patchText.split("\n") let i = 0 @@ -93,11 +85,7 @@ function textToPatch( const changes: PatchChange[] = [] i++ - while ( - i < lines.length && - !lines[i].startsWith("@@") && - !lines[i].startsWith("***") - ) { + while (i < lines.length && !lines[i].startsWith("@@") && !lines[i].startsWith("***")) { const changeLine = lines[i] if (changeLine.startsWith(" ")) { changes.push({ type: "keep", content: changeLine.substring(1) }) @@ -151,10 +139,7 @@ function textToPatch( return [operations, fuzz] } -function patchToCommit( - operations: PatchOperation[], - currentFiles: Record, -): Commit { +function patchToCommit(operations: PatchOperation[], currentFiles: Record): Commit { const changes: Record = {} for (const op of operations) { @@ -173,9 +158,7 @@ function patchToCommit( const lines = originalContent.split("\n") for (const hunk of op.hunks) { - const contextIndex = lines.findIndex((line) => - line.includes(hunk.contextLine), - ) + const contextIndex = lines.findIndex((line) => line.includes(hunk.contextLine)) if (contextIndex === -1) { throw new Error(`Context line not found: ${hunk.contextLine}`) } @@ -204,11 +187,7 @@ function patchToCommit( return { changes } } -function generateDiff( - oldContent: string, - newContent: string, - filePath: string, -): [string, number, number] { +function generateDiff(oldContent: string, newContent: string, filePath: string): [string, number, number] { // Mock implementation - would need actual diff generation const lines1 = oldContent.split("\n") const lines2 = newContent.split("\n") @@ -296,9 +275,7 @@ export const PatchTool = Tool.define({ // Process the patch const [patch, fuzz] = textToPatch(params.patchText, currentFiles) if (fuzz > 3) { - throw new Error( - `patch contains fuzzy matches (fuzz level: ${fuzz}). Please make your context lines more precise`, - ) + throw new Error(`patch contains fuzzy matches (fuzz level: ${fuzz}). Please make your context lines more precise`) } // Convert patch to commit @@ -343,11 +320,7 @@ export const PatchTool = Tool.define({ const newContent = change.new_content || "" // Calculate diff statistics - const [, additions, removals] = generateDiff( - oldContent, - newContent, - filePath, - ) + const [, additions, removals] = generateDiff(oldContent, newContent, filePath) totalAdditions += additions totalRemovals += removals @@ -358,11 +331,11 @@ export const PatchTool = Tool.define({ const output = result return { + title: `${filesToRead.length} files`, metadata: { changed: changedFiles, additions: totalAdditions, removals: totalRemovals, - title: `${filesToRead.length} files`, }, output, } diff --git a/packages/opencode/src/tool/read.ts b/packages/opencode/src/tool/read.ts index f524389e..62d67aa1 100644 --- a/packages/opencode/src/tool/read.ts +++ b/packages/opencode/src/tool/read.ts @@ -16,14 +16,8 @@ export const ReadTool = Tool.define({ description: DESCRIPTION, parameters: z.object({ filePath: z.string().describe("The path to the file to read"), - offset: z - .number() - .describe("The line number to start reading from (0-based)") - .optional(), - limit: z - .number() - .describe("The number of lines to read (defaults to 2000)") - .optional(), + offset: z.number().describe("The line number to start reading from (0-based)").optional(), + limit: z.number().describe("The number of lines to read (defaults to 2000)").optional(), }), async execute(params, ctx) { let filePath = params.filePath @@ -40,16 +34,13 @@ export const ReadTool = Tool.define({ const suggestions = dirEntries .filter( (entry) => - entry.toLowerCase().includes(base.toLowerCase()) || - base.toLowerCase().includes(entry.toLowerCase()), + entry.toLowerCase().includes(base.toLowerCase()) || base.toLowerCase().includes(entry.toLowerCase()), ) .map((entry) => path.join(dir, entry)) .slice(0, 3) if (suggestions.length > 0) { - throw new Error( - `File not found: ${filePath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`, - ) + throw new Error(`File not found: ${filePath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`) } throw new Error(`File not found: ${filePath}`) @@ -57,21 +48,14 @@ export const ReadTool = Tool.define({ const stats = await file.stat() if (stats.size > MAX_READ_SIZE) - throw new Error( - `File is too large (${stats.size} bytes). Maximum size is ${MAX_READ_SIZE} bytes`, - ) + throw new Error(`File is too large (${stats.size} bytes). Maximum size is ${MAX_READ_SIZE} bytes`) const limit = params.limit ?? DEFAULT_READ_LIMIT const offset = params.offset || 0 const isImage = isImageFile(filePath) - if (isImage) - throw new Error( - `This is an image file of type: ${isImage}\nUse a different tool to process images`, - ) + if (isImage) throw new Error(`This is an image file of type: ${isImage}\nUse a different tool to process images`) const lines = await file.text().then((text) => text.split("\n")) const raw = lines.slice(offset, offset + limit).map((line) => { - return line.length > MAX_LINE_LENGTH - ? line.substring(0, MAX_LINE_LENGTH) + "..." - : line + return line.length > MAX_LINE_LENGTH ? line.substring(0, MAX_LINE_LENGTH) + "..." : line }) const content = raw.map((line, index) => { return `${(index + offset + 1).toString().padStart(5, "0")}| ${line}` @@ -82,9 +66,7 @@ export const ReadTool = Tool.define({ output += content.join("\n") if (lines.length > offset + content.length) { - output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${ - offset + content.length - })` + output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${offset + content.length})` } output += "\n" @@ -93,10 +75,10 @@ export const ReadTool = Tool.define({ FileTime.read(ctx.sessionID, filePath) return { + title: path.relative(App.info().path.root, filePath), output, metadata: { preview, - title: path.relative(App.info().path.root, filePath), }, } }, diff --git a/packages/opencode/src/tool/read.txt b/packages/opencode/src/tool/read.txt index d1bf8c5d..be9e9e0c 100644 --- a/packages/opencode/src/tool/read.txt +++ b/packages/opencode/src/tool/read.txt @@ -2,7 +2,7 @@ Reads a file from the local filesystem. You can access any file directly by usin Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned. Usage: -- The file_path parameter must be an absolute path, not a relative path +- The filePath parameter must be an absolute path, not a relative path - By default, it reads up to 2000 lines starting from the beginning of the file - You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters - Any lines longer than 2000 characters will be truncated diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index 2796d0fe..75739833 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -3,41 +3,36 @@ import DESCRIPTION from "./task.txt" import { z } from "zod" import { Session } from "../session" import { Bus } from "../bus" -import { Message } from "../session/message" +import { MessageV2 } from "../session/message-v2" export const TaskTool = Tool.define({ id: "task", description: DESCRIPTION, parameters: z.object({ - description: z - .string() - .describe("A short (3-5 words) description of the task"), + description: z.string().describe("A short (3-5 words) description of the task"), prompt: z.string().describe("The task for the agent to perform"), }), async execute(params, ctx) { const session = await Session.create(ctx.sessionID) - const msg = await Session.getMessage(ctx.sessionID, ctx.messageID) - const metadata = msg.metadata.assistant! + const msg = (await Session.getMessage(ctx.sessionID, ctx.messageID)) as MessageV2.Assistant - function summary(input: Message.Info) { + function summary(input: MessageV2.Info) { const result = [] - for (const part of input.parts) { - if (part.type === "tool-invocation") { - result.push({ - toolInvocation: part.toolInvocation, - metadata: input.metadata.tool[part.toolInvocation.toolCallId], - }) + if (part.type === "tool" && part.state.status === "completed") { + result.push(part) } } return result } - const unsub = Bus.subscribe(Message.Event.Updated, async (evt) => { - if (evt.properties.info.metadata.sessionID !== session.id) return + const unsub = Bus.subscribe(MessageV2.Event.Updated, async (evt) => { + if (evt.properties.info.sessionID !== session.id) return ctx.metadata({ title: params.description, - summary: summary(evt.properties.info), + metadata: { + summary: summary(evt.properties.info), + }, }) }) @@ -46,8 +41,8 @@ export const TaskTool = Tool.define({ }) const result = await Session.chat({ sessionID: session.id, - modelID: metadata.modelID, - providerID: metadata.providerID, + modelID: msg.modelID, + providerID: msg.providerID, parts: [ { type: "text", @@ -57,8 +52,8 @@ export const TaskTool = Tool.define({ }) unsub() return { + title: params.description, metadata: { - title: params.description, summary: summary(result), }, output: result.parts.findLast((x) => x.type === "text")!.text, diff --git a/packages/opencode/src/tool/todo.ts b/packages/opencode/src/tool/todo.ts index 33ac3d12..8a330c2d 100644 --- a/packages/opencode/src/tool/todo.ts +++ b/packages/opencode/src/tool/todo.ts @@ -5,12 +5,8 @@ import { App } from "../app/app" const TodoInfo = z.object({ content: z.string().min(1).describe("Brief description of the task"), - status: z - .enum(["pending", "in_progress", "completed"]) - .describe("Current status of the task"), - priority: z - .enum(["high", "medium", "low"]) - .describe("Priority level of the task"), + status: z.enum(["pending", "in_progress", "completed", "cancelled"]).describe("Current status of the task"), + priority: z.enum(["high", "medium", "low"]).describe("Priority level of the task"), id: z.string().describe("Unique identifier for the todo item"), }) type TodoInfo = z.infer @@ -32,9 +28,9 @@ export const TodoWriteTool = Tool.define({ const todos = state() todos[opts.sessionID] = params.todos return { + title: `${params.todos.filter((x) => x.status !== "completed").length} todos`, output: JSON.stringify(params.todos, null, 2), metadata: { - title: `${params.todos.filter((x) => x.status !== "completed").length} todos`, todos: params.todos, }, } @@ -48,9 +44,9 @@ export const TodoReadTool = Tool.define({ async execute(_params, opts) { const todos = state()[opts.sessionID] ?? [] return { + title: `${todos.filter((x) => x.status !== "completed").length} todos`, metadata: { todos, - title: `${todos.filter((x) => x.status !== "completed").length} todos`, }, output: JSON.stringify(todos, null, 2), } diff --git a/packages/opencode/src/tool/tool.ts b/packages/opencode/src/tool/tool.ts index 8c1cbf48..f44322ed 100644 --- a/packages/opencode/src/tool/tool.ts +++ b/packages/opencode/src/tool/tool.ts @@ -2,19 +2,15 @@ import type { StandardSchemaV1 } from "@standard-schema/spec" export namespace Tool { interface Metadata { - title: string [key: string]: any } export type Context = { sessionID: string messageID: string abort: AbortSignal - metadata(meta: M): void + metadata(input: { title?: string; metadata?: M }): void } - export interface Info< - Parameters extends StandardSchemaV1 = StandardSchemaV1, - M extends Metadata = Metadata, - > { + export interface Info { id: string description: string parameters: Parameters @@ -22,15 +18,15 @@ export namespace Tool { args: StandardSchemaV1.InferOutput, ctx: Context, ): Promise<{ + title: string metadata: M output: string }> } - export function define< - Parameters extends StandardSchemaV1, - Result extends Metadata, - >(input: Info): Info { + export function define( + input: Info, + ): Info { return input } } diff --git a/packages/opencode/src/tool/webfetch.ts b/packages/opencode/src/tool/webfetch.ts index 5b7b9f9d..235d2113 100644 --- a/packages/opencode/src/tool/webfetch.ts +++ b/packages/opencode/src/tool/webfetch.ts @@ -14,9 +14,7 @@ export const WebFetchTool = Tool.define({ url: z.string().describe("The URL to fetch content from"), format: z .enum(["text", "markdown", "html"]) - .describe( - "The format to return the content in (text, markdown, or html)", - ), + .describe("The format to return the content in (text, markdown, or html)"), timeout: z .number() .min(0) @@ -26,17 +24,11 @@ export const WebFetchTool = Tool.define({ }), async execute(params, ctx) { // Validate URL - if ( - !params.url.startsWith("http://") && - !params.url.startsWith("https://") - ) { + if (!params.url.startsWith("http://") && !params.url.startsWith("https://")) { throw new Error("URL must start with http:// or https://") } - const timeout = Math.min( - (params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, - MAX_TIMEOUT, - ) + const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT) const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), timeout) @@ -46,8 +38,7 @@ export const WebFetchTool = Tool.define({ headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", - Accept: - "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8", + Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9", }, }) @@ -79,16 +70,14 @@ export const WebFetchTool = Tool.define({ const text = await extractTextFromHTML(content) return { output: text, - metadata: { - title, - }, + title, + metadata: {}, } } return { output: content, - metadata: { - title, - }, + title, + metadata: {}, } case "markdown": @@ -96,32 +85,28 @@ export const WebFetchTool = Tool.define({ const markdown = convertHTMLToMarkdown(content) return { output: markdown, - metadata: { - title, - }, + title, + metadata: {}, } } return { output: "```\n" + content + "\n```", - metadata: { - title, - }, + title, + metadata: {}, } case "html": return { output: content, - metadata: { - title, - }, + title, + metadata: {}, } default: return { output: content, - metadata: { - title, - }, + title, + metadata: {}, } } }, @@ -143,16 +128,7 @@ async function extractTextFromHTML(html: string) { .on("*", { element(element) { // Reset skip flag when entering other elements - if ( - ![ - "script", - "style", - "noscript", - "iframe", - "object", - "embed", - ].includes(element.tagName) - ) { + if (!["script", "style", "noscript", "iframe", "object", "embed"].includes(element.tagName)) { skipContent = false } }, diff --git a/packages/opencode/src/tool/write.ts b/packages/opencode/src/tool/write.ts index b0515805..be92d626 100644 --- a/packages/opencode/src/tool/write.ts +++ b/packages/opencode/src/tool/write.ts @@ -13,18 +13,12 @@ export const WriteTool = Tool.define({ id: "write", description: DESCRIPTION, parameters: z.object({ - filePath: z - .string() - .describe( - "The absolute path to the file to write (must be absolute, not relative)", - ), + filePath: z.string().describe("The absolute path to the file to write (must be absolute, not relative)"), content: z.string().describe("The content to write to the file"), }), async execute(params, ctx) { const app = App.info() - const filepath = path.isAbsolute(params.filePath) - ? params.filePath - : path.join(app.path.cwd, params.filePath) + const filepath = path.isAbsolute(params.filePath) ? params.filePath : path.join(app.path.cwd, params.filePath) const file = Bun.file(filepath) const exists = await file.exists() @@ -33,9 +27,7 @@ export const WriteTool = Tool.define({ await Permission.ask({ id: "write", sessionID: ctx.sessionID, - title: exists - ? "Overwrite this file: " + filepath - : "Create new file: " + filepath, + title: exists ? "Overwrite this file: " + filepath : "Create new file: " + filepath, metadata: { filePath: filepath, content: params.content, @@ -62,11 +54,11 @@ export const WriteTool = Tool.define({ } return { + title: path.relative(app.path.root, filepath), metadata: { diagnostics, filepath, exists: exists, - title: path.relative(app.path.root, filepath), }, output, } diff --git a/packages/opencode/src/util/error.ts b/packages/opencode/src/util/error.ts index be8764ee..53b434c6 100644 --- a/packages/opencode/src/util/error.ts +++ b/packages/opencode/src/util/error.ts @@ -7,10 +7,7 @@ export abstract class NamedError extends Error { abstract schema(): ZodSchema abstract toObject(): { name: string; data: any } - static create( - name: Name, - data: Data, - ) { + static create(name: Name, data: Data) { const schema = z .object({ name: z.literal(name), diff --git a/packages/opencode/src/util/filesystem.ts b/packages/opencode/src/util/filesystem.ts index c4fd163c..318f60b9 100644 --- a/packages/opencode/src/util/filesystem.ts +++ b/packages/opencode/src/util/filesystem.ts @@ -1,7 +1,17 @@ import { exists } from "fs/promises" -import { dirname, join } from "path" +import { dirname, join, relative } from "path" export namespace Filesystem { + export function overlaps(a: string, b: string) { + const relA = relative(a, b) + const relB = relative(b, a) + return !relA || !relA.startsWith("..") || !relB || !relB.startsWith("..") + } + + export function contains(parent: string, child: string) { + return relative(parent, child).startsWith("..") + } + export async function findUp(target: string, start: string, stop?: string) { let current = start const result = [] diff --git a/packages/opencode/src/util/log.ts b/packages/opencode/src/util/log.ts index b73e2dee..50749dae 100644 --- a/packages/opencode/src/util/log.ts +++ b/packages/opencode/src/util/log.ts @@ -1,15 +1,59 @@ import path from "path" import fs from "fs/promises" import { Global } from "../global" +import z from "zod" + export namespace Log { + export const Level = z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).openapi({ ref: "LogLevel", description: "Log level" }) + export type Level = z.infer + + const levelPriority: Record = { + DEBUG: 0, + INFO: 1, + WARN: 2, + ERROR: 3, + } + + let currentLevel: Level = "INFO" + + export function setLevel(level: Level) { + currentLevel = level + } + + export function getLevel(): Level { + return currentLevel + } + + function shouldLog(level: Level): boolean { + return levelPriority[level] >= levelPriority[currentLevel] + } + + export type Logger = { + debug(message?: any, extra?: Record): void + info(message?: any, extra?: Record): void + error(message?: any, extra?: Record): void + warn(message?: any, extra?: Record): void + tag(key: string, value: string): Logger + clone(): Logger + time( + message: string, + extra?: Record, + ): { + stop(): void + [Symbol.dispose](): void + } + } + + const loggers = new Map() + export const Default = create({ service: "default" }) export interface Options { print: boolean + level?: Level } let logpath = "" - export function file() { return logpath } @@ -19,10 +63,7 @@ export namespace Log { await fs.mkdir(dir, { recursive: true }) cleanup(dir) if (options.print) return - logpath = path.join( - dir, - new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log", - ) + logpath = path.join(dir, new Date().toISOString().split(".")[0].replace(/:/g, "") + ".log") const logfile = Bun.file(logpath) await fs.truncate(logpath).catch(() => {}) const writer = logfile.writer() @@ -43,15 +84,21 @@ export namespace Log { const filesToDelete = files.slice(0, -10) - await Promise.all( - filesToDelete.map((file) => fs.unlink(file).catch(() => {})), - ) + await Promise.all(filesToDelete.map((file) => fs.unlink(file).catch(() => {}))) } let last = Date.now() export function create(tags?: Record) { tags = tags || {} + const service = tags["service"] + if (service && typeof service === "string") { + const cached = loggers.get(service) + if (cached) { + return cached + } + } + function build(message: any, extra?: Record) { const prefix = Object.entries({ ...tags, @@ -63,21 +110,28 @@ export namespace Log { const next = new Date() const diff = next.getTime() - last last = next.getTime() - return ( - [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message] - .filter(Boolean) - .join(" ") + "\n" - ) + return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n" } - const result = { + const result: Logger = { + debug(message?: any, extra?: Record) { + if (shouldLog("DEBUG")) { + process.stderr.write("DEBUG " + build(message, extra)) + } + }, info(message?: any, extra?: Record) { - process.stderr.write("INFO " + build(message, extra)) + if (shouldLog("INFO")) { + process.stderr.write("INFO " + build(message, extra)) + } }, error(message?: any, extra?: Record) { - process.stderr.write("ERROR " + build(message, extra)) + if (shouldLog("ERROR")) { + process.stderr.write("ERROR " + build(message, extra)) + } }, warn(message?: any, extra?: Record) { - process.stderr.write("WARN " + build(message, extra)) + if (shouldLog("WARN")) { + process.stderr.write("WARN " + build(message, extra)) + } }, tag(key: string, value: string) { if (tags) tags[key] = value @@ -105,6 +159,10 @@ export namespace Log { }, } + if (service && typeof service === "string") { + loggers.set(service, result) + } + return result } } diff --git a/packages/opencode/test/tool/edit.test.ts b/packages/opencode/test/tool/edit.test.ts index 6de4f2a7..6906062d 100644 --- a/packages/opencode/test/tool/edit.test.ts +++ b/packages/opencode/test/tool/edit.test.ts @@ -17,12 +17,7 @@ const testCases: TestCase[] = [ replace: 'console.log("universe");', }, { - content: [ - "if (condition) {", - " doSomething();", - " doSomethingElse();", - "}", - ].join("\n"), + content: ["if (condition) {", " doSomething();", " doSomethingElse();", "}"].join("\n"), find: [" doSomething();", " doSomethingElse();"].join("\n"), replace: [" doNewThing();", " doAnotherThing();"].join("\n"), }, @@ -53,15 +48,8 @@ const testCases: TestCase[] = [ " return result;", "}", ].join("\n"), - find: [ - "function calculate(a, b) {", - " // different middle content", - " return result;", - "}", - ].join("\n"), - replace: ["function calculate(a, b) {", " return a * b * 2;", "}"].join( - "\n", - ), + find: ["function calculate(a, b) {", " // different middle content", " return result;", "}"].join("\n"), + replace: ["function calculate(a, b) {", " return a * b * 2;", "}"].join("\n"), }, { content: [ @@ -76,13 +64,7 @@ const testCases: TestCase[] = [ "}", ].join("\n"), find: ["class MyClass {", " // different implementation", "}"].join("\n"), - replace: [ - "class MyClass {", - " constructor() {", - " this.value = 42;", - " }", - "}", - ].join("\n"), + replace: ["class MyClass {", " constructor() {", " this.value = 42;", " }", "}"].join("\n"), }, // WhitespaceNormalizedReplacer cases @@ -104,48 +86,21 @@ const testCases: TestCase[] = [ // IndentationFlexibleReplacer cases { - content: [ - " function nested() {", - ' console.log("deeply nested");', - " return true;", - " }", - ].join("\n"), - find: [ - "function nested() {", - ' console.log("deeply nested");', - " return true;", - "}", - ].join("\n"), - replace: [ - "function nested() {", - ' console.log("updated");', - " return false;", - "}", - ].join("\n"), + content: [" function nested() {", ' console.log("deeply nested");', " return true;", " }"].join( + "\n", + ), + find: ["function nested() {", ' console.log("deeply nested");', " return true;", "}"].join("\n"), + replace: ["function nested() {", ' console.log("updated");', " return false;", "}"].join("\n"), }, { - content: [ - " if (true) {", - ' console.log("level 1");', - ' console.log("level 2");', - " }", - ].join("\n"), - find: [ - "if (true) {", - 'console.log("level 1");', - ' console.log("level 2");', - "}", - ].join("\n"), + content: [" if (true) {", ' console.log("level 1");', ' console.log("level 2");', " }"].join("\n"), + find: ["if (true) {", 'console.log("level 1");', ' console.log("level 2");', "}"].join("\n"), replace: ["if (true) {", 'console.log("updated");', "}"].join("\n"), }, // replaceAll option cases { - content: [ - 'console.log("test");', - 'console.log("test");', - 'console.log("test");', - ].join("\n"), + content: ['console.log("test");', 'console.log("test");', 'console.log("test");'].join("\n"), find: 'console.log("test");', replace: 'console.log("updated");', all: true, @@ -213,9 +168,7 @@ const testCases: TestCase[] = [ // MultiOccurrenceReplacer cases (with replaceAll) { - content: ["debug('start');", "debug('middle');", "debug('end');"].join( - "\n", - ), + content: ["debug('start');", "debug('middle');", "debug('end');"].join("\n"), find: "debug", replace: "log", all: true, @@ -239,9 +192,7 @@ const testCases: TestCase[] = [ replace: "const value = 24;", }, { - content: ["", " if (condition) {", " doSomething();", " }", ""].join( - "\n", - ), + content: ["", " if (condition) {", " doSomething();", " }", ""].join("\n"), find: ["if (condition) {", " doSomething();", "}"].join("\n"), replace: ["if (condition) {", " doNothing();", "}"].join("\n"), }, @@ -262,9 +213,7 @@ const testCases: TestCase[] = [ " return result;", "}", ].join("\n"), - replace: ["function calculate(a, b) {", " return (a + b) * 2;", "}"].join( - "\n", - ), + replace: ["function calculate(a, b) {", " return (a + b) * 2;", "}"].join("\n"), }, { content: [ @@ -278,15 +227,8 @@ const testCases: TestCase[] = [ " }", "}", ].join("\n"), - find: [ - "class TestClass {", - " // different implementation", - " // with multiple lines", - "}", - ].join("\n"), - replace: ["class TestClass {", " getValue() { return 42; }", "}"].join( - "\n", - ), + find: ["class TestClass {", " // different implementation", " // with multiple lines", "}"].join("\n"), + replace: ["class TestClass {", " getValue() { return 42; }", "}"].join("\n"), }, // Combined edge cases for new replacers @@ -296,9 +238,7 @@ const testCases: TestCase[] = [ replace: 'console.log("updated");', }, { - content: [" ", "function test() {", " return 'value';", "}", " "].join( - "\n", - ), + content: [" ", "function test() {", " return 'value';", "}", " "].join("\n"), find: ["function test() {", "return 'value';", "}"].join("\n"), replace: ["function test() {", "return 'new value';", "}"].join("\n"), }, @@ -346,13 +286,7 @@ const testCases: TestCase[] = [ // ContextAwareReplacer - test with trailing newline in find string { - content: [ - "class Test {", - " method1() {", - " return 1;", - " }", - "}", - ].join("\n"), + content: ["class Test {", " method1() {", " return 1;", " }", "}"].join("\n"), find: [ "class Test {", " // different content", @@ -401,12 +335,7 @@ describe("EditTool Replacers", () => { replace(testCase.content, testCase.find, testCase.replace, testCase.all) }).toThrow() } else { - const result = replace( - testCase.content, - testCase.find, - testCase.replace, - testCase.all, - ) + const result = replace(testCase.content, testCase.find, testCase.replace, testCase.all) expect(result).toContain(testCase.replace) } }) diff --git a/packages/opencode/test/tool/tool.test.ts b/packages/opencode/test/tool/tool.test.ts index 4723a61d..88325029 100644 --- a/packages/opencode/test/tool/tool.test.ts +++ b/packages/opencode/test/tool/tool.test.ts @@ -42,10 +42,7 @@ describe("tool.glob", () => { describe("tool.ls", () => { test("basic", async () => { const result = await App.provide({ cwd: process.cwd() }, async () => { - return await ListTool.execute( - { path: "./example", ignore: [".git"] }, - ctx, - ) + return await ListTool.execute({ path: "./example", ignore: [".git"] }, ctx) }) expect(result.output).toMatchSnapshot() }) diff --git a/packages/tui/cmd/opencode/main.go b/packages/tui/cmd/opencode/main.go index a9283525..31ef03e5 100644 --- a/packages/tui/cmd/opencode/main.go +++ b/packages/tui/cmd/opencode/main.go @@ -5,14 +5,16 @@ import ( "encoding/json" "log/slog" "os" - "path/filepath" "strings" tea "github.com/charmbracelet/bubbletea/v2" + flag "github.com/spf13/pflag" "github.com/sst/opencode-sdk-go" "github.com/sst/opencode-sdk-go/option" "github.com/sst/opencode/internal/app" + "github.com/sst/opencode/internal/clipboard" "github.com/sst/opencode/internal/tui" + "github.com/sst/opencode/internal/util" ) var Version = "dev" @@ -23,6 +25,10 @@ func main() { version = "v" + Version } + var model *string = flag.String("model", "", "model to begin with") + var prompt *string = flag.String("prompt", "", "prompt to begin with") + flag.Parse() + url := os.Getenv("OPENCODE_SERVER") appInfoStr := os.Getenv("OPENCODE_APP_INFO") @@ -33,39 +39,28 @@ func main() { os.Exit(1) } - logfile := filepath.Join(appInfo.Path.Data, "log", "tui.log") - if _, err := os.Stat(filepath.Dir(logfile)); os.IsNotExist(err) { - err := os.MkdirAll(filepath.Dir(logfile), 0755) - if err != nil { - slog.Error("Failed to create log directory", "error", err) - os.Exit(1) - } - } - file, err := os.Create(logfile) - if err != nil { - slog.Error("Failed to create log file", "error", err) - os.Exit(1) - } - defer file.Close() - logger := slog.New(slog.NewTextHandler(file, &slog.HandlerOptions{Level: slog.LevelDebug})) - slog.SetDefault(logger) - - slog.Debug("TUI launched", "app", appInfo) - httpClient := opencode.NewClient( option.WithBaseURL(url), ) - if err != nil { - slog.Error("Failed to create client", "error", err) - os.Exit(1) - } + apiHandler := util.NewAPILogHandler(httpClient, "tui", slog.LevelDebug) + logger := slog.New(apiHandler) + slog.SetDefault(logger) + + slog.Debug("TUI launched", "app", appInfo) + + go func() { + err = clipboard.Init() + if err != nil { + slog.Error("Failed to initialize clipboard", "error", err) + } + }() // Create main context for the application ctx, cancel := context.WithCancel(context.Background()) defer cancel() - app_, err := app.New(ctx, version, appInfo, httpClient) + app_, err := app.New(ctx, version, appInfo, httpClient, model, prompt) if err != nil { panic(err) } diff --git a/packages/tui/go.mod b/packages/tui/go.mod index 74047af1..12dd3f88 100644 --- a/packages/tui/go.mod +++ b/packages/tui/go.mod @@ -10,13 +10,14 @@ require ( github.com/charmbracelet/glamour v0.10.0 github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1 github.com/charmbracelet/x/ansi v0.8.0 + github.com/google/uuid v1.6.0 github.com/lithammer/fuzzysearch v1.1.8 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 github.com/muesli/reflow v0.3.0 github.com/muesli/termenv v0.16.0 github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 github.com/sst/opencode-sdk-go v0.1.0-alpha.8 - github.com/tidwall/gjson v1.14.4 + golang.org/x/image v0.28.0 rsc.io/qr v0.2.0 ) @@ -37,7 +38,6 @@ require ( github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect github.com/goccy/go-yaml v1.17.1 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/invopop/yaml v0.3.1 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/mailru/easyjson v0.7.7 // indirect @@ -50,23 +50,23 @@ require ( github.com/sosodev/duration v1.3.1 // indirect github.com/speakeasy-api/openapi-overlay v0.9.0 // indirect github.com/spf13/cobra v1.9.1 // indirect + github.com/tidwall/gjson v1.14.4 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect - golang.org/x/mod v0.24.0 // indirect - golang.org/x/tools v0.31.0 // indirect + golang.org/x/mod v0.25.0 // indirect + golang.org/x/tools v0.34.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( - github.com/atotto/clipboard v0.1.4 + github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/charmbracelet/colorprofile v0.3.1 // indirect github.com/charmbracelet/x/cellbuf v0.0.14-0.20250501183327-ad3bc78c6a81 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect - github.com/disintegration/imaging v1.6.2 github.com/dlclark/regexp2 v1.11.5 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/gorilla/css v1.0.1 // indirect @@ -78,16 +78,15 @@ require ( github.com/muesli/cancelreader v0.2.2 // indirect github.com/rivo/uniseg v0.4.7 github.com/rogpeppe/go-internal v1.14.1 // indirect - github.com/spf13/pflag v1.0.6 // indirect + github.com/spf13/pflag v1.0.6 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.5 // indirect - golang.org/x/image v0.26.0 - golang.org/x/net v0.39.0 // indirect - golang.org/x/sync v0.13.0 // indirect - golang.org/x/sys v0.32.0 // indirect - golang.org/x/term v0.31.0 // indirect - golang.org/x/text v0.24.0 + golang.org/x/net v0.41.0 // indirect + golang.org/x/sync v0.15.0 // indirect + golang.org/x/sys v0.33.0 // indirect + golang.org/x/term v0.32.0 // indirect + golang.org/x/text v0.26.0 gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/packages/tui/go.sum b/packages/tui/go.sum index fdc5bbb0..9eab3f57 100644 --- a/packages/tui/go.sum +++ b/packages/tui/go.sum @@ -54,8 +54,6 @@ github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= -github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= @@ -218,14 +216,13 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= -golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/image v0.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY= -golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c= +golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE= +golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= -golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= +golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w= +golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -236,15 +233,15 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= -golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= +golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= +golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= -golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= +golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -263,28 +260,28 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= -golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= -golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= +golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg= +golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= -golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= -golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= +golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= +golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/packages/tui/internal/app/app.go b/packages/tui/internal/app/app.go index 469857ab..a70b3ca6 100644 --- a/packages/tui/internal/app/app.go +++ b/packages/tui/internal/app/app.go @@ -12,6 +12,7 @@ import ( tea "github.com/charmbracelet/bubbletea/v2" "github.com/sst/opencode-sdk-go" + "github.com/sst/opencode/internal/clipboard" "github.com/sst/opencode/internal/commands" "github.com/sst/opencode/internal/components/toast" "github.com/sst/opencode/internal/config" @@ -21,17 +22,20 @@ import ( ) type App struct { - Info opencode.App - Version string - StatePath string - Config *opencode.Config - Client *opencode.Client - State *config.State - Provider *opencode.Provider - Model *opencode.Model - Session *opencode.Session - Messages []opencode.Message - Commands commands.CommandRegistry + Info opencode.App + Version string + StatePath string + Config *opencode.Config + Client *opencode.Client + State *config.State + Provider *opencode.Provider + Model *opencode.Model + Session *opencode.Session + Messages []opencode.MessageUnion + Commands commands.CommandRegistry + InitialModel *string + InitialPrompt *string + compactCancel context.CancelFunc } type SessionSelectedMsg = *opencode.Session @@ -47,7 +51,7 @@ type SendMsg struct { Attachments []opencode.FilePartParam } type OptimisticMessageAddedMsg struct { - Message opencode.Message + Message opencode.MessageUnion } type FileRenderedMsg struct { FilePath string @@ -58,6 +62,8 @@ func New( version string, appInfo opencode.App, httpClient *opencode.Client, + model *string, + prompt *string, ) (*App, error) { util.RootPath = appInfo.Path.Root util.CwdPath = appInfo.Path.Cwd @@ -109,15 +115,17 @@ func New( slog.Debug("Loaded config", "config", configInfo) app := &App{ - Info: appInfo, - Version: version, - StatePath: appStatePath, - Config: configInfo, - State: appState, - Client: httpClient, - Session: &opencode.Session{}, - Messages: []opencode.Message{}, - Commands: commands.LoadFromConfig(configInfo), + Info: appInfo, + Version: version, + StatePath: appStatePath, + Config: configInfo, + State: appState, + Client: httpClient, + Session: &opencode.Session{}, + Messages: []opencode.MessageUnion{}, + Commands: commands.LoadFromConfig(configInfo), + InitialModel: model, + InitialPrompt: prompt, } return app, nil @@ -140,66 +148,102 @@ func (a *App) Key(commandName commands.CommandName) string { return base(key) + muted(" "+command.Description) } +func (a *App) SetClipboard(text string) tea.Cmd { + var cmds []tea.Cmd + cmds = append(cmds, func() tea.Msg { + clipboard.Write(clipboard.FmtText, []byte(text)) + return nil + }) + // try to set the clipboard using OSC52 for terminals that support it + cmds = append(cmds, tea.SetClipboard(text)) + return tea.Sequence(cmds...) +} + func (a *App) InitializeProvider() tea.Cmd { - return func() tea.Msg { - providersResponse, err := a.Client.Config.Providers(context.Background()) - if err != nil { - slog.Error("Failed to list providers", "error", err) - // TODO: notify user - return nil - } - providers := providersResponse.Providers - var defaultProvider *opencode.Provider - var defaultModel *opencode.Model + providersResponse, err := a.Client.Config.Providers(context.Background()) + if err != nil { + slog.Error("Failed to list providers", "error", err) + // TODO: notify user + return nil + } + providers := providersResponse.Providers + var defaultProvider *opencode.Provider + var defaultModel *opencode.Model - var anthropic *opencode.Provider - for _, provider := range providers { - if provider.ID == "anthropic" { - anthropic = &provider + var anthropic *opencode.Provider + for _, provider := range providers { + if provider.ID == "anthropic" { + anthropic = &provider + } + } + + // default to anthropic if available + if anthropic != nil { + defaultProvider = anthropic + defaultModel = getDefaultModel(providersResponse, *anthropic) + } + + for _, provider := range providers { + if defaultProvider == nil || defaultModel == nil { + defaultProvider = &provider + defaultModel = getDefaultModel(providersResponse, provider) + } + providers = append(providers, provider) + } + if len(providers) == 0 { + slog.Error("No providers configured") + return nil + } + + var currentProvider *opencode.Provider + var currentModel *opencode.Model + for _, provider := range providers { + if provider.ID == a.State.Provider { + currentProvider = &provider + + for _, model := range provider.Models { + if model.ID == a.State.Model { + currentModel = &model + } } } + } + if currentProvider == nil || currentModel == nil { + currentProvider = defaultProvider + currentModel = defaultModel + } - // default to anthropic if available - if anthropic != nil { - defaultProvider = anthropic - defaultModel = getDefaultModel(providersResponse, *anthropic) - } - + var initialProvider *opencode.Provider + var initialModel *opencode.Model + if a.InitialModel != nil && *a.InitialModel != "" { + splits := strings.Split(*a.InitialModel, "/") for _, provider := range providers { - if defaultProvider == nil || defaultModel == nil { - defaultProvider = &provider - defaultModel = getDefaultModel(providersResponse, provider) - } - providers = append(providers, provider) - } - if len(providers) == 0 { - slog.Error("No providers configured") - return nil - } - - var currentProvider *opencode.Provider - var currentModel *opencode.Model - for _, provider := range providers { - if provider.ID == a.State.Provider { - currentProvider = &provider - + if provider.ID == splits[0] { + initialProvider = &provider for _, model := range provider.Models { - if model.ID == a.State.Model { - currentModel = &model + modelID := strings.Join(splits[1:], "/") + if model.ID == modelID { + initialModel = &model } } } } - if currentProvider == nil || currentModel == nil { - currentProvider = defaultProvider - currentModel = defaultModel - } - - return ModelSelectedMsg{ - Provider: *currentProvider, - Model: *currentModel, - } } + + if initialProvider != nil && initialModel != nil { + currentProvider = initialProvider + currentModel = initialModel + } + + var cmds []tea.Cmd + cmds = append(cmds, util.CmdHandler(ModelSelectedMsg{ + Provider: *currentProvider, + Model: *currentModel, + })) + if a.InitialPrompt != nil && *a.InitialPrompt != "" { + cmds = append(cmds, util.CmdHandler(SendMsg{Text: *a.InitialPrompt})) + } + return tea.Sequence(cmds...) } func getDefaultModel( @@ -223,7 +267,10 @@ func (a *App) IsBusy() bool { } lastMessage := a.Messages[len(a.Messages)-1] - return lastMessage.Metadata.Time.Completed == 0 + if casted, ok := lastMessage.(opencode.AssistantMessage); ok { + return casted.Time.Completed == 0 + } + return false } func (a *App) SaveState() { @@ -260,13 +307,26 @@ func (a *App) InitializeProject(ctx context.Context) tea.Cmd { } func (a *App) CompactSession(ctx context.Context) tea.Cmd { + if a.compactCancel != nil { + a.compactCancel() + } + + compactCtx, cancel := context.WithCancel(ctx) + a.compactCancel = cancel + go func() { - _, err := a.Client.Session.Summarize(ctx, a.Session.ID, opencode.SessionSummarizeParams{ + defer func() { + a.compactCancel = nil + }() + + _, err := a.Client.Session.Summarize(compactCtx, a.Session.ID, opencode.SessionSummarizeParams{ ProviderID: opencode.F(a.Provider.ID), ModelID: opencode.F(a.Model.ID), }) if err != nil { - slog.Error("Failed to compact session", "error", err) + if compactCtx.Err() != context.Canceled { + slog.Error("Failed to compact session", "error", err) + } } }() return nil @@ -304,30 +364,28 @@ func (a *App) SendChatMessage( cmds = append(cmds, util.CmdHandler(SessionSelectedMsg(session))) } - optimisticParts := []opencode.MessagePart{{ - Type: opencode.MessagePartTypeText, + optimisticParts := []opencode.UserMessagePart{{ + Type: opencode.UserMessagePartTypeText, Text: text, }} if len(attachments) > 0 { for _, attachment := range attachments { - optimisticParts = append(optimisticParts, opencode.MessagePart{ - Type: opencode.MessagePartTypeFile, - Filename: attachment.Filename.Value, - MediaType: attachment.MediaType.Value, - URL: attachment.URL.Value, + optimisticParts = append(optimisticParts, opencode.UserMessagePart{ + Type: opencode.UserMessagePartTypeFile, + Filename: attachment.Filename.Value, + Mime: attachment.Mime.Value, + URL: attachment.URL.Value, }) } } - optimisticMessage := opencode.Message{ - ID: fmt.Sprintf("optimistic-%d", time.Now().UnixNano()), - Role: opencode.MessageRoleUser, - Parts: optimisticParts, - Metadata: opencode.MessageMetadata{ - SessionID: a.Session.ID, - Time: opencode.MessageMetadataTime{ - Created: float64(time.Now().Unix()), - }, + optimisticMessage := opencode.UserMessage{ + ID: fmt.Sprintf("optimistic-%d", time.Now().UnixNano()), + Role: opencode.UserMessageRoleUser, + Parts: optimisticParts, + SessionID: a.Session.ID, + Time: opencode.UserMessageTime{ + Created: float64(time.Now().Unix()), }, } @@ -335,7 +393,7 @@ func (a *App) SendChatMessage( cmds = append(cmds, util.CmdHandler(OptimisticMessageAddedMsg{Message: optimisticMessage})) cmds = append(cmds, func() tea.Msg { - parts := []opencode.MessagePartUnionParam{ + parts := []opencode.UserMessagePartUnionParam{ opencode.TextPartParam{ Type: opencode.F(opencode.TextPartTypeText), Text: opencode.F(text), @@ -344,10 +402,10 @@ func (a *App) SendChatMessage( if len(attachments) > 0 { for _, attachment := range attachments { parts = append(parts, opencode.FilePartParam{ - MediaType: attachment.MediaType, - Type: attachment.Type, - URL: attachment.URL, - Filename: attachment.Filename, + Mime: attachment.Mime, + Type: attachment.Type, + URL: attachment.URL, + Filename: attachment.Filename, }) } } @@ -371,6 +429,12 @@ func (a *App) SendChatMessage( } func (a *App) Cancel(ctx context.Context, sessionID string) error { + // Cancel any running compact operation + if a.compactCancel != nil { + a.compactCancel() + a.compactCancel = nil + } + _, err := a.Client.Session.Abort(ctx, sessionID) if err != nil { slog.Error("Failed to cancel session", "error", err) diff --git a/packages/tui/internal/clipboard/clipboard.go b/packages/tui/internal/clipboard/clipboard.go new file mode 100644 index 00000000..70e05bd2 --- /dev/null +++ b/packages/tui/internal/clipboard/clipboard.go @@ -0,0 +1,155 @@ +// Copyright 2021 The golang.design Initiative Authors. +// All rights reserved. Use of this source code is governed +// by a MIT license that can be found in the LICENSE file. +// +// Written by Changkun Ou + +/* +Package clipboard provides cross platform clipboard access and supports +macOS/Linux/Windows/Android/iOS platform. Before interacting with the +clipboard, one must call Init to assert if it is possible to use this +package: + + err := clipboard.Init() + if err != nil { + panic(err) + } + +The most common operations are `Read` and `Write`. To use them: + + // write/read text format data of the clipboard, and + // the byte buffer regarding the text are UTF8 encoded. + clipboard.Write(clipboard.FmtText, []byte("text data")) + clipboard.Read(clipboard.FmtText) + + // write/read image format data of the clipboard, and + // the byte buffer regarding the image are PNG encoded. + clipboard.Write(clipboard.FmtImage, []byte("image data")) + clipboard.Read(clipboard.FmtImage) + +Note that read/write regarding image format assumes that the bytes are +PNG encoded since it serves the alpha blending purpose that might be +used in other graphical software. + +In addition, `clipboard.Write` returns a channel that can receive an +empty struct as a signal, which indicates the corresponding write call +to the clipboard is outdated, meaning the clipboard has been overwritten +by others and the previously written data is lost. For instance: + + changed := clipboard.Write(clipboard.FmtText, []byte("text data")) + + select { + case <-changed: + println(`"text data" is no longer available from clipboard.`) + } + +You can ignore the returning channel if you don't need this type of +notification. Furthermore, when you need more than just knowing whether +clipboard data is changed, use the watcher API: + + ch := clipboard.Watch(context.TODO(), clipboard.FmtText) + for data := range ch { + // print out clipboard data whenever it is changed + println(string(data)) + } +*/ +package clipboard + +import ( + "context" + "errors" + "fmt" + "os" + "sync" +) + +var ( + // activate only for running tests. + debug = false + errUnavailable = errors.New("clipboard unavailable") + errUnsupported = errors.New("unsupported format") + errNoCgo = errors.New("clipboard: cannot use when CGO_ENABLED=0") +) + +// Format represents the format of clipboard data. +type Format int + +// All sorts of supported clipboard data +const ( + // FmtText indicates plain text clipboard format + FmtText Format = iota + // FmtImage indicates image/png clipboard format + FmtImage +) + +var ( + // Due to the limitation on operating systems (such as darwin), + // concurrent read can even cause panic, use a global lock to + // guarantee one read at a time. + lock = sync.Mutex{} + initOnce sync.Once + initError error +) + +// Init initializes the clipboard package. It returns an error +// if the clipboard is not available to use. This may happen if the +// target system lacks required dependency, such as libx11-dev in X11 +// environment. For example, +// +// err := clipboard.Init() +// if err != nil { +// panic(err) +// } +// +// If Init returns an error, any subsequent Read/Write/Watch call +// may result in an unrecoverable panic. +func Init() error { + initOnce.Do(func() { + initError = initialize() + }) + return initError +} + +// Read returns a chunk of bytes of the clipboard data if it presents +// in the desired format t presents. Otherwise, it returns nil. +func Read(t Format) []byte { + lock.Lock() + defer lock.Unlock() + + buf, err := read(t) + if err != nil { + if debug { + fmt.Fprintf(os.Stderr, "read clipboard err: %v\n", err) + } + return nil + } + return buf +} + +// Write writes a given buffer to the clipboard in a specified format. +// Write returned a receive-only channel can receive an empty struct +// as a signal, which indicates the clipboard has been overwritten from +// this write. +// If format t indicates an image, then the given buf assumes +// the image data is PNG encoded. +func Write(t Format, buf []byte) <-chan struct{} { + lock.Lock() + defer lock.Unlock() + + changed, err := write(t, buf) + if err != nil { + if debug { + fmt.Fprintf(os.Stderr, "write to clipboard err: %v\n", err) + } + return nil + } + return changed +} + +// Watch returns a receive-only channel that received the clipboard data +// whenever any change of clipboard data in the desired format happens. +// +// The returned channel will be closed if the given context is canceled. +func Watch(ctx context.Context, t Format) <-chan []byte { + return watch(ctx, t) +} diff --git a/packages/tui/internal/clipboard/clipboard_darwin.go b/packages/tui/internal/clipboard/clipboard_darwin.go new file mode 100644 index 00000000..ead6811f --- /dev/null +++ b/packages/tui/internal/clipboard/clipboard_darwin.go @@ -0,0 +1,266 @@ +// Copyright 2021 The golang.design Initiative Authors. +// All rights reserved. Use of this source code is governed +// by a MIT license that can be found in the LICENSE file. +// +// Written by Changkun Ou + +//go:build darwin + +package clipboard + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "strconv" + "strings" + "sync" + "time" +) + +var ( + lastChangeCount int64 + changeCountMu sync.Mutex +) + +func initialize() error { return nil } + +func read(t Format) (buf []byte, err error) { + switch t { + case FmtText: + return readText() + case FmtImage: + return readImage() + default: + return nil, errUnsupported + } +} + +func readText() ([]byte, error) { + // Check if clipboard contains string data + checkScript := ` + try + set clipboardTypes to (clipboard info) + repeat with aType in clipboardTypes + if (first item of aType) is string then + return "hastext" + end if + end repeat + return "notext" + on error + return "error" + end try + ` + + cmd := exec.Command("osascript", "-e", checkScript) + checkOut, err := cmd.Output() + if err != nil { + return nil, errUnavailable + } + + checkOut = bytes.TrimSpace(checkOut) + if !bytes.Equal(checkOut, []byte("hastext")) { + return nil, errUnavailable + } + + // Now get the actual text + cmd = exec.Command("osascript", "-e", "get the clipboard") + out, err := cmd.Output() + if err != nil { + return nil, errUnavailable + } + // Remove trailing newline that osascript adds + out = bytes.TrimSuffix(out, []byte("\n")) + + // If clipboard was set to empty string, return nil + if len(out) == 0 { + return nil, nil + } + return out, nil +} +func readImage() ([]byte, error) { + // AppleScript to read image data from clipboard as base64 + script := ` + try + set theData to the clipboard as «class PNGf» + return theData + on error + return "" + end try + ` + + cmd := exec.Command("osascript", "-e", script) + out, err := cmd.Output() + if err != nil { + return nil, errUnavailable + } + + // Check if we got any data + out = bytes.TrimSpace(out) + if len(out) == 0 { + return nil, errUnavailable + } + + // The output is in hex format (e.g., «data PNGf89504E...») + // We need to extract and convert it + outStr := string(out) + if !strings.HasPrefix(outStr, "«data PNGf") || !strings.HasSuffix(outStr, "»") { + return nil, errUnavailable + } + + // Extract hex data + hexData := strings.TrimPrefix(outStr, "«data PNGf") + hexData = strings.TrimSuffix(hexData, "»") + + // Convert hex to bytes + buf := make([]byte, len(hexData)/2) + for i := 0; i < len(hexData); i += 2 { + b, err := strconv.ParseUint(hexData[i:i+2], 16, 8) + if err != nil { + return nil, errUnavailable + } + buf[i/2] = byte(b) + } + + return buf, nil +} + +// write writes the given data to clipboard and +// returns true if success or false if failed. +func write(t Format, buf []byte) (<-chan struct{}, error) { + var err error + switch t { + case FmtText: + err = writeText(buf) + case FmtImage: + err = writeImage(buf) + default: + return nil, errUnsupported + } + + if err != nil { + return nil, err + } + + // Update change count + changeCountMu.Lock() + lastChangeCount++ + currentCount := lastChangeCount + changeCountMu.Unlock() + + // use unbuffered channel to prevent goroutine leak + changed := make(chan struct{}, 1) + go func() { + for { + time.Sleep(time.Second) + changeCountMu.Lock() + if lastChangeCount != currentCount { + changeCountMu.Unlock() + changed <- struct{}{} + close(changed) + return + } + changeCountMu.Unlock() + } + }() + return changed, nil +} + +func writeText(buf []byte) error { + if len(buf) == 0 { + // Clear clipboard + script := `set the clipboard to ""` + cmd := exec.Command("osascript", "-e", script) + if err := cmd.Run(); err != nil { + return errUnavailable + } + return nil + } + + // Escape the text for AppleScript + text := string(buf) + text = strings.ReplaceAll(text, "\\", "\\\\") + text = strings.ReplaceAll(text, "\"", "\\\"") + + script := fmt.Sprintf(`set the clipboard to "%s"`, text) + cmd := exec.Command("osascript", "-e", script) + if err := cmd.Run(); err != nil { + return errUnavailable + } + return nil +} +func writeImage(buf []byte) error { + if len(buf) == 0 { + // Clear clipboard + script := `set the clipboard to ""` + cmd := exec.Command("osascript", "-e", script) + if err := cmd.Run(); err != nil { + return errUnavailable + } + return nil + } + + // Create a temporary file to store the PNG data + tmpFile, err := os.CreateTemp("", "clipboard*.png") + if err != nil { + return errUnavailable + } + defer os.Remove(tmpFile.Name()) + + if _, err := tmpFile.Write(buf); err != nil { + tmpFile.Close() + return errUnavailable + } + tmpFile.Close() + + // Use osascript to set clipboard to the image file + script := fmt.Sprintf(` + set theFile to POSIX file "%s" + set theImage to read theFile as «class PNGf» + set the clipboard to theImage + `, tmpFile.Name()) + + cmd := exec.Command("osascript", "-e", script) + if err := cmd.Run(); err != nil { + return errUnavailable + } + return nil +} +func watch(ctx context.Context, t Format) <-chan []byte { + recv := make(chan []byte, 1) + ti := time.NewTicker(time.Second) + + // Get initial clipboard content + var lastContent []byte + if b := Read(t); b != nil { + lastContent = make([]byte, len(b)) + copy(lastContent, b) + } + + go func() { + defer close(recv) + defer ti.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ti.C: + b := Read(t) + if b == nil { + continue + } + + // Check if content changed + if !bytes.Equal(lastContent, b) { + recv <- b + lastContent = make([]byte, len(b)) + copy(lastContent, b) + } + } + } + }() + return recv +} diff --git a/packages/tui/internal/clipboard/clipboard_linux.go b/packages/tui/internal/clipboard/clipboard_linux.go new file mode 100644 index 00000000..e65bdcea --- /dev/null +++ b/packages/tui/internal/clipboard/clipboard_linux.go @@ -0,0 +1,297 @@ +// Copyright 2021 The golang.design Initiative Authors. +// All rights reserved. Use of this source code is governed +// by a MIT license that can be found in the LICENSE file. +// +// Written by Changkun Ou + +//go:build linux + +package clipboard + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "os/exec" + "strings" + "sync" + "time" +) + +var ( + // Clipboard tools in order of preference + clipboardTools = []struct { + name string + readCmd []string + writeCmd []string + readImg []string + writeImg []string + available bool + }{ + { + name: "xclip", + readCmd: []string{"xclip", "-selection", "clipboard", "-o"}, + writeCmd: []string{"xclip", "-selection", "clipboard"}, + readImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png", "-o"}, + writeImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png"}, + }, + { + name: "xsel", + readCmd: []string{"xsel", "--clipboard", "--output"}, + writeCmd: []string{"xsel", "--clipboard", "--input"}, + readImg: []string{"xsel", "--clipboard", "--output"}, + writeImg: []string{"xsel", "--clipboard", "--input"}, + }, + { + name: "wl-clipboard", + readCmd: []string{"wl-paste", "-n"}, + writeCmd: []string{"wl-copy"}, + readImg: []string{"wl-paste", "-t", "image/png", "-n"}, + writeImg: []string{"wl-copy", "-t", "image/png"}, + }, + } + + selectedTool int = -1 + toolMutex sync.Mutex + lastChangeTime time.Time + changeTimeMu sync.Mutex +) + +func initialize() error { + toolMutex.Lock() + defer toolMutex.Unlock() + + if selectedTool >= 0 { + return nil // Already initialized + } + + // Check which clipboard tool is available + for i, tool := range clipboardTools { + cmd := exec.Command("which", tool.name) + if err := cmd.Run(); err == nil { + clipboardTools[i].available = true + if selectedTool < 0 { + selectedTool = i + slog.Debug("Clipboard tool found", "tool", tool.name) + } + } + } + + if selectedTool < 0 { + slog.Warn("No clipboard utility found on system. Copy/paste functionality will be disabled.") + return fmt.Errorf(`%w: No clipboard utility found. Install one of the following: + +For X11 systems: + apt install -y xclip + # or + apt install -y xsel + +For Wayland systems: + apt install -y wl-clipboard + +If running in a headless environment, you may also need: + apt install -y xvfb + # and run: + Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & + export DISPLAY=:99.0`, errUnavailable) + } + + return nil +} + +func read(t Format) (buf []byte, err error) { + // Ensure clipboard is initialized before attempting to read + if err := initialize(); err != nil { + slog.Debug("Clipboard read failed: not initialized", "error", err) + return nil, err + } + + toolMutex.Lock() + tool := clipboardTools[selectedTool] + toolMutex.Unlock() + + switch t { + case FmtText: + return readText(tool) + case FmtImage: + return readImage(tool) + default: + return nil, errUnsupported + } +} + +func readText(tool struct { + name string + readCmd []string + writeCmd []string + readImg []string + writeImg []string + available bool +}) ([]byte, error) { + // First check if clipboard contains text + cmd := exec.Command(tool.readCmd[0], tool.readCmd[1:]...) + out, err := cmd.Output() + if err != nil { + // Check if it's because clipboard contains non-text data + if tool.name == "xclip" { + // xclip returns error when clipboard doesn't contain requested type + checkCmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o") + targets, _ := checkCmd.Output() + if bytes.Contains(targets, []byte("image/png")) && !bytes.Contains(targets, []byte("UTF8_STRING")) { + return nil, errUnavailable + } + } + return nil, errUnavailable + } + + return out, nil +} + +func readImage(tool struct { + name string + readCmd []string + writeCmd []string + readImg []string + writeImg []string + available bool +}) ([]byte, error) { + if tool.name == "xsel" { + // xsel doesn't support image types well, return error + return nil, errUnavailable + } + + cmd := exec.Command(tool.readImg[0], tool.readImg[1:]...) + out, err := cmd.Output() + if err != nil { + return nil, errUnavailable + } + + // Verify it's PNG data + if len(out) < 8 || !bytes.Equal(out[:8], []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) { + return nil, errUnavailable + } + + return out, nil +} + +func write(t Format, buf []byte) (<-chan struct{}, error) { + // Ensure clipboard is initialized before attempting to write + if err := initialize(); err != nil { + return nil, err + } + + toolMutex.Lock() + tool := clipboardTools[selectedTool] + toolMutex.Unlock() + + var cmd *exec.Cmd + switch t { + case FmtText: + if len(buf) == 0 { + // Write empty string + cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...) + cmd.Stdin = bytes.NewReader([]byte{}) + } else { + cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...) + cmd.Stdin = bytes.NewReader(buf) + } + case FmtImage: + if tool.name == "xsel" { + // xsel doesn't support image types well + return nil, errUnavailable + } + if len(buf) == 0 { + // Clear clipboard + cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...) + cmd.Stdin = bytes.NewReader([]byte{}) + } else { + cmd = exec.Command(tool.writeImg[0], tool.writeImg[1:]...) + cmd.Stdin = bytes.NewReader(buf) + } + default: + return nil, errUnsupported + } + + if err := cmd.Run(); err != nil { + return nil, errUnavailable + } + + // Update change time + changeTimeMu.Lock() + lastChangeTime = time.Now() + currentTime := lastChangeTime + changeTimeMu.Unlock() + + // Create change notification channel + changed := make(chan struct{}, 1) + go func() { + for { + time.Sleep(time.Second) + changeTimeMu.Lock() + if !lastChangeTime.Equal(currentTime) { + changeTimeMu.Unlock() + changed <- struct{}{} + close(changed) + return + } + changeTimeMu.Unlock() + } + }() + + return changed, nil +} + +func watch(ctx context.Context, t Format) <-chan []byte { + recv := make(chan []byte, 1) + + // Ensure clipboard is initialized before starting watch + if err := initialize(); err != nil { + close(recv) + return recv + } + + ti := time.NewTicker(time.Second) + + // Get initial clipboard content + var lastContent []byte + if b := Read(t); b != nil { + lastContent = make([]byte, len(b)) + copy(lastContent, b) + } + + go func() { + defer close(recv) + defer ti.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ti.C: + b := Read(t) + if b == nil { + continue + } + + // Check if content changed + if !bytes.Equal(lastContent, b) { + recv <- b + lastContent = make([]byte, len(b)) + copy(lastContent, b) + } + } + } + }() + return recv +} + +// Helper function to check clipboard content type for xclip +func getClipboardTargets() []string { + cmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o") + out, err := cmd.Output() + if err != nil { + return nil + } + return strings.Split(string(out), "\n") +} diff --git a/packages/tui/internal/clipboard/clipboard_nocgo.go b/packages/tui/internal/clipboard/clipboard_nocgo.go new file mode 100644 index 00000000..7b3e05f6 --- /dev/null +++ b/packages/tui/internal/clipboard/clipboard_nocgo.go @@ -0,0 +1,25 @@ +//go:build !windows && !darwin && !linux && !cgo + +package clipboard + +import "context" + +func initialize() error { + return errNoCgo +} + +func read(t Format) (buf []byte, err error) { + panic("clipboard: cannot use when CGO_ENABLED=0") +} + +func readc(t string) ([]byte, error) { + panic("clipboard: cannot use when CGO_ENABLED=0") +} + +func write(t Format, buf []byte) (<-chan struct{}, error) { + panic("clipboard: cannot use when CGO_ENABLED=0") +} + +func watch(ctx context.Context, t Format) <-chan []byte { + panic("clipboard: cannot use when CGO_ENABLED=0") +} diff --git a/packages/tui/internal/clipboard/clipboard_windows.go b/packages/tui/internal/clipboard/clipboard_windows.go new file mode 100644 index 00000000..bd042cda --- /dev/null +++ b/packages/tui/internal/clipboard/clipboard_windows.go @@ -0,0 +1,551 @@ +// Copyright 2021 The golang.design Initiative Authors. +// All rights reserved. Use of this source code is governed +// by a MIT license that can be found in the LICENSE file. +// +// Written by Changkun Ou + +//go:build windows + +package clipboard + +// Interacting with Clipboard on Windows: +// https://docs.microsoft.com/zh-cn/windows/win32/dataxchg/using-the-clipboard + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "image" + "image/color" + "image/png" + "reflect" + "runtime" + "syscall" + "time" + "unicode/utf16" + "unsafe" + + "golang.org/x/image/bmp" +) + +func initialize() error { return nil } + +// readText reads the clipboard and returns the text data if presents. +// The caller is responsible for opening/closing the clipboard before +// calling this function. +func readText() (buf []byte, err error) { + hMem, _, err := getClipboardData.Call(cFmtUnicodeText) + if hMem == 0 { + return nil, err + } + p, _, err := gLock.Call(hMem) + if p == 0 { + return nil, err + } + defer gUnlock.Call(hMem) + + // Find NUL terminator + n := 0 + for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ { + ptr = unsafe.Pointer(uintptr(ptr) + + unsafe.Sizeof(*((*uint16)(unsafe.Pointer(p))))) + } + + var s []uint16 + h := (*reflect.SliceHeader)(unsafe.Pointer(&s)) + h.Data = p + h.Len = n + h.Cap = n + return []byte(string(utf16.Decode(s))), nil +} + +// writeText writes given data to the clipboard. It is the caller's +// responsibility for opening/closing the clipboard before calling +// this function. +func writeText(buf []byte) error { + r, _, err := emptyClipboard.Call() + if r == 0 { + return fmt.Errorf("failed to clear clipboard: %w", err) + } + + // empty text, we are done here. + if len(buf) == 0 { + return nil + } + + s, err := syscall.UTF16FromString(string(buf)) + if err != nil { + return fmt.Errorf("failed to convert given string: %w", err) + } + + hMem, _, err := gAlloc.Call(gmemMoveable, uintptr(len(s)*int(unsafe.Sizeof(s[0])))) + if hMem == 0 { + return fmt.Errorf("failed to alloc global memory: %w", err) + } + + p, _, err := gLock.Call(hMem) + if p == 0 { + return fmt.Errorf("failed to lock global memory: %w", err) + } + defer gUnlock.Call(hMem) + + // no return value + memMove.Call(p, uintptr(unsafe.Pointer(&s[0])), + uintptr(len(s)*int(unsafe.Sizeof(s[0])))) + + v, _, err := setClipboardData.Call(cFmtUnicodeText, hMem) + if v == 0 { + gFree.Call(hMem) + return fmt.Errorf("failed to set text to clipboard: %w", err) + } + + return nil +} + +// readImage reads the clipboard and returns PNG encoded image data +// if presents. The caller is responsible for opening/closing the +// clipboard before calling this function. +func readImage() ([]byte, error) { + hMem, _, err := getClipboardData.Call(cFmtDIBV5) + if hMem == 0 { + // second chance to try FmtDIB + return readImageDib() + } + p, _, err := gLock.Call(hMem) + if p == 0 { + return nil, err + } + defer gUnlock.Call(hMem) + + // inspect header information + info := (*bitmapV5Header)(unsafe.Pointer(p)) + + // maybe deal with other formats? + if info.BitCount != 32 { + return nil, errUnsupported + } + + var data []byte + sh := (*reflect.SliceHeader)(unsafe.Pointer(&data)) + sh.Data = uintptr(p) + sh.Cap = int(info.Size + 4*uint32(info.Width)*uint32(info.Height)) + sh.Len = int(info.Size + 4*uint32(info.Width)*uint32(info.Height)) + img := image.NewRGBA(image.Rect(0, 0, int(info.Width), int(info.Height))) + offset := int(info.Size) + stride := int(info.Width) + for y := 0; y < int(info.Height); y++ { + for x := 0; x < int(info.Width); x++ { + idx := offset + 4*(y*stride+x) + xhat := (x + int(info.Width)) % int(info.Width) + yhat := int(info.Height) - 1 - y + r := data[idx+2] + g := data[idx+1] + b := data[idx+0] + a := data[idx+3] + img.SetRGBA(xhat, yhat, color.RGBA{r, g, b, a}) + } + } + // always use PNG encoding. + var buf bytes.Buffer + png.Encode(&buf, img) + return buf.Bytes(), nil +} + +func readImageDib() ([]byte, error) { + const ( + fileHeaderLen = 14 + infoHeaderLen = 40 + cFmtDIB = 8 + ) + + hClipDat, _, err := getClipboardData.Call(cFmtDIB) + if err != nil { + return nil, errors.New("not dib format data: " + err.Error()) + } + pMemBlk, _, err := gLock.Call(hClipDat) + if pMemBlk == 0 { + return nil, errors.New("failed to call global lock: " + err.Error()) + } + defer gUnlock.Call(hClipDat) + + bmpHeader := (*bitmapHeader)(unsafe.Pointer(pMemBlk)) + dataSize := bmpHeader.SizeImage + fileHeaderLen + infoHeaderLen + + if bmpHeader.SizeImage == 0 && bmpHeader.Compression == 0 { + iSizeImage := bmpHeader.Height * ((bmpHeader.Width*uint32(bmpHeader.BitCount)/8 + 3) &^ 3) + dataSize += iSizeImage + } + buf := new(bytes.Buffer) + binary.Write(buf, binary.LittleEndian, uint16('B')|(uint16('M')<<8)) + binary.Write(buf, binary.LittleEndian, uint32(dataSize)) + binary.Write(buf, binary.LittleEndian, uint32(0)) + const sizeof_colorbar = 0 + binary.Write(buf, binary.LittleEndian, uint32(fileHeaderLen+infoHeaderLen+sizeof_colorbar)) + j := 0 + for i := fileHeaderLen; i < int(dataSize); i++ { + binary.Write(buf, binary.BigEndian, *(*byte)(unsafe.Pointer(pMemBlk + uintptr(j)))) + j++ + } + return bmpToPng(buf) +} + +func bmpToPng(bmpBuf *bytes.Buffer) (buf []byte, err error) { + var f bytes.Buffer + original_image, err := bmp.Decode(bmpBuf) + if err != nil { + return nil, err + } + err = png.Encode(&f, original_image) + if err != nil { + return nil, err + } + return f.Bytes(), nil +} + +func writeImage(buf []byte) error { + r, _, err := emptyClipboard.Call() + if r == 0 { + return fmt.Errorf("failed to clear clipboard: %w", err) + } + + // empty text, we are done here. + if len(buf) == 0 { + return nil + } + + img, err := png.Decode(bytes.NewReader(buf)) + if err != nil { + return fmt.Errorf("input bytes is not PNG encoded: %w", err) + } + + offset := unsafe.Sizeof(bitmapV5Header{}) + width := img.Bounds().Dx() + height := img.Bounds().Dy() + imageSize := 4 * width * height + + data := make([]byte, int(offset)+imageSize) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + idx := int(offset) + 4*(y*width+x) + r, g, b, a := img.At(x, height-1-y).RGBA() + data[idx+2] = uint8(r) + data[idx+1] = uint8(g) + data[idx+0] = uint8(b) + data[idx+3] = uint8(a) + } + } + + info := bitmapV5Header{} + info.Size = uint32(offset) + info.Width = int32(width) + info.Height = int32(height) + info.Planes = 1 + info.Compression = 0 // BI_RGB + info.SizeImage = uint32(4 * info.Width * info.Height) + info.RedMask = 0xff0000 // default mask + info.GreenMask = 0xff00 + info.BlueMask = 0xff + info.AlphaMask = 0xff000000 + info.BitCount = 32 // we only deal with 32 bpp at the moment. + // Use calibrated RGB values as Go's image/png assumes linear color space. + // Other options: + // - LCS_CALIBRATED_RGB = 0x00000000 + // - LCS_sRGB = 0x73524742 + // - LCS_WINDOWS_COLOR_SPACE = 0x57696E20 + // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/eb4bbd50-b3ce-4917-895c-be31f214797f + info.CSType = 0x73524742 + // Use GL_IMAGES for GamutMappingIntent + // Other options: + // - LCS_GM_ABS_COLORIMETRIC = 0x00000008 + // - LCS_GM_BUSINESS = 0x00000001 + // - LCS_GM_GRAPHICS = 0x00000002 + // - LCS_GM_IMAGES = 0x00000004 + // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/9fec0834-607d-427d-abd5-ab240fb0db38 + info.Intent = 4 // LCS_GM_IMAGES + + infob := make([]byte, int(unsafe.Sizeof(info))) + for i, v := range *(*[unsafe.Sizeof(info)]byte)(unsafe.Pointer(&info)) { + infob[i] = v + } + copy(data[:], infob[:]) + + hMem, _, err := gAlloc.Call(gmemMoveable, + uintptr(len(data)*int(unsafe.Sizeof(data[0])))) + if hMem == 0 { + return fmt.Errorf("failed to alloc global memory: %w", err) + } + + p, _, err := gLock.Call(hMem) + if p == 0 { + return fmt.Errorf("failed to lock global memory: %w", err) + } + defer gUnlock.Call(hMem) + + memMove.Call(p, uintptr(unsafe.Pointer(&data[0])), + uintptr(len(data)*int(unsafe.Sizeof(data[0])))) + + v, _, err := setClipboardData.Call(cFmtDIBV5, hMem) + if v == 0 { + gFree.Call(hMem) + return fmt.Errorf("failed to set text to clipboard: %w", err) + } + + return nil +} + +func read(t Format) (buf []byte, err error) { + // On Windows, OpenClipboard and CloseClipboard must be executed on + // the same thread. Thus, lock the OS thread for further execution. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + var format uintptr + switch t { + case FmtImage: + format = cFmtDIBV5 + case FmtText: + fallthrough + default: + format = cFmtUnicodeText + } + + // check if clipboard is avaliable for the requested format + r, _, err := isClipboardFormatAvailable.Call(format) + if r == 0 { + return nil, errUnavailable + } + + // try again until open clipboard successed + for { + r, _, _ = openClipboard.Call() + if r == 0 { + continue + } + break + } + defer closeClipboard.Call() + + switch format { + case cFmtDIBV5: + return readImage() + case cFmtUnicodeText: + fallthrough + default: + return readText() + } +} + +// write writes the given data to clipboard and +// returns true if success or false if failed. +func write(t Format, buf []byte) (<-chan struct{}, error) { + errch := make(chan error) + changed := make(chan struct{}, 1) + go func() { + // make sure GetClipboardSequenceNumber happens with + // OpenClipboard on the same thread. + runtime.LockOSThread() + defer runtime.UnlockOSThread() + for { + r, _, _ := openClipboard.Call(0) + if r == 0 { + continue + } + break + } + + // var param uintptr + switch t { + case FmtImage: + err := writeImage(buf) + if err != nil { + errch <- err + closeClipboard.Call() + return + } + case FmtText: + fallthrough + default: + // param = cFmtUnicodeText + err := writeText(buf) + if err != nil { + errch <- err + closeClipboard.Call() + return + } + } + // Close the clipboard otherwise other applications cannot + // paste the data. + closeClipboard.Call() + + cnt, _, _ := getClipboardSequenceNumber.Call() + errch <- nil + for { + time.Sleep(time.Second) + cur, _, _ := getClipboardSequenceNumber.Call() + if cur != cnt { + changed <- struct{}{} + close(changed) + return + } + } + }() + err := <-errch + if err != nil { + return nil, err + } + return changed, nil +} + +func watch(ctx context.Context, t Format) <-chan []byte { + recv := make(chan []byte, 1) + ready := make(chan struct{}) + go func() { + // not sure if we are too slow or the user too fast :) + ti := time.NewTicker(time.Second) + cnt, _, _ := getClipboardSequenceNumber.Call() + ready <- struct{}{} + for { + select { + case <-ctx.Done(): + close(recv) + return + case <-ti.C: + cur, _, _ := getClipboardSequenceNumber.Call() + if cnt != cur { + b := Read(t) + if b == nil { + continue + } + recv <- b + cnt = cur + } + } + } + }() + <-ready + return recv +} + +const ( + cFmtBitmap = 2 // Win+PrintScreen + cFmtUnicodeText = 13 + cFmtDIBV5 = 17 + // Screenshot taken from special shortcut is in different format (why??), see: + // https://jpsoft.com/forums/threads/detecting-clipboard-format.5225/ + cFmtDataObject = 49161 // Shift+Win+s, returned from enumClipboardFormats + gmemMoveable = 0x0002 +) + +// BITMAPV5Header structure, see: +// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapv5header +type bitmapV5Header struct { + Size uint32 + Width int32 + Height int32 + Planes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter int32 + YPelsPerMeter int32 + ClrUsed uint32 + ClrImportant uint32 + RedMask uint32 + GreenMask uint32 + BlueMask uint32 + AlphaMask uint32 + CSType uint32 + Endpoints struct { + CiexyzRed, CiexyzGreen, CiexyzBlue struct { + CiexyzX, CiexyzY, CiexyzZ int32 // FXPT2DOT30 + } + } + GammaRed uint32 + GammaGreen uint32 + GammaBlue uint32 + Intent uint32 + ProfileData uint32 + ProfileSize uint32 + Reserved uint32 +} + +type bitmapHeader struct { + Size uint32 + Width uint32 + Height uint32 + PLanes uint16 + BitCount uint16 + Compression uint32 + SizeImage uint32 + XPelsPerMeter uint32 + YPelsPerMeter uint32 + ClrUsed uint32 + ClrImportant uint32 +} + +// Calling a Windows DLL, see: +// https://github.com/golang/go/wiki/WindowsDLLs +var ( + user32 = syscall.MustLoadDLL("user32") + // Opens the clipboard for examination and prevents other + // applications from modifying the clipboard content. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-openclipboard + openClipboard = user32.MustFindProc("OpenClipboard") + // Closes the clipboard. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-closeclipboard + closeClipboard = user32.MustFindProc("CloseClipboard") + // Empties the clipboard and frees handles to data in the clipboard. + // The function then assigns ownership of the clipboard to the + // window that currently has the clipboard open. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-emptyclipboard + emptyClipboard = user32.MustFindProc("EmptyClipboard") + // Retrieves data from the clipboard in a specified format. + // The clipboard must have been opened previously. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclipboarddata + getClipboardData = user32.MustFindProc("GetClipboardData") + // Places data on the clipboard in a specified clipboard format. + // The window must be the current clipboard owner, and the + // application must have called the OpenClipboard function. (When + // responding to the WM_RENDERFORMAT message, the clipboard owner + // must not call OpenClipboard before calling SetClipboardData.) + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setclipboarddata + setClipboardData = user32.MustFindProc("SetClipboardData") + // Determines whether the clipboard contains data in the specified format. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-isclipboardformatavailable + isClipboardFormatAvailable = user32.MustFindProc("IsClipboardFormatAvailable") + // Clipboard data formats are stored in an ordered list. To perform + // an enumeration of clipboard data formats, you make a series of + // calls to the EnumClipboardFormats function. For each call, the + // format parameter specifies an available clipboard format, and the + // function returns the next available clipboard format. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-isclipboardformatavailable + enumClipboardFormats = user32.MustFindProc("EnumClipboardFormats") + // Retrieves the clipboard sequence number for the current window station. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclipboardsequencenumber + getClipboardSequenceNumber = user32.MustFindProc("GetClipboardSequenceNumber") + // Registers a new clipboard format. This format can then be used as + // a valid clipboard format. + // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclipboardformata + registerClipboardFormatA = user32.MustFindProc("RegisterClipboardFormatA") + + kernel32 = syscall.NewLazyDLL("kernel32") + + // Locks a global memory object and returns a pointer to the first + // byte of the object's memory block. + // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globallock + gLock = kernel32.NewProc("GlobalLock") + // Decrements the lock count associated with a memory object that was + // allocated with GMEM_MOVEABLE. This function has no effect on memory + // objects allocated with GMEM_FIXED. + // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalunlock + gUnlock = kernel32.NewProc("GlobalUnlock") + // Allocates the specified number of bytes from the heap. + // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalalloc + gAlloc = kernel32.NewProc("GlobalAlloc") + // Frees the specified global memory object and invalidates its handle. + // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalfree + gFree = kernel32.NewProc("GlobalFree") + memMove = kernel32.NewProc("RtlMoveMemory") +) diff --git a/packages/tui/internal/commands/command.go b/packages/tui/internal/commands/command.go index 9c4da12e..791f7475 100644 --- a/packages/tui/internal/commands/command.go +++ b/packages/tui/internal/commands/command.go @@ -29,7 +29,7 @@ type Command struct { Name CommandName Description string Keybindings []Keybinding - Trigger string + Trigger []string } func (c Command) Keys() []string { @@ -40,6 +40,21 @@ func (c Command) Keys() []string { return keys } +func (c Command) HasTrigger() bool { + return len(c.Trigger) > 0 +} + +func (c Command) PrimaryTrigger() string { + if len(c.Trigger) > 0 { + return c.Trigger[0] + } + return "" +} + +func (c Command) MatchesTrigger(trigger string) bool { + return slices.Contains(c.Trigger, trigger) +} + type CommandRegistry map[CommandName]Command func (r CommandRegistry) Sorted() []Command { @@ -135,37 +150,37 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry { Name: AppHelpCommand, Description: "show help", Keybindings: parseBindings("h"), - Trigger: "help", + Trigger: []string{"help"}, }, { Name: EditorOpenCommand, Description: "open editor", Keybindings: parseBindings("e"), - Trigger: "editor", + Trigger: []string{"editor"}, }, { Name: SessionNewCommand, Description: "new session", Keybindings: parseBindings("n"), - Trigger: "new", + Trigger: []string{"new", "clear"}, }, { Name: SessionListCommand, Description: "list sessions", Keybindings: parseBindings("l"), - Trigger: "sessions", + Trigger: []string{"sessions", "resume", "continue"}, }, { Name: SessionShareCommand, Description: "share session", Keybindings: parseBindings("s"), - Trigger: "share", + Trigger: []string{"share"}, }, { Name: SessionUnshareCommand, Description: "unshare session", Keybindings: parseBindings("u"), - Trigger: "unshare", + Trigger: []string{"unshare"}, }, { Name: SessionInterruptCommand, @@ -176,31 +191,31 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry { Name: SessionCompactCommand, Description: "compact the session", Keybindings: parseBindings("c"), - Trigger: "compact", + Trigger: []string{"compact", "summarize"}, }, { Name: ToolDetailsCommand, Description: "toggle tool details", Keybindings: parseBindings("d"), - Trigger: "details", + Trigger: []string{"details"}, }, { Name: ModelListCommand, Description: "list models", Keybindings: parseBindings("m"), - Trigger: "models", + Trigger: []string{"models"}, }, { Name: ThemeListCommand, Description: "list themes", Keybindings: parseBindings("t"), - Trigger: "themes", + Trigger: []string{"themes"}, }, { Name: FileListCommand, Description: "list files", Keybindings: parseBindings("f"), - Trigger: "files", + Trigger: []string{"files"}, }, { Name: FileCloseCommand, @@ -221,7 +236,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry { Name: ProjectInitCommand, Description: "create/update AGENTS.md", Keybindings: parseBindings("i"), - Trigger: "init", + Trigger: []string{"init"}, }, { Name: InputClearCommand, @@ -231,7 +246,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry { { Name: InputPasteCommand, Description: "paste content", - Keybindings: parseBindings("ctrl+v"), + Keybindings: parseBindings("ctrl+v", "super+v"), }, { Name: InputSubmitCommand, @@ -302,7 +317,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry { Name: AppExitCommand, Description: "exit the app", Keybindings: parseBindings("ctrl+c", "q"), - Trigger: "exit", + Trigger: []string{"exit", "quit"}, }, } registry := make(CommandRegistry) diff --git a/packages/tui/internal/completions/commands.go b/packages/tui/internal/completions/commands.go index c73923e8..3a5dc3bb 100644 --- a/packages/tui/internal/completions/commands.go +++ b/packages/tui/internal/completions/commands.go @@ -31,7 +31,7 @@ func (c *CommandCompletionProvider) GetEmptyMessage() string { func getCommandCompletionItem(cmd commands.Command, space int, t theme.Theme) dialog.CompletionItemI { spacer := strings.Repeat(" ", space) - title := " /" + cmd.Trigger + styles.NewStyle().Foreground(t.TextMuted()).Render(spacer+cmd.Description) + title := " /" + cmd.PrimaryTrigger() + styles.NewStyle().Foreground(t.TextMuted()).Render(spacer+cmd.Description) value := string(cmd.Name) return dialog.NewCompletionItem(dialog.CompletionItem{ Title: title, @@ -45,8 +45,8 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp space := 1 for _, cmd := range c.app.Commands { - if lipgloss.Width(cmd.Trigger) > space { - space = lipgloss.Width(cmd.Trigger) + if cmd.HasTrigger() && lipgloss.Width(cmd.PrimaryTrigger()) > space { + space = lipgloss.Width(cmd.PrimaryTrigger()) } } space += 2 @@ -56,10 +56,10 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp // If no query, return all commands items := []dialog.CompletionItemI{} for _, cmd := range sorted { - if cmd.Trigger == "" { + if !cmd.HasTrigger() { continue } - space := space - lipgloss.Width(cmd.Trigger) + space := space - lipgloss.Width(cmd.PrimaryTrigger()) items = append(items, getCommandCompletionItem(cmd, space, t)) } return items, nil @@ -70,12 +70,15 @@ func (c *CommandCompletionProvider) GetChildEntries(query string) ([]dialog.Comp commandMap := make(map[string]dialog.CompletionItemI) for _, cmd := range sorted { - if cmd.Trigger == "" { + if !cmd.HasTrigger() { continue } - space := space - lipgloss.Width(cmd.Trigger) - commandNames = append(commandNames, cmd.Trigger) - commandMap[cmd.Trigger] = getCommandCompletionItem(cmd, space, t) + space := space - lipgloss.Width(cmd.PrimaryTrigger()) + // Add all triggers as searchable options + for _, trigger := range cmd.Trigger { + commandNames = append(commandNames, trigger) + commandMap[trigger] = getCommandCompletionItem(cmd, space, t) + } } // Find fuzzy matches diff --git a/packages/tui/internal/completions/files-folders.go b/packages/tui/internal/completions/files-folders.go index ec298af9..55e0c1a1 100644 --- a/packages/tui/internal/completions/files-folders.go +++ b/packages/tui/internal/completions/files-folders.go @@ -42,7 +42,7 @@ func (cg *filesAndFoldersContextGroup) getGitFiles() []dialog.CompletionItemI { }) for _, file := range files { - title := file.File + title := file.Path if file.Added > 0 { title += green(" +" + strconv.Itoa(int(file.Added))) } @@ -51,7 +51,7 @@ func (cg *filesAndFoldersContextGroup) getGitFiles() []dialog.CompletionItemI { } item := dialog.NewCompletionItem(dialog.CompletionItem{ Title: title, - Value: file.File, + Value: file.Path, }) items = append(items, item) } diff --git a/packages/tui/internal/components/chat/editor.go b/packages/tui/internal/components/chat/editor.go index 9466d541..6053c9c0 100644 --- a/packages/tui/internal/components/chat/editor.go +++ b/packages/tui/internal/components/chat/editor.go @@ -1,9 +1,12 @@ package chat import ( + "encoding/base64" "fmt" "log/slog" + "os" "path/filepath" + "strconv" "strings" "github.com/charmbracelet/bubbles/v2/spinner" @@ -12,10 +15,10 @@ import ( "github.com/google/uuid" "github.com/sst/opencode-sdk-go" "github.com/sst/opencode/internal/app" + "github.com/sst/opencode/internal/clipboard" "github.com/sst/opencode/internal/commands" "github.com/sst/opencode/internal/components/dialog" "github.com/sst/opencode/internal/components/textarea" - "github.com/sst/opencode/internal/image" "github.com/sst/opencode/internal/styles" "github.com/sst/opencode/internal/theme" "github.com/sst/opencode/internal/util" @@ -27,6 +30,7 @@ type EditorComponent interface { Content(width int) string Lines() int Value() string + Length() int Focused() bool Focus() (tea.Model, tea.Cmd) Blur() @@ -35,6 +39,7 @@ type EditorComponent interface { Paste() (tea.Model, tea.Cmd) Newline() (tea.Model, tea.Cmd) SetInterruptKeyInDebounce(inDebounce bool) + SetExitKeyInDebounce(inDebounce bool) } type editorComponent struct { @@ -42,6 +47,7 @@ type editorComponent struct { textarea textarea.Model spinner spinner.Model interruptKeyInDebounce bool + exitKeyInDebounce bool } func (m *editorComponent) Init() tea.Cmd { @@ -63,8 +69,65 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) { cmds = append(cmds, cmd) return m, tea.Batch(cmds...) } + case tea.PasteMsg: + text := string(msg) + text = strings.ReplaceAll(text, "\\", "") + text, err := strconv.Unquote(`"` + text + `"`) + if err != nil { + slog.Error("Failed to unquote text", "error", err) + m.textarea.InsertRunesFromUserInput([]rune(msg)) + return m, nil + } + if _, err := os.Stat(text); err != nil { + slog.Error("Failed to paste file", "error", err) + m.textarea.InsertRunesFromUserInput([]rune(msg)) + return m, nil + } + + filePath := text + ext := strings.ToLower(filepath.Ext(filePath)) + + mediaType := "" + switch ext { + case ".jpg": + mediaType = "image/jpeg" + case ".png", ".jpeg", ".gif", ".webp": + mediaType = "image/" + ext[1:] + case ".pdf": + mediaType = "application/pdf" + default: + mediaType = "text/plain" + } + + fileBytes, err := os.ReadFile(filePath) + if err != nil { + slog.Error("Failed to read file", "error", err) + m.textarea.InsertRunesFromUserInput([]rune(msg)) + return m, nil + } + base64EncodedFile := base64.StdEncoding.EncodeToString(fileBytes) + url := fmt.Sprintf("data:%s;base64,%s", mediaType, base64EncodedFile) + attachmentCount := len(m.textarea.GetAttachments()) + attachmentIndex := attachmentCount + 1 + label := "File" + if strings.HasPrefix(mediaType, "image/") { + label = "Image" + } + + attachment := &textarea.Attachment{ + ID: uuid.NewString(), + MediaType: mediaType, + Display: fmt.Sprintf("[%s #%d]", label, attachmentIndex), + URL: url, + Filename: filePath, + } + m.textarea.InsertAttachment(attachment) + m.textarea.InsertString(" ") + case tea.ClipboardMsg: + text := string(msg) + m.textarea.InsertRunesFromUserInput([]rune(text)) case dialog.ThemeSelectedMsg: - m.textarea = createTextArea(&m.textarea) + m.textarea = m.resetTextareaStyles() m.spinner = createSpinner() return m, tea.Batch(m.spinner.Tick, m.textarea.Focus()) case dialog.CompletionSelectedMsg: @@ -164,7 +227,10 @@ func (m *editorComponent) Content(width int) string { Render(textarea) hint := base(m.getSubmitKeyText()) + muted(" send ") - if m.app.IsBusy() { + if m.exitKeyInDebounce { + keyText := m.getExitKeyText() + hint = base(keyText+" again") + muted(" to exit") + } else if m.app.IsBusy() { keyText := m.getInterruptKeyText() if m.interruptKeyInDebounce { hint = muted( @@ -230,6 +296,10 @@ func (m *editorComponent) Value() string { return m.textarea.Value() } +func (m *editorComponent) Length() int { + return m.textarea.Length() +} + func (m *editorComponent) Submit() (tea.Model, tea.Cmd) { value := strings.TrimSpace(m.Value()) if value == "" { @@ -248,10 +318,10 @@ func (m *editorComponent) Submit() (tea.Model, tea.Cmd) { fileParts := make([]opencode.FilePartParam, 0) for _, attachment := range attachments { fileParts = append(fileParts, opencode.FilePartParam{ - Type: opencode.F(opencode.FilePartTypeFile), - MediaType: opencode.F(attachment.MediaType), - URL: opencode.F(attachment.URL), - Filename: opencode.F(attachment.Filename), + Type: opencode.F(opencode.FilePartTypeFile), + Mime: opencode.F(attachment.MediaType), + URL: opencode.F(attachment.URL), + Filename: opencode.F(attachment.Filename), }) } @@ -269,24 +339,31 @@ func (m *editorComponent) Clear() (tea.Model, tea.Cmd) { } func (m *editorComponent) Paste() (tea.Model, tea.Cmd) { - _, text, err := image.GetImageFromClipboard() - if err != nil { - slog.Error(err.Error()) + imageBytes := clipboard.Read(clipboard.FmtImage) + if imageBytes != nil { + attachmentCount := len(m.textarea.GetAttachments()) + attachmentIndex := attachmentCount + 1 + base64EncodedFile := base64.StdEncoding.EncodeToString(imageBytes) + attachment := &textarea.Attachment{ + ID: uuid.NewString(), + MediaType: "image/png", + Display: fmt.Sprintf("[Image #%d]", attachmentIndex), + Filename: fmt.Sprintf("image-%d.png", attachmentIndex), + URL: fmt.Sprintf("data:image/png;base64,%s", base64EncodedFile), + } + m.textarea.InsertAttachment(attachment) + m.textarea.InsertString(" ") return m, nil } - // if len(imageBytes) != 0 { - // attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments)) - // attachment := app.Attachment{ - // FilePath: attachmentName, - // FileName: attachmentName, - // Content: imageBytes, - // MimeType: "image/png", - // } - // m.attachments = append(m.attachments, attachment) - // } else { - m.textarea.InsertString(text) - // } - return m, nil + + textBytes := clipboard.Read(clipboard.FmtText) + if textBytes != nil { + m.textarea.InsertRunesFromUserInput([]rune(string(textBytes))) + return m, nil + } + + // fallback to reading the clipboard using OSC52 + return m, tea.ReadClipboard } func (m *editorComponent) Newline() (tea.Model, tea.Cmd) { @@ -298,6 +375,10 @@ func (m *editorComponent) SetInterruptKeyInDebounce(inDebounce bool) { m.interruptKeyInDebounce = inDebounce } +func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) { + m.exitKeyInDebounce = inDebounce +} + func (m *editorComponent) getInterruptKeyText() string { return m.app.Commands[commands.SessionInterruptCommand].Keys()[0] } @@ -306,13 +387,17 @@ func (m *editorComponent) getSubmitKeyText() string { return m.app.Commands[commands.InputSubmitCommand].Keys()[0] } -func createTextArea(existing *textarea.Model) textarea.Model { +func (m *editorComponent) getExitKeyText() string { + return m.app.Commands[commands.AppExitCommand].Keys()[0] +} + +func (m *editorComponent) resetTextareaStyles() textarea.Model { t := theme.CurrentTheme() bgColor := t.BackgroundElement() textColor := t.Text() textMutedColor := t.TextMuted() - ta := textarea.New() + ta := m.textarea ta.Styles.Blurred.Base = styles.NewStyle().Foreground(textColor).Background(bgColor).Lipgloss() ta.Styles.Blurred.CursorLine = styles.NewStyle().Background(bgColor).Lipgloss() @@ -337,17 +422,6 @@ func createTextArea(existing *textarea.Model) textarea.Model { Background(t.Secondary()). Lipgloss() ta.Styles.Cursor.Color = t.Primary() - - ta.Prompt = " " - ta.ShowLineNumbers = false - ta.CharLimit = -1 - - if existing != nil { - ta.SetValue(existing.Value()) - // ta.SetWidth(existing.Width()) - ta.SetHeight(existing.Height()) - } - return ta } @@ -367,12 +441,19 @@ func createSpinner() spinner.Model { func NewEditorComponent(app *app.App) EditorComponent { s := createSpinner() - ta := createTextArea(nil) - return &editorComponent{ + ta := textarea.New() + ta.Prompt = " " + ta.ShowLineNumbers = false + ta.CharLimit = -1 + + m := &editorComponent{ app: app, textarea: ta, spinner: s, interruptKeyInDebounce: false, } + m.resetTextareaStyles() + + return m } diff --git a/packages/tui/internal/components/chat/message.go b/packages/tui/internal/components/chat/message.go index 9e245c8b..4f3bfdfa 100644 --- a/packages/tui/internal/components/chat/message.go +++ b/packages/tui/internal/components/chat/message.go @@ -17,7 +17,6 @@ import ( "github.com/sst/opencode/internal/styles" "github.com/sst/opencode/internal/theme" "github.com/sst/opencode/internal/util" - "github.com/tidwall/gjson" "golang.org/x/text/cases" "golang.org/x/text/language" ) @@ -135,7 +134,6 @@ func renderContentBlock( style := styles.NewStyle(). Foreground(renderer.textColor). Background(t.BackgroundPanel()). - Width(width). PaddingTop(renderer.paddingTop). PaddingBottom(renderer.paddingBottom). PaddingLeft(renderer.paddingLeft). @@ -217,18 +215,34 @@ func renderContentBlock( func renderText( app *app.App, - message opencode.Message, + message opencode.MessageUnion, text string, author string, showToolDetails bool, highlight bool, width int, extra string, - toolCalls ...opencode.ToolInvocationPart, + toolCalls ...opencode.ToolPart, ) string { t := theme.CurrentTheme() - timestamp := time.UnixMilli(int64(message.Metadata.Time.Created)). + var ts time.Time + backgroundColor := t.BackgroundPanel() + if highlight { + backgroundColor = t.BackgroundElement() + } + var content string + switch casted := message.(type) { + case opencode.AssistantMessage: + ts = time.UnixMilli(int64(casted.Time.Created)) + content = util.ToMarkdown(text, width, backgroundColor) + case opencode.UserMessage: + ts = time.UnixMilli(int64(casted.Time.Created)) + messageStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6) + content = messageStyle.Render(text) + } + + timestamp := ts. Local(). Format("02 Jan 2006 03:04 PM") if time.Now().Format("02 Jan 2006") == timestamp[:11] { @@ -238,30 +252,12 @@ func renderText( info := fmt.Sprintf("%s (%s)", author, timestamp) info = styles.NewStyle().Foreground(t.TextMuted()).Render(info) - backgroundColor := t.BackgroundPanel() - if highlight { - backgroundColor = t.BackgroundElement() - } - messageStyle := styles.NewStyle().Background(backgroundColor) - if message.Role == opencode.MessageRoleUser { - messageStyle = messageStyle.Width(width - 6) - } - - content := messageStyle.Render(text) - if message.Role == opencode.MessageRoleAssistant { - content = util.ToMarkdown(text, width, backgroundColor) - } - if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 { content = content + "\n\n" for _, toolCall := range toolCalls { - title := renderToolTitle(toolCall, message.Metadata, width) - metadata := opencode.MessageMetadataTool{} - if _, ok := message.Metadata.Tool[toolCall.ToolInvocation.ToolCallID]; ok { - metadata = message.Metadata.Tool[toolCall.ToolInvocation.ToolCallID] - } + title := renderToolTitle(toolCall, width) style := styles.NewStyle() - if _, ok := metadata.ExtraFields["error"]; ok { + if toolCall.State.Status == opencode.ToolPartStateStatusError { style = style.Foreground(t.Error()) } title = style.Render(title) @@ -276,8 +272,8 @@ func renderText( } content = strings.Join(sections, "\n") - switch message.Role { - case opencode.MessageRoleUser: + switch message.(type) { + case opencode.UserMessage: return renderContentBlock( app, content, @@ -286,7 +282,7 @@ func renderText( WithTextColor(t.Text()), WithBorderColorRight(t.Secondary()), ) - case opencode.MessageRoleAssistant: + case opencode.AssistantMessage: return renderContentBlock( app, content, @@ -300,39 +296,34 @@ func renderText( func renderToolDetails( app *app.App, - toolCall opencode.ToolInvocationPart, - messageMetadata opencode.MessageMetadata, + toolCall opencode.ToolPart, highlight bool, width int, ) string { ignoredTools := []string{"todoread"} - if slices.Contains(ignoredTools, toolCall.ToolInvocation.ToolName) { + if slices.Contains(ignoredTools, toolCall.Tool) { return "" } - toolCallID := toolCall.ToolInvocation.ToolCallID - metadata := opencode.MessageMetadataTool{} - if _, ok := messageMetadata.Tool[toolCallID]; ok { - metadata = messageMetadata.Tool[toolCallID] - } - - var result *string - if toolCall.ToolInvocation.Result != "" { - result = &toolCall.ToolInvocation.Result - } - - if toolCall.ToolInvocation.State == "partial-call" { - title := renderToolTitle(toolCall, messageMetadata, width) + if toolCall.State.Status == opencode.ToolPartStateStatusPending || + toolCall.State.Status == opencode.ToolPartStateStatusRunning { + title := renderToolTitle(toolCall, width) + title = styles.NewStyle().Width(width - 6).Render(title) return renderContentBlock(app, title, highlight, width) } - toolArgsMap := make(map[string]any) - if toolCall.ToolInvocation.Args != nil { - value := toolCall.ToolInvocation.Args + var result *string + if toolCall.State.Output != "" { + result = &toolCall.State.Output + } + + toolInputMap := make(map[string]any) + if toolCall.State.Input != nil { + value := toolCall.State.Input if m, ok := value.(map[string]any); ok { - toolArgsMap = m - keys := make([]string, 0, len(toolArgsMap)) - for key := range toolArgsMap { + toolInputMap = m + keys := make([]string, 0, len(toolInputMap)) + for key := range toolInputMap { keys = append(keys, key) } slices.Sort(keys) @@ -340,7 +331,6 @@ func renderToolDetails( } body := "" - finished := result != nil && *result != "" t := theme.CurrentTheme() backgroundColor := t.BackgroundPanel() borderColor := t.BackgroundPanel() @@ -349,141 +339,136 @@ func renderToolDetails( borderColor = t.BorderActive() } - switch toolCall.ToolInvocation.ToolName { - case "read": - preview := metadata.ExtraFields["preview"] - if preview != nil && toolArgsMap["filePath"] != nil { - filename := toolArgsMap["filePath"].(string) - body = preview.(string) - body = util.RenderFile(filename, body, width, util.WithTruncate(6)) - } - case "edit": - if filename, ok := toolArgsMap["filePath"].(string); ok { - diffField := metadata.ExtraFields["diff"] - if diffField != nil { - patch := diffField.(string) - var formattedDiff string - formattedDiff, _ = diff.FormatUnifiedDiff( - filename, - patch, - diff.WithWidth(width-2), - ) - body = strings.TrimSpace(formattedDiff) - style := styles.NewStyle(). - Background(backgroundColor). - Foreground(t.TextMuted()). - Padding(1, 2). - Width(width - 4) - if highlight { - style = style.Foreground(t.Text()).Bold(true) - } - - if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" { - diagnostics = style.Render(diagnostics) - body += "\n" + diagnostics - } - - title := renderToolTitle(toolCall, messageMetadata, width) - title = style.Render(title) - content := title + "\n" + body - content = renderContentBlock( - app, - content, - highlight, - width, - WithPadding(0), - WithBorderColor(borderColor), - ) - return content + if toolCall.State.Status == opencode.ToolPartStateStatusCompleted { + metadata := toolCall.State.Metadata.(map[string]any) + switch toolCall.Tool { + case "read": + preview := metadata["preview"] + if preview != nil && toolInputMap["filePath"] != nil { + filename := toolInputMap["filePath"].(string) + body = preview.(string) + body = util.RenderFile(filename, body, width, util.WithTruncate(6)) } - } - case "write": - if filename, ok := toolArgsMap["filePath"].(string); ok { - if content, ok := toolArgsMap["content"].(string); ok { - body = util.RenderFile(filename, content, width) - if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" { - body += "\n\n" + diagnostics + case "edit": + if filename, ok := toolInputMap["filePath"].(string); ok { + diffField := metadata["diff"] + if diffField != nil { + patch := diffField.(string) + var formattedDiff string + formattedDiff, _ = diff.FormatUnifiedDiff( + filename, + patch, + diff.WithWidth(width-2), + ) + body = strings.TrimSpace(formattedDiff) + style := styles.NewStyle(). + Background(backgroundColor). + Foreground(t.TextMuted()). + Padding(1, 2). + Width(width - 4) + if highlight { + style = style.Foreground(t.Text()).Bold(true) + } + + if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" { + diagnostics = style.Render(diagnostics) + body += "\n" + diagnostics + } + + title := renderToolTitle(toolCall, width) + title = style.Render(title) + content := title + "\n" + body + content = renderContentBlock( + app, + content, + highlight, + width, + WithPadding(0), + WithBorderColor(borderColor), + ) + return content } } - } - case "bash": - stdout := metadata.ExtraFields["stdout"] - if stdout != nil { - command := toolArgsMap["command"].(string) - body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout) - body = util.ToMarkdown(body, width, backgroundColor) - } - case "webfetch": - if format, ok := toolArgsMap["format"].(string); ok && result != nil { - body = *result - body = util.TruncateHeight(body, 10) - if format == "html" || format == "markdown" { + case "write": + if filename, ok := toolInputMap["filePath"].(string); ok { + if content, ok := toolInputMap["content"].(string); ok { + body = util.RenderFile(filename, content, width) + if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" { + body += "\n\n" + diagnostics + } + } + } + case "bash": + stdout := metadata["stdout"] + if stdout != nil { + command := toolInputMap["command"].(string) + body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout) body = util.ToMarkdown(body, width, backgroundColor) } - } - case "todowrite": - todos := metadata.JSON.ExtraFields["todos"] - if !todos.IsNull() && finished { - strTodos := todos.Raw() - todos := gjson.Parse(strTodos) - for _, todo := range todos.Array() { - content := todo.Get("content").String() - switch todo.Get("status").String() { - case "completed": - body += fmt.Sprintf("- [x] %s\n", content) - // case "in-progress": - // body += fmt.Sprintf("- [ ] %s\n", content) - default: - body += fmt.Sprintf("- [ ] %s\n", content) + case "webfetch": + if format, ok := toolInputMap["format"].(string); ok && result != nil { + body = *result + body = util.TruncateHeight(body, 10) + if format == "html" || format == "markdown" { + body = util.ToMarkdown(body, width, backgroundColor) } } - body = util.ToMarkdown(body, width, backgroundColor) - } - case "task": - summary := metadata.JSON.ExtraFields["summary"] - if !summary.IsNull() { - strValue := summary.Raw() - toolcalls := gjson.Parse(strValue).Array() - - steps := []string{} - for _, toolcall := range toolcalls { - call := toolcall.Value().(map[string]any) - if toolInvocation, ok := call["toolInvocation"].(map[string]any); ok { - data, _ := json.Marshal(toolInvocation) - var toolCall opencode.ToolInvocationPart - _ = json.Unmarshal(data, &toolCall) - - if metadata, ok := call["metadata"].(map[string]any); ok { - data, _ = json.Marshal(metadata) - var toolMetadata opencode.MessageMetadataTool - _ = json.Unmarshal(data, &toolMetadata) - - step := renderToolTitle(toolCall, messageMetadata, width) + case "todowrite": + todos := metadata["todos"] + if todos != nil { + for _, item := range todos.([]any) { + todo := item.(map[string]any) + content := todo["content"].(string) + switch todo["status"] { + case "completed": + body += fmt.Sprintf("- [x] %s\n", content) + case "cancelled": + body += fmt.Sprintf("- [~] %s\n", content) + // case "in-progress": + // body += fmt.Sprintf("- [ ] %s\n", content) + default: + body += fmt.Sprintf("- [ ] %s\n", content) + } + } + body = util.ToMarkdown(body, width, backgroundColor) + } + case "task": + summary := metadata["summary"] + if summary != nil { + toolcalls := summary.([]any) + steps := []string{} + for _, toolcall := range toolcalls { + call := toolcall.(map[string]any) + if toolInvocation, ok := call["toolInvocation"].(map[string]any); ok { + data, _ := json.Marshal(toolInvocation) + var toolCall opencode.ToolPart + _ = json.Unmarshal(data, &toolCall) + step := renderToolTitle(toolCall, width) step = "∟ " + step steps = append(steps, step) } } + body = strings.Join(steps, "\n") } - body = strings.Join(steps, "\n") + default: + if result == nil { + empty := "" + result = &empty + } + body = *result + body = util.TruncateHeight(body, 10) + body = styles.NewStyle().Width(width - 6).Render(body) } - default: - if result == nil { - empty := "" - result = &empty - } - body = *result - body = util.TruncateHeight(body, 10) } error := "" - if err, ok := metadata.ExtraFields["error"].(bool); ok && err { - if message, ok := metadata.ExtraFields["message"].(string); ok { - error = message - } + if toolCall.State.Status == opencode.ToolPartStateStatusError { + error = toolCall.State.Error } if error != "" { body = styles.NewStyle(). + Width(width - 6). Foreground(t.Error()). Background(backgroundColor). Render(error) @@ -492,9 +477,10 @@ func renderToolDetails( if body == "" && error == "" && result != nil { body = *result body = util.TruncateHeight(body, 10) + body = styles.NewStyle().Width(width - 6).Render(body) } - title := renderToolTitle(toolCall, messageMetadata, width) + title := renderToolTitle(toolCall, width) content := title + "\n\n" + body return renderContentBlock(app, content, highlight, width, WithBorderColor(borderColor)) } @@ -515,20 +501,19 @@ func renderToolName(name string) string { } func renderToolTitle( - toolCall opencode.ToolInvocationPart, - messageMetadata opencode.MessageMetadata, + toolCall opencode.ToolPart, width int, ) string { // TODO: handle truncate to width - if toolCall.ToolInvocation.State == "partial-call" { - return renderToolAction(toolCall.ToolInvocation.ToolName) + if toolCall.State.Status == opencode.ToolPartStateStatusPending { + return renderToolAction(toolCall.Tool) } toolArgs := "" toolArgsMap := make(map[string]any) - if toolCall.ToolInvocation.Args != nil { - value := toolCall.ToolInvocation.Args + if toolCall.State.Input != nil { + value := toolCall.State.Input if m, ok := value.(map[string]any); ok { toolArgsMap = m @@ -546,8 +531,8 @@ func renderToolTitle( } } - title := renderToolName(toolCall.ToolInvocation.ToolName) - switch toolCall.ToolInvocation.ToolName { + title := renderToolName(toolCall.Tool) + switch toolCall.Tool { case "read": toolArgs = renderArgs(&toolArgsMap, "filePath") title = fmt.Sprintf("%s %s", title, toolArgs) @@ -565,7 +550,7 @@ func renderToolTitle( case "todowrite", "todoread": // title is just the tool name default: - toolName := renderToolName(toolCall.ToolInvocation.ToolName) + toolName := renderToolName(toolCall.Tool) title = fmt.Sprintf("%s %s", toolName, toolArgs) } return title @@ -645,8 +630,8 @@ type Diagnostic struct { } // renderDiagnostics formats LSP diagnostics for display in the TUI -func renderDiagnostics(metadata opencode.MessageMetadataTool, filePath string) string { - if diagnosticsData, ok := metadata.ExtraFields["diagnostics"].(map[string]any); ok { +func renderDiagnostics(metadata map[string]any, filePath string) string { + if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok { if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok { var errorDiagnostics []string for _, diagInterface := range fileDiagnostics { diff --git a/packages/tui/internal/components/chat/messages.go b/packages/tui/internal/components/chat/messages.go index a59b5d79..573acdfc 100644 --- a/packages/tui/internal/components/chat/messages.go +++ b/packages/tui/internal/components/chat/messages.go @@ -99,7 +99,7 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } case opencode.EventListResponseEventMessageUpdated: - if msg.Properties.Info.Metadata.SessionID == m.app.Session.ID { + if msg.Properties.Info.SessionID == m.app.Session.ID { m.renderView(m.width) if m.tail { m.viewport.GotoBottom() @@ -124,19 +124,19 @@ func (m *messagesComponent) renderView(width int) { m.partCount = 0 m.lineCount = 0 - orphanedToolCalls := make([]opencode.ToolInvocationPart, 0) + orphanedToolCalls := make([]opencode.ToolPart, 0) for _, message := range m.app.Messages { var content string var cached bool - switch message.Role { - case opencode.MessageRoleUser: + switch casted := message.(type) { + case opencode.UserMessage: userLoop: - for partIndex, part := range message.Parts { + for partIndex, part := range casted.Parts { switch part := part.AsUnion().(type) { case opencode.TextPart: - remainingParts := message.Parts[partIndex+1:] + remainingParts := casted.Parts[partIndex+1:] fileParts := make([]opencode.FilePart, 0) for _, part := range remainingParts { switch part := part.AsUnion().(type) { @@ -150,7 +150,7 @@ func (m *messagesComponent) renderView(width int) { mediaTypeStyle := styles.NewStyle().Background(t.Secondary()).Foreground(t.BackgroundPanel()).Padding(0, 1) for _, filePart := range fileParts { mediaType := "" - switch filePart.MediaType { + switch filePart.Mime { case "text/plain": mediaType = "txt" case "image/png", "image/jpeg", "image/gif", "image/webp": @@ -175,7 +175,7 @@ func (m *messagesComponent) renderView(width int) { flexItems..., ) - key := m.cache.GenerateKey(message.ID, part.Text, width, m.selectedPart == m.partCount, files) + key := m.cache.GenerateKey(casted.ID, part.Text, width, m.selectedPart == m.partCount, files) content, cached = m.cache.Get(key) if !cached { content = renderText( @@ -199,21 +199,21 @@ func (m *messagesComponent) renderView(width int) { } } - case opencode.MessageRoleAssistant: + case opencode.AssistantMessage: hasTextPart := false - for partIndex, p := range message.Parts { + for partIndex, p := range casted.Parts { switch part := p.AsUnion().(type) { case opencode.TextPart: hasTextPart = true - finished := message.Metadata.Time.Completed > 0 - remainingParts := message.Parts[partIndex+1:] - toolCallParts := make([]opencode.ToolInvocationPart, 0) + finished := casted.Time.Completed > 0 + remainingParts := casted.Parts[partIndex+1:] + toolCallParts := make([]opencode.ToolPart, 0) // sometimes tool calls happen without an assistant message // these should be included in this assistant message as well if len(orphanedToolCalls) > 0 { toolCallParts = append(toolCallParts, orphanedToolCalls...) - orphanedToolCalls = make([]opencode.ToolInvocationPart, 0) + orphanedToolCalls = make([]opencode.ToolPart, 0) } remaining := true @@ -226,9 +226,9 @@ func (m *messagesComponent) renderView(width int) { // we only want tool calls associated with the current text part. // if we hit another text part, we're done. remaining = false - case opencode.ToolInvocationPart: + case opencode.ToolPart: toolCallParts = append(toolCallParts, part) - if part.ToolInvocation.State != "result" { + if part.State.Status != opencode.ToolPartStateStatusCompleted || part.State.Status != opencode.ToolPartStateStatusError { // i don't think there's a case where a tool call isn't in result state // and the message time is 0, but just in case finished = false @@ -237,14 +237,14 @@ func (m *messagesComponent) renderView(width int) { } if finished { - key := m.cache.GenerateKey(message.ID, p.Text, width, m.showToolDetails, m.selectedPart == m.partCount) + key := m.cache.GenerateKey(casted.ID, p.Text, width, m.showToolDetails, m.selectedPart == m.partCount) content, cached = m.cache.Get(key) if !cached { content = renderText( m.app, message, p.Text, - message.Metadata.Assistant.ModelID, + casted.ModelID, m.showToolDetails, m.partCount == m.selectedPart, width, @@ -258,7 +258,7 @@ func (m *messagesComponent) renderView(width int) { m.app, message, p.Text, - message.Metadata.Assistant.ModelID, + casted.ModelID, m.showToolDetails, m.partCount == m.selectedPart, width, @@ -270,7 +270,7 @@ func (m *messagesComponent) renderView(width int) { m = m.updateSelected(content, p.Text) blocks = append(blocks, content) } - case opencode.ToolInvocationPart: + case opencode.ToolPart: if !m.showToolDetails { if !hasTextPart { orphanedToolCalls = append(orphanedToolCalls, part) @@ -278,9 +278,9 @@ func (m *messagesComponent) renderView(width int) { continue } - if part.ToolInvocation.State == "result" { - key := m.cache.GenerateKey(message.ID, - part.ToolInvocation.ToolCallID, + if part.State.Status == opencode.ToolPartStateStatusCompleted || part.State.Status == opencode.ToolPartStateStatusError { + key := m.cache.GenerateKey(casted.ID, + part.ID, m.showToolDetails, width, m.partCount == m.selectedPart, @@ -290,7 +290,6 @@ func (m *messagesComponent) renderView(width int) { content = renderToolDetails( m.app, part, - message.Metadata, m.partCount == m.selectedPart, width, ) @@ -301,7 +300,6 @@ func (m *messagesComponent) renderView(width int) { content = renderToolDetails( m.app, part, - message.Metadata, m.partCount == m.selectedPart, width, ) @@ -315,17 +313,22 @@ func (m *messagesComponent) renderView(width int) { } error := "" - switch err := message.Metadata.Error.AsUnion().(type) { - case nil: - case opencode.MessageMetadataErrorMessageOutputLengthError: - error = "Message output length exceeded" - case opencode.ProviderAuthError: - error = err.Data.Message - case opencode.UnknownError: - error = err.Data.Message + if assistant, ok := message.(opencode.AssistantMessage); ok { + switch err := assistant.Error.AsUnion().(type) { + case nil: + case opencode.AssistantMessageErrorMessageOutputLengthError: + error = "Message output length exceeded" + case opencode.ProviderAuthError: + error = err.Data.Message + case opencode.MessageAbortedError: + error = "Request was aborted" + case opencode.UnknownError: + error = err.Data.Message + } } if error != "" { + error = styles.NewStyle().Width(width - 6).Render(error) error = renderContentBlock( m.app, error, diff --git a/packages/tui/internal/components/commands/commands.go b/packages/tui/internal/components/commands/commands.go index f3080b38..7f293230 100644 --- a/packages/tui/internal/components/commands/commands.go +++ b/packages/tui/internal/components/commands/commands.go @@ -56,8 +56,8 @@ func (c *commandsComponent) View() string { var untriggeredCommands []commands.Command for _, cmd := range c.app.Commands.Sorted() { - if c.showAll || cmd.Trigger != "" { - if cmd.Trigger != "" { + if c.showAll || cmd.HasTrigger() { + if cmd.HasTrigger() { triggeredCommands = append(triggeredCommands, cmd) } else if c.showAll { untriggeredCommands = append(untriggeredCommands, cmd) @@ -97,8 +97,8 @@ func (c *commandsComponent) View() string { for _, cmd := range commandsToShow { trigger := "" - if cmd.Trigger != "" { - trigger = "/" + cmd.Trigger + if cmd.HasTrigger() { + trigger = "/" + cmd.PrimaryTrigger() } else { trigger = string(cmd.Name) } diff --git a/packages/tui/internal/components/dialog/complete.go b/packages/tui/internal/components/dialog/complete.go index 7ba91dc5..8173c8af 100644 --- a/packages/tui/internal/components/dialog/complete.go +++ b/packages/tui/internal/components/dialog/complete.go @@ -2,6 +2,7 @@ package dialog import ( "log/slog" + "strings" "github.com/charmbracelet/bubbles/v2/key" "github.com/charmbracelet/bubbles/v2/textarea" @@ -87,6 +88,7 @@ type completionDialogComponent struct { height int pseudoSearchTextArea textarea.Model list list.List[CompletionItemI] + trigger string } type completionDialogKeyMap struct { @@ -119,8 +121,8 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) { c.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg) cmds = append(cmds, cmd) - var query string - query = c.pseudoSearchTextArea.Value() + fullValue := c.pseudoSearchTextArea.Value() + query := strings.TrimPrefix(fullValue, c.trigger) if query != c.query { c.query = query @@ -147,8 +149,9 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return c, c.complete(item) case key.Matches(msg, completionDialogKeys.Cancel): - // Only close on backspace when there are no characters left - if msg.String() != "backspace" || len(c.pseudoSearchTextArea.Value()) <= 0 { + // Only close on backspace when there are no characters left, unless we're back to just the trigger + value := c.pseudoSearchTextArea.Value() + if msg.String() != "backspace" || (len(value) <= len(c.trigger) && value != c.trigger) { return c, c.close() } } @@ -227,7 +230,7 @@ func (c *completionDialogComponent) close() tea.Cmd { return util.CmdHandler(CompletionDialogCloseMsg{}) } -func NewCompletionDialogComponent(completionProvider CompletionProvider) CompletionDialog { +func NewCompletionDialogComponent(completionProvider CompletionProvider, trigger string) CompletionDialog { ti := textarea.New() li := list.NewListComponent( @@ -245,10 +248,14 @@ func NewCompletionDialogComponent(completionProvider CompletionProvider) Complet li.SetItems(items) }() + // Initialize the textarea with the trigger character + ti.SetValue(trigger) + return &completionDialogComponent{ query: "", completionProvider: completionProvider, pseudoSearchTextArea: ti, list: li, + trigger: trigger, } } diff --git a/packages/tui/internal/components/status/status.go b/packages/tui/internal/components/status/status.go index 791267e0..7d5820de 100644 --- a/packages/tui/internal/components/status/status.go +++ b/packages/tui/internal/components/status/status.go @@ -6,6 +6,7 @@ import ( tea "github.com/charmbracelet/bubbletea/v2" "github.com/charmbracelet/lipgloss/v2" + "github.com/sst/opencode-sdk-go" "github.com/sst/opencode/internal/app" "github.com/sst/opencode/internal/styles" "github.com/sst/opencode/internal/theme" @@ -101,18 +102,20 @@ func (m statusComponent) View() string { contextWindow := m.app.Model.Limit.Context for _, message := range m.app.Messages { - cost += message.Metadata.Assistant.Cost - usage := message.Metadata.Assistant.Tokens - if usage.Output > 0 { - if message.Metadata.Assistant.Summary { - tokens = usage.Output - continue + if assistant, ok := message.(opencode.AssistantMessage); ok { + cost += assistant.Cost + usage := assistant.Tokens + if usage.Output > 0 { + if assistant.Summary { + tokens = usage.Output + continue + } + tokens = (usage.Input + + usage.Cache.Write + + usage.Cache.Read + + usage.Output + + usage.Reasoning) } - tokens = (usage.Input + - usage.Cache.Write + - usage.Cache.Read + - usage.Output + - usage.Reasoning) } } diff --git a/packages/tui/internal/components/textarea/textarea.go b/packages/tui/internal/components/textarea/textarea.go index 5ff936f1..41a4a3d9 100644 --- a/packages/tui/internal/components/textarea/textarea.go +++ b/packages/tui/internal/components/textarea/textarea.go @@ -11,7 +11,6 @@ import ( "slices" - "github.com/atotto/clipboard" "github.com/charmbracelet/bubbles/v2/cursor" "github.com/charmbracelet/bubbles/v2/key" tea "github.com/charmbracelet/bubbletea/v2" @@ -653,12 +652,12 @@ func (m *Model) SetValue(s string) { // InsertString inserts a string at the cursor position. func (m *Model) InsertString(s string) { - m.insertRunesFromUserInput([]rune(s)) + m.InsertRunesFromUserInput([]rune(s)) } // InsertRune inserts a rune at the cursor position. func (m *Model) InsertRune(r rune) { - m.insertRunesFromUserInput([]rune{r}) + m.InsertRunesFromUserInput([]rune{r}) } // InsertAttachment inserts an attachment at the cursor position. @@ -730,8 +729,8 @@ func (m Model) GetAttachments() []*Attachment { return attachments } -// insertRunesFromUserInput inserts runes at the current cursor position. -func (m *Model) insertRunesFromUserInput(runes []rune) { +// InsertRunesFromUserInput inserts runes at the current cursor position. +func (m *Model) InsertRunesFromUserInput(runes []rune) { // Clean up any special characters in the input provided by the // clipboard. This avoids bugs due to e.g. tab characters and // whatnot. @@ -1429,8 +1428,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } switch msg := msg.(type) { - case tea.PasteMsg: - m.insertRunesFromUserInput([]rune(msg)) case tea.KeyPressMsg: switch { case key.Matches(msg, m.KeyMap.DeleteAfterCursor): @@ -1490,8 +1487,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.CursorDown() case key.Matches(msg, m.KeyMap.WordForward): m.wordRight() - case key.Matches(msg, m.KeyMap.Paste): - return m, Paste case key.Matches(msg, m.KeyMap.CharacterBackward): m.characterLeft(false /* insideLine */) case key.Matches(msg, m.KeyMap.LinePrevious): @@ -1512,11 +1507,11 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.transposeLeft() default: - m.insertRunesFromUserInput([]rune(msg.Text)) + m.InsertRunesFromUserInput([]rune(msg.Text)) } case pasteMsg: - m.insertRunesFromUserInput([]rune(msg)) + m.InsertRunesFromUserInput([]rune(msg)) case pasteErrMsg: m.Err = msg @@ -1908,15 +1903,6 @@ func (m *Model) splitLine(row, col int) { m.row++ } -// Paste is a command for pasting from the clipboard into the text input. -func Paste() tea.Msg { - str, err := clipboard.ReadAll() - if err != nil { - return pasteErrMsg{err} - } - return pasteMsg(str) -} - func wrapInterfaces(content []any, width int) [][]any { if width <= 0 { return [][]any{content} diff --git a/packages/tui/internal/image/clipboard_unix.go b/packages/tui/internal/image/clipboard_unix.go deleted file mode 100644 index 2653d8ca..00000000 --- a/packages/tui/internal/image/clipboard_unix.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build !windows - -package image - -import ( - "bytes" - "fmt" - "github.com/atotto/clipboard" - "image" -) - -func GetImageFromClipboard() ([]byte, string, error) { - text, err := clipboard.ReadAll() - if err != nil { - return nil, "", fmt.Errorf("Error reading clipboard") - } - - if text == "" { - return nil, "", nil - } - - binaryData := []byte(text) - imageBytes, err := binaryToImage(binaryData) - if err != nil { - return nil, text, nil - } - return imageBytes, "", nil - -} - -func binaryToImage(data []byte) ([]byte, error) { - reader := bytes.NewReader(data) - img, _, err := image.Decode(reader) - if err != nil { - return nil, fmt.Errorf("Unable to covert bytes to image") - } - - return ImageToBytes(img) -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/packages/tui/internal/image/clipboard_windows.go b/packages/tui/internal/image/clipboard_windows.go deleted file mode 100644 index 6431ce3d..00000000 --- a/packages/tui/internal/image/clipboard_windows.go +++ /dev/null @@ -1,192 +0,0 @@ -//go:build windows - -package image - -import ( - "bytes" - "fmt" - "image" - "image/color" - "log/slog" - "syscall" - "unsafe" -) - -var ( - user32 = syscall.NewLazyDLL("user32.dll") - kernel32 = syscall.NewLazyDLL("kernel32.dll") - openClipboard = user32.NewProc("OpenClipboard") - closeClipboard = user32.NewProc("CloseClipboard") - getClipboardData = user32.NewProc("GetClipboardData") - isClipboardFormatAvailable = user32.NewProc("IsClipboardFormatAvailable") - globalLock = kernel32.NewProc("GlobalLock") - globalUnlock = kernel32.NewProc("GlobalUnlock") - globalSize = kernel32.NewProc("GlobalSize") -) - -const ( - CF_TEXT = 1 - CF_UNICODETEXT = 13 - CF_DIB = 8 -) - -type BITMAPINFOHEADER struct { - BiSize uint32 - BiWidth int32 - BiHeight int32 - BiPlanes uint16 - BiBitCount uint16 - BiCompression uint32 - BiSizeImage uint32 - BiXPelsPerMeter int32 - BiYPelsPerMeter int32 - BiClrUsed uint32 - BiClrImportant uint32 -} - -func GetImageFromClipboard() ([]byte, string, error) { - ret, _, _ := openClipboard.Call(0) - if ret == 0 { - return nil, "", fmt.Errorf("failed to open clipboard") - } - defer func(closeClipboard *syscall.LazyProc, a ...uintptr) { - _, _, err := closeClipboard.Call(a...) - if err != nil { - slog.Error("close clipboard failed") - return - } - }(closeClipboard) - isTextAvailable, _, _ := isClipboardFormatAvailable.Call(uintptr(CF_TEXT)) - isUnicodeTextAvailable, _, _ := isClipboardFormatAvailable.Call(uintptr(CF_UNICODETEXT)) - - if isTextAvailable != 0 || isUnicodeTextAvailable != 0 { - // Get text from clipboard - var formatToUse uintptr = CF_TEXT - if isUnicodeTextAvailable != 0 { - formatToUse = CF_UNICODETEXT - } - - hClipboardText, _, _ := getClipboardData.Call(formatToUse) - if hClipboardText != 0 { - textPtr, _, _ := globalLock.Call(hClipboardText) - if textPtr != 0 { - defer func(globalUnlock *syscall.LazyProc, a ...uintptr) { - _, _, err := globalUnlock.Call(a...) - if err != nil { - slog.Error("Global unlock failed") - return - } - }(globalUnlock, hClipboardText) - - // Get clipboard text - var clipboardText string - if formatToUse == CF_UNICODETEXT { - // Convert wide string to Go string - clipboardText = syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(textPtr))[:]) - } else { - // Get size of ANSI text - size, _, _ := globalSize.Call(hClipboardText) - if size > 0 { - // Convert ANSI string to Go string - textBytes := make([]byte, size) - copy(textBytes, (*[1 << 20]byte)(unsafe.Pointer(textPtr))[:size:size]) - clipboardText = bytesToString(textBytes) - } - } - - // Check if the text is not empty - if clipboardText != "" { - return nil, clipboardText, nil - } - } - } - } - hClipboardData, _, _ := getClipboardData.Call(uintptr(CF_DIB)) - if hClipboardData == 0 { - return nil, "", fmt.Errorf("failed to get clipboard data") - } - - dataPtr, _, _ := globalLock.Call(hClipboardData) - if dataPtr == 0 { - return nil, "", fmt.Errorf("failed to lock clipboard data") - } - defer func(globalUnlock *syscall.LazyProc, a ...uintptr) { - _, _, err := globalUnlock.Call(a...) - if err != nil { - slog.Error("Global unlock failed") - return - } - }(globalUnlock, hClipboardData) - - bmiHeader := (*BITMAPINFOHEADER)(unsafe.Pointer(dataPtr)) - - width := int(bmiHeader.BiWidth) - height := int(bmiHeader.BiHeight) - if height < 0 { - height = -height - } - bitsPerPixel := int(bmiHeader.BiBitCount) - - img := image.NewRGBA(image.Rect(0, 0, width, height)) - - var bitsOffset uintptr - if bitsPerPixel <= 8 { - numColors := uint32(1) << bitsPerPixel - if bmiHeader.BiClrUsed > 0 { - numColors = bmiHeader.BiClrUsed - } - bitsOffset = unsafe.Sizeof(*bmiHeader) + uintptr(numColors*4) - } else { - bitsOffset = unsafe.Sizeof(*bmiHeader) - } - - for y := range height { - for x := range width { - - srcY := height - y - 1 - if bmiHeader.BiHeight < 0 { - srcY = y - } - - var pixelPointer unsafe.Pointer - var r, g, b, a uint8 - - switch bitsPerPixel { - case 24: - stride := (width*3 + 3) &^ 3 - pixelPointer = unsafe.Pointer(dataPtr + bitsOffset + uintptr(srcY*stride+x*3)) - b = *(*byte)(pixelPointer) - g = *(*byte)(unsafe.Add(pixelPointer, 1)) - r = *(*byte)(unsafe.Add(pixelPointer, 2)) - a = 255 - case 32: - pixelPointer = unsafe.Pointer(dataPtr + bitsOffset + uintptr(srcY*width*4+x*4)) - b = *(*byte)(pixelPointer) - g = *(*byte)(unsafe.Add(pixelPointer, 1)) - r = *(*byte)(unsafe.Add(pixelPointer, 2)) - a = *(*byte)(unsafe.Add(pixelPointer, 3)) - if a == 0 { - a = 255 - } - default: - return nil, "", fmt.Errorf("unsupported bit count: %d", bitsPerPixel) - } - - img.Set(x, y, color.RGBA{R: r, G: g, B: b, A: a}) - } - } - - imageBytes, err := ImageToBytes(img) - if err != nil { - return nil, "", err - } - return imageBytes, "", nil -} - -func bytesToString(b []byte) string { - i := bytes.IndexByte(b, 0) - if i == -1 { - return string(b) - } - return string(b[:i]) -} diff --git a/packages/tui/internal/image/images.go b/packages/tui/internal/image/images.go deleted file mode 100644 index 742eb30a..00000000 --- a/packages/tui/internal/image/images.go +++ /dev/null @@ -1,86 +0,0 @@ -package image - -import ( - "bytes" - "fmt" - "image" - "image/color" - "image/png" - "os" - "strings" - - "github.com/charmbracelet/lipgloss/v2" - "github.com/disintegration/imaging" - "github.com/lucasb-eyer/go-colorful" - _ "golang.org/x/image/webp" -) - -func ValidateFileSize(filePath string, sizeLimit int64) (bool, error) { - fileInfo, err := os.Stat(filePath) - if err != nil { - return false, fmt.Errorf("error getting file info: %w", err) - } - - if fileInfo.Size() > sizeLimit { - return true, nil - } - - return false, nil -} - -func ToString(width int, img image.Image) string { - img = imaging.Resize(img, width, 0, imaging.Lanczos) - b := img.Bounds() - imageWidth := b.Max.X - h := b.Max.Y - str := strings.Builder{} - - for heightCounter := 0; heightCounter < h; heightCounter += 2 { - for x := range imageWidth { - c1, _ := colorful.MakeColor(img.At(x, heightCounter)) - color1 := lipgloss.Color(c1.Hex()) - - var color2 color.Color - if heightCounter+1 < h { - c2, _ := colorful.MakeColor(img.At(x, heightCounter+1)) - color2 = lipgloss.Color(c2.Hex()) - } else { - color2 = color1 - } - - str.WriteString(lipgloss.NewStyle().Foreground(color1). - Background(color2).Render("▀")) - } - - str.WriteString("\n") - } - - return str.String() -} - -func ImagePreview(width int, filename string) (string, error) { - imageContent, err := os.Open(filename) - if err != nil { - return "", err - } - defer imageContent.Close() - - img, _, err := image.Decode(imageContent) - if err != nil { - return "", err - } - - imageString := ToString(width, img) - - return imageString, nil -} - -func ImageToBytes(image image.Image) ([]byte, error) { - buf := new(bytes.Buffer) - err := png.Encode(buf, image) - if err != nil { - return nil, err - } - - return buf.Bytes(), nil -} diff --git a/packages/tui/internal/tui/tui.go b/packages/tui/internal/tui/tui.go index 150a1b26..73dd0118 100644 --- a/packages/tui/internal/tui/tui.go +++ b/packages/tui/internal/tui/tui.go @@ -32,15 +32,27 @@ import ( // InterruptDebounceTimeoutMsg is sent when the interrupt key debounce timeout expires type InterruptDebounceTimeoutMsg struct{} +// ExitDebounceTimeoutMsg is sent when the exit key debounce timeout expires +type ExitDebounceTimeoutMsg struct{} + // InterruptKeyState tracks the state of interrupt key presses for debouncing type InterruptKeyState int +// ExitKeyState tracks the state of exit key presses for debouncing +type ExitKeyState int + const ( InterruptKeyIdle InterruptKeyState = iota InterruptKeyFirstPress ) +const ( + ExitKeyIdle ExitKeyState = iota + ExitKeyFirstPress +) + const interruptDebounceTimeout = 1 * time.Second +const exitDebounceTimeout = 1 * time.Second const fileViewerFullWidthCutoff = 160 type appModel struct { @@ -59,6 +71,7 @@ type appModel struct { isLeaderSequence bool toastManager *toast.ToastManager interruptKeyState InterruptKeyState + exitKeyState ExitKeyState lastScroll time.Time messagesRight bool fileViewer fileviewer.Model @@ -189,7 +202,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { cmds = append(cmds, cmd) // Set command provider for command completion - a.completions = dialog.NewCompletionDialogComponent(a.commandProvider) + a.completions = dialog.NewCompletionDialogComponent(a.commandProvider, "/") updated, cmd = a.completions.Update(msg) a.completions = updated.(dialog.CompletionDialog) cmds = append(cmds, cmd) @@ -208,7 +221,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { cmds = append(cmds, cmd) // Set file provider for file completion - a.completions = dialog.NewCompletionDialogComponent(a.fileProvider) + a.completions = dialog.NewCompletionDialogComponent(a.fileProvider, "@") updated, cmd = a.completions.Update(msg) a.completions = updated.(dialog.CompletionDialog) cmds = append(cmds, cmd) @@ -252,7 +265,13 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return a, nil } - // 6. Handle interrupt key debounce for session interrupt + // 6 Handle input clear command + inputClearCommand := a.app.Commands[commands.InputClearCommand] + if inputClearCommand.Matches(msg, a.isLeaderSequence) && a.editor.Length() > 0 { + return a, util.CmdHandler(commands.ExecuteCommandMsg(inputClearCommand)) + } + + // 7. Handle interrupt key debounce for session interrupt interruptCommand := a.app.Commands[commands.SessionInterruptCommand] if interruptCommand.Matches(msg, a.isLeaderSequence) && a.app.IsBusy() { switch a.interruptKeyState { @@ -271,7 +290,26 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } - // 7. Check again for commands that don't require leader (excluding interrupt when busy) + // 8. Handle exit key debounce for app exit when using non-leader command + exitCommand := a.app.Commands[commands.AppExitCommand] + if exitCommand.Matches(msg, a.isLeaderSequence) { + switch a.exitKeyState { + case ExitKeyIdle: + // First exit key press - start debounce timer + a.exitKeyState = ExitKeyFirstPress + a.editor.SetExitKeyInDebounce(true) + return a, tea.Tick(exitDebounceTimeout, func(t time.Time) tea.Msg { + return ExitDebounceTimeoutMsg{} + }) + case ExitKeyFirstPress: + // Second exit key press within timeout - actually exit + a.exitKeyState = ExitKeyIdle + a.editor.SetExitKeyInDebounce(false) + return a, util.CmdHandler(commands.ExecuteCommandMsg(exitCommand)) + } + } + + // 9. Check again for commands that don't require leader (excluding interrupt when busy and exit when in debounce) matches := a.app.Commands.Matches(msg, a.isLeaderSequence) if len(matches) > 0 { // Skip interrupt key if we're in debounce mode and app is busy @@ -281,8 +319,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return a, util.CmdHandler(commands.ExecuteCommandsMsg(matches)) } - // 7. Fallback to editor. This is for other characters - // like backspace, tab, etc. + // 10. Fallback to editor. This is for other characters like backspace, tab, etc. updatedEditor, cmd := a.editor.Update(msg) a.editor = updatedEditor.(chat.EditorComponent) return a, cmd @@ -363,7 +400,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case opencode.EventListResponseEventSessionDeleted: if a.app.Session != nil && msg.Properties.Info.ID == a.app.Session.ID { a.app.Session = &opencode.Session{} - a.app.Messages = []opencode.Message{} + a.app.Messages = []opencode.MessageUnion{} } return a, toast.NewSuccessToast("Session deleted successfully") case opencode.EventListResponseEventSessionUpdated: @@ -371,7 +408,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { a.app.Session = &msg.Properties.Info } case opencode.EventListResponseEventMessageUpdated: - if msg.Properties.Info.Metadata.SessionID == a.app.Session.ID { + if msg.Properties.Info.SessionID == a.app.Session.ID { exists := false optimisticReplaced := false @@ -379,12 +416,15 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.Properties.Info.Role == opencode.MessageRoleUser { // Look for optimistic messages to replace for i, m := range a.app.Messages { - if strings.HasPrefix(m.ID, "optimistic-") && m.Role == opencode.MessageRoleUser { - // Replace the optimistic message with the real one - a.app.Messages[i] = msg.Properties.Info - exists = true - optimisticReplaced = true - break + switch m := m.(type) { + case opencode.UserMessage: + if strings.HasPrefix(m.ID, "optimistic-") && m.Role == opencode.UserMessageRoleUser { + // Replace the optimistic message with the real one + a.app.Messages[i] = msg.Properties.Info.AsUnion() + exists = true + optimisticReplaced = true + break + } } } } @@ -392,8 +432,15 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // If not replacing optimistic, check for existing message with same ID if !optimisticReplaced { for i, m := range a.app.Messages { - if m.ID == msg.Properties.Info.ID { - a.app.Messages[i] = msg.Properties.Info + var id string + switch m := m.(type) { + case opencode.UserMessage: + id = m.ID + case opencode.AssistantMessage: + id = m.ID + } + if id == msg.Properties.Info.ID { + a.app.Messages[i] = msg.Properties.Info.AsUnion() exists = true break } @@ -401,7 +448,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } if !exists { - a.app.Messages = append(a.app.Messages, msg.Properties.Info) + a.app.Messages = append(a.app.Messages, msg.Properties.Info.AsUnion()) } } case opencode.EventListResponseEventSessionError: @@ -462,7 +509,10 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return a, toast.NewErrorToast("Failed to open session") } a.app.Session = msg - a.app.Messages = messages + a.app.Messages = make([]opencode.MessageUnion, 0) + for _, message := range messages { + a.app.Messages = append(a.app.Messages, message.AsUnion()) + } return a, util.CmdHandler(app.SessionLoadedMsg{}) case app.ModelSelectedMsg: a.app.Provider = &msg.Provider @@ -486,6 +536,10 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Reset interrupt key state after timeout a.interruptKeyState = InterruptKeyIdle a.editor.SetInterruptKeyInDebounce(false) + case ExitDebounceTimeoutMsg: + // Reset exit key state after timeout + a.exitKeyState = ExitKeyIdle + a.editor.SetExitKeyInDebounce(false) case dialog.FindSelectedMsg: return a.openFile(msg.FilePath) } @@ -813,7 +867,7 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd) return a, nil } a.app.Session = &opencode.Session{} - a.app.Messages = []opencode.Message{} + a.app.Messages = []opencode.MessageUnion{} cmds = append(cmds, util.CmdHandler(app.SessionClearedMsg{})) case commands.SessionListCommand: sessionDialog := dialog.NewSessionDialog(a.app) @@ -828,7 +882,7 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd) return a, toast.NewErrorToast("Failed to share session") } shareUrl := response.Share.URL - cmds = append(cmds, tea.SetClipboard(shareUrl)) + cmds = append(cmds, a.app.SetClipboard(shareUrl)) cmds = append(cmds, toast.NewSuccessToast("Share URL copied to clipboard!")) case commands.SessionUnshareCommand: if a.app.Session.ID == "" { @@ -962,7 +1016,7 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd) case commands.MessagesCopyCommand: selected := a.messages.Selected() if selected != "" { - cmd = tea.SetClipboard(selected) + cmd = a.app.SetClipboard(selected) cmds = append(cmds, cmd) cmd = toast.NewSuccessToast("Message copied to clipboard") cmds = append(cmds, cmd) @@ -980,7 +1034,7 @@ func NewModel(app *app.App) tea.Model { messages := chat.NewMessagesComponent(app) editor := chat.NewEditorComponent(app) - completions := dialog.NewCompletionDialogComponent(commandProvider) + completions := dialog.NewCompletionDialogComponent(commandProvider, "/") var leaderBinding *key.Binding if app.Config.Keybinds.Leader != "" { @@ -1002,6 +1056,7 @@ func NewModel(app *app.App) tea.Model { fileCompletionActive: false, toastManager: toast.NewToastManager(), interruptKeyState: InterruptKeyIdle, + exitKeyState: ExitKeyIdle, fileViewer: fileviewer.New(app), messagesRight: app.State.MessagesRight, } diff --git a/packages/tui/internal/util/apilogger.go b/packages/tui/internal/util/apilogger.go new file mode 100644 index 00000000..b439bbec --- /dev/null +++ b/packages/tui/internal/util/apilogger.go @@ -0,0 +1,123 @@ +package util + +import ( + "context" + "log/slog" + "sync" + + opencode "github.com/sst/opencode-sdk-go" +) + +type APILogHandler struct { + client *opencode.Client + service string + level slog.Level + attrs []slog.Attr + groups []string + mu sync.Mutex +} + +func NewAPILogHandler(client *opencode.Client, service string, level slog.Level) *APILogHandler { + return &APILogHandler{ + client: client, + service: service, + level: level, + attrs: make([]slog.Attr, 0), + groups: make([]string, 0), + } +} + +func (h *APILogHandler) Enabled(_ context.Context, level slog.Level) bool { + return level >= h.level +} + +func (h *APILogHandler) Handle(ctx context.Context, r slog.Record) error { + var apiLevel opencode.AppLogParamsLevel + switch r.Level { + case slog.LevelDebug: + apiLevel = opencode.AppLogParamsLevelDebug + case slog.LevelInfo: + apiLevel = opencode.AppLogParamsLevelInfo + case slog.LevelWarn: + apiLevel = opencode.AppLogParamsLevelWarn + case slog.LevelError: + apiLevel = opencode.AppLogParamsLevelError + default: + apiLevel = opencode.AppLogParamsLevelInfo + } + + extra := make(map[string]any) + + h.mu.Lock() + for _, attr := range h.attrs { + extra[attr.Key] = attr.Value.Any() + } + h.mu.Unlock() + + r.Attrs(func(attr slog.Attr) bool { + extra[attr.Key] = attr.Value.Any() + return true + }) + + params := opencode.AppLogParams{ + Service: opencode.F(h.service), + Level: opencode.F(apiLevel), + Message: opencode.F(r.Message), + } + + if len(extra) > 0 { + params.Extra = opencode.F(extra) + } + + go func() { + _, err := h.client.App.Log(context.Background(), params) + if err != nil { + // Fallback: we can't log the error using slog as it would create a loop + // TODO: fallback file? + } + }() + + return nil +} + +// WithAttrs returns a new Handler whose attributes consist of +// both the receiver's attributes and the arguments. +func (h *APILogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + h.mu.Lock() + defer h.mu.Unlock() + + newHandler := &APILogHandler{ + client: h.client, + service: h.service, + level: h.level, + attrs: make([]slog.Attr, len(h.attrs)+len(attrs)), + groups: make([]string, len(h.groups)), + } + + copy(newHandler.attrs, h.attrs) + copy(newHandler.attrs[len(h.attrs):], attrs) + copy(newHandler.groups, h.groups) + + return newHandler +} + +// WithGroup returns a new Handler with the given group appended to +// the receiver's existing groups. +func (h *APILogHandler) WithGroup(name string) slog.Handler { + h.mu.Lock() + defer h.mu.Unlock() + + newHandler := &APILogHandler{ + client: h.client, + service: h.service, + level: h.level, + attrs: make([]slog.Attr, len(h.attrs)), + groups: make([]string, len(h.groups)+1), + } + + copy(newHandler.attrs, h.attrs) + copy(newHandler.groups, h.groups) + newHandler.groups[len(h.groups)] = name + + return newHandler +} diff --git a/packages/tui/sdk/.stats.yml b/packages/tui/sdk/.stats.yml index ab6c4a20..e3d98579 100644 --- a/packages/tui/sdk/.stats.yml +++ b/packages/tui/sdk/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 20 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-945f9da9e9a4c4008834deef63e4346c0076e020eed3d3c98c249095033c1ac5.yml -openapi_spec_hash: 522a44f6cb0677435fe2ac7693848ad7 -config_hash: 6c8822d278ba83456e5eed6d774ca230 +configured_endpoints: 21 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-879570c29c56e0a73a0624a84662b7f7c319a3c790c78ec6ac4cf62a7b1a5bd0.yml +openapi_spec_hash: 2432e2dfed22193a0c6b3dfe0f82ec7d +config_hash: 53e3aeb355f3b2e0d10985d6d7635a7e diff --git a/packages/tui/sdk/aliases.go b/packages/tui/sdk/aliases.go index 84dd614a..6ab36d04 100644 --- a/packages/tui/sdk/aliases.go +++ b/packages/tui/sdk/aliases.go @@ -9,6 +9,15 @@ import ( type Error = apierror.Error +// This is an alias to an internal type. +type MessageAbortedError = shared.MessageAbortedError + +// This is an alias to an internal type. +type MessageAbortedErrorName = shared.MessageAbortedErrorName + +// This is an alias to an internal value. +const MessageAbortedErrorNameMessageAbortedError = shared.MessageAbortedErrorNameMessageAbortedError + // This is an alias to an internal type. type ProviderAuthError = shared.ProviderAuthError diff --git a/packages/tui/sdk/api.md b/packages/tui/sdk/api.md index 4ac9edcf..c0304614 100644 --- a/packages/tui/sdk/api.md +++ b/packages/tui/sdk/api.md @@ -1,5 +1,6 @@ # Shared Response Types +- shared.MessageAbortedError - shared.ProviderAuthError - shared.UnknownError @@ -18,36 +19,38 @@ Methods: Response Types: - opencode.App +- opencode.LogLevel Methods: - client.App.Get(ctx context.Context) (opencode.App, error) - client.App.Init(ctx context.Context) (bool, error) +- client.App.Log(ctx context.Context, body opencode.AppLogParams) (bool, error) # Find Response Types: -- opencode.FindSymbolsResponse -- opencode.FindTextResponse +- opencode.Match +- opencode.Symbol Methods: - client.Find.Files(ctx context.Context, query opencode.FindFilesParams) ([]string, error) -- client.Find.Symbols(ctx context.Context, query opencode.FindSymbolsParams) ([]opencode.FindSymbolsResponse, error) -- client.Find.Text(ctx context.Context, query opencode.FindTextParams) ([]opencode.FindTextResponse, error) +- client.Find.Symbols(ctx context.Context, query opencode.FindSymbolsParams) ([]opencode.Symbol, error) +- client.Find.Text(ctx context.Context, query opencode.FindTextParams) ([]opencode.Match, error) # File Response Types: +- opencode.File - opencode.FileReadResponse -- opencode.FileStatusResponse Methods: - client.File.Read(ctx context.Context, query opencode.FileReadParams) (opencode.FileReadResponse, error) -- client.File.Status(ctx context.Context) ([]opencode.FileStatusResponse, error) +- client.File.Status(ctx context.Context) ([]opencode.File, error) # Config @@ -71,30 +74,25 @@ Methods: Params Types: - opencode.FilePartParam -- opencode.MessagePartUnionParam -- opencode.ReasoningPartParam -- opencode.SourceURLPartParam -- opencode.StepStartPartParam - opencode.TextPartParam -- opencode.ToolCallParam -- opencode.ToolInvocationPartParam -- opencode.ToolPartialCallParam -- opencode.ToolResultParam +- opencode.UserMessagePartUnionParam Response Types: +- opencode.AssistantMessage +- opencode.AssistantMessagePart - opencode.FilePart - opencode.Message -- opencode.MessagePart -- opencode.ReasoningPart - opencode.Session -- opencode.SourceURLPart - opencode.StepStartPart - opencode.TextPart -- opencode.ToolCall -- opencode.ToolInvocationPart -- opencode.ToolPartialCall -- opencode.ToolResult +- opencode.ToolPart +- opencode.ToolStateCompleted +- opencode.ToolStateError +- opencode.ToolStatePending +- opencode.ToolStateRunning +- opencode.UserMessage +- opencode.UserMessagePart Methods: @@ -102,7 +100,7 @@ Methods: - client.Session.List(ctx context.Context) ([]opencode.Session, error) - client.Session.Delete(ctx context.Context, id string) (bool, error) - client.Session.Abort(ctx context.Context, id string) (bool, error) -- client.Session.Chat(ctx context.Context, id string, body opencode.SessionChatParams) (opencode.Message, error) +- client.Session.Chat(ctx context.Context, id string, body opencode.SessionChatParams) (opencode.AssistantMessage, error) - client.Session.Init(ctx context.Context, id string, body opencode.SessionInitParams) (bool, error) - client.Session.Messages(ctx context.Context, id string) ([]opencode.Message, error) - client.Session.Share(ctx context.Context, id string) (opencode.Session, error) diff --git a/packages/tui/sdk/app.go b/packages/tui/sdk/app.go index dc44a74b..ba9303c8 100644 --- a/packages/tui/sdk/app.go +++ b/packages/tui/sdk/app.go @@ -7,6 +7,7 @@ import ( "net/http" "github.com/sst/opencode-sdk-go/internal/apijson" + "github.com/sst/opencode-sdk-go/internal/param" "github.com/sst/opencode-sdk-go/internal/requestconfig" "github.com/sst/opencode-sdk-go/option" ) @@ -46,6 +47,14 @@ func (r *AppService) Init(ctx context.Context, opts ...option.RequestOption) (re return } +// Write a log entry to the server logs +func (r *AppService) Log(ctx context.Context, body AppLogParams, opts ...option.RequestOption) (res *bool, err error) { + opts = append(r.Options[:], opts...) + path := "log" + err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...) + return +} + type App struct { Git bool `json:"git,required"` Hostname string `json:"hostname,required"` @@ -121,3 +130,54 @@ func (r *AppTime) UnmarshalJSON(data []byte) (err error) { func (r appTimeJSON) RawJSON() string { return r.raw } + +// Log level +type LogLevel string + +const ( + LogLevelDebug LogLevel = "DEBUG" + LogLevelInfo LogLevel = "INFO" + LogLevelWarn LogLevel = "WARN" + LogLevelError LogLevel = "ERROR" +) + +func (r LogLevel) IsKnown() bool { + switch r { + case LogLevelDebug, LogLevelInfo, LogLevelWarn, LogLevelError: + return true + } + return false +} + +type AppLogParams struct { + // Log level + Level param.Field[AppLogParamsLevel] `json:"level,required"` + // Log message + Message param.Field[string] `json:"message,required"` + // Service name for the log entry + Service param.Field[string] `json:"service,required"` + // Additional metadata for the log entry + Extra param.Field[map[string]interface{}] `json:"extra"` +} + +func (r AppLogParams) MarshalJSON() (data []byte, err error) { + return apijson.MarshalRoot(r) +} + +// Log level +type AppLogParamsLevel string + +const ( + AppLogParamsLevelDebug AppLogParamsLevel = "debug" + AppLogParamsLevelInfo AppLogParamsLevel = "info" + AppLogParamsLevelError AppLogParamsLevel = "error" + AppLogParamsLevelWarn AppLogParamsLevel = "warn" +) + +func (r AppLogParamsLevel) IsKnown() bool { + switch r { + case AppLogParamsLevelDebug, AppLogParamsLevelInfo, AppLogParamsLevelError, AppLogParamsLevelWarn: + return true + } + return false +} diff --git a/packages/tui/sdk/app_test.go b/packages/tui/sdk/app_test.go index f96495f1..15f531ad 100644 --- a/packages/tui/sdk/app_test.go +++ b/packages/tui/sdk/app_test.go @@ -56,3 +56,32 @@ func TestAppInit(t *testing.T) { t.Fatalf("err should be nil: %s", err.Error()) } } + +func TestAppLogWithOptionalParams(t *testing.T) { + t.Skip("skipped: tests are disabled for the time being") + baseURL := "http://localhost:4010" + if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok { + baseURL = envURL + } + if !testutil.CheckTestServer(t, baseURL) { + return + } + client := opencode.NewClient( + option.WithBaseURL(baseURL), + ) + _, err := client.App.Log(context.TODO(), opencode.AppLogParams{ + Level: opencode.F(opencode.AppLogParamsLevelDebug), + Message: opencode.F("message"), + Service: opencode.F("service"), + Extra: opencode.F(map[string]interface{}{ + "foo": "bar", + }), + }) + if err != nil { + var apierr *opencode.Error + if errors.As(err, &apierr) { + t.Log(string(apierr.DumpRequest(true))) + } + t.Fatalf("err should be nil: %s", err.Error()) + } +} diff --git a/packages/tui/sdk/config.go b/packages/tui/sdk/config.go index 39da2f94..d6dc65f2 100644 --- a/packages/tui/sdk/config.go +++ b/packages/tui/sdk/config.go @@ -62,6 +62,8 @@ type Config struct { Instructions []string `json:"instructions"` // Custom keybind configurations Keybinds Keybinds `json:"keybinds"` + // Minimum log level to write to log files + LogLevel LogLevel `json:"log_level"` // MCP (Model Context Protocol) server configurations Mcp map[string]ConfigMcp `json:"mcp"` // Model to use in the format of provider/model, eg anthropic/claude-2 @@ -82,6 +84,7 @@ type configJSON struct { Experimental apijson.Field Instructions apijson.Field Keybinds apijson.Field + LogLevel apijson.Field Mcp apijson.Field Model apijson.Field Provider apijson.Field @@ -396,82 +399,99 @@ func (r configProviderModelsLimitJSON) RawJSON() string { type Keybinds struct { // Exit the application - AppExit string `json:"app_exit"` - // Open external editor - EditorOpen string `json:"editor_open"` + AppExit string `json:"app_exit,required"` // Show help dialog - Help string `json:"help"` - // Navigate to next history item - HistoryNext string `json:"history_next"` - // Navigate to previous history item - HistoryPrevious string `json:"history_previous"` + AppHelp string `json:"app_help,required"` + // Open external editor + EditorOpen string `json:"editor_open,required"` + // Close file + FileClose string `json:"file_close,required"` + // Split/unified diff + FileDiffToggle string `json:"file_diff_toggle,required"` + // List files + FileList string `json:"file_list,required"` + // Search file + FileSearch string `json:"file_search,required"` // Clear input field - InputClear string `json:"input_clear"` + InputClear string `json:"input_clear,required"` // Insert newline in input - InputNewline string `json:"input_newline"` + InputNewline string `json:"input_newline,required"` // Paste from clipboard - InputPaste string `json:"input_paste"` + InputPaste string `json:"input_paste,required"` // Submit input - InputSubmit string `json:"input_submit"` + InputSubmit string `json:"input_submit,required"` // Leader key for keybind combinations - Leader string `json:"leader"` + Leader string `json:"leader,required"` + // Copy message + MessagesCopy string `json:"messages_copy,required"` // Navigate to first message - MessagesFirst string `json:"messages_first"` + MessagesFirst string `json:"messages_first,required"` // Scroll messages down by half page - MessagesHalfPageDown string `json:"messages_half_page_down"` + MessagesHalfPageDown string `json:"messages_half_page_down,required"` // Scroll messages up by half page - MessagesHalfPageUp string `json:"messages_half_page_up"` + MessagesHalfPageUp string `json:"messages_half_page_up,required"` // Navigate to last message - MessagesLast string `json:"messages_last"` + MessagesLast string `json:"messages_last,required"` + // Toggle layout + MessagesLayoutToggle string `json:"messages_layout_toggle,required"` // Navigate to next message - MessagesNext string `json:"messages_next"` + MessagesNext string `json:"messages_next,required"` // Scroll messages down by one page - MessagesPageDown string `json:"messages_page_down"` + MessagesPageDown string `json:"messages_page_down,required"` // Scroll messages up by one page - MessagesPageUp string `json:"messages_page_up"` + MessagesPageUp string `json:"messages_page_up,required"` // Navigate to previous message - MessagesPrevious string `json:"messages_previous"` + MessagesPrevious string `json:"messages_previous,required"` + // Revert message + MessagesRevert string `json:"messages_revert,required"` // List available models - ModelList string `json:"model_list"` - // Initialize project configuration - ProjectInit string `json:"project_init"` - // Toggle compact mode for session - SessionCompact string `json:"session_compact"` + ModelList string `json:"model_list,required"` + // Create/update AGENTS.md + ProjectInit string `json:"project_init,required"` + // Compact the session + SessionCompact string `json:"session_compact,required"` // Interrupt current session - SessionInterrupt string `json:"session_interrupt"` + SessionInterrupt string `json:"session_interrupt,required"` // List all sessions - SessionList string `json:"session_list"` + SessionList string `json:"session_list,required"` // Create a new session - SessionNew string `json:"session_new"` + SessionNew string `json:"session_new,required"` // Share current session - SessionShare string `json:"session_share"` + SessionShare string `json:"session_share,required"` + // Unshare current session + SessionUnshare string `json:"session_unshare,required"` // List available themes - ThemeList string `json:"theme_list"` - // Show tool details - ToolDetails string `json:"tool_details"` + ThemeList string `json:"theme_list,required"` + // Toggle tool details + ToolDetails string `json:"tool_details,required"` JSON keybindsJSON `json:"-"` } // keybindsJSON contains the JSON metadata for the struct [Keybinds] type keybindsJSON struct { AppExit apijson.Field + AppHelp apijson.Field EditorOpen apijson.Field - Help apijson.Field - HistoryNext apijson.Field - HistoryPrevious apijson.Field + FileClose apijson.Field + FileDiffToggle apijson.Field + FileList apijson.Field + FileSearch apijson.Field InputClear apijson.Field InputNewline apijson.Field InputPaste apijson.Field InputSubmit apijson.Field Leader apijson.Field + MessagesCopy apijson.Field MessagesFirst apijson.Field MessagesHalfPageDown apijson.Field MessagesHalfPageUp apijson.Field MessagesLast apijson.Field + MessagesLayoutToggle apijson.Field MessagesNext apijson.Field MessagesPageDown apijson.Field MessagesPageUp apijson.Field MessagesPrevious apijson.Field + MessagesRevert apijson.Field ModelList apijson.Field ProjectInit apijson.Field SessionCompact apijson.Field @@ -479,6 +499,7 @@ type keybindsJSON struct { SessionList apijson.Field SessionNew apijson.Field SessionShare apijson.Field + SessionUnshare apijson.Field ThemeList apijson.Field ToolDetails apijson.Field raw string diff --git a/packages/tui/sdk/event.go b/packages/tui/sdk/event.go index ed92b2ae..8bbf636c 100644 --- a/packages/tui/sdk/event.go +++ b/packages/tui/sdk/event.go @@ -51,11 +51,11 @@ type EventListResponse struct { // [EventListResponseEventLspClientDiagnosticsProperties], // [EventListResponseEventPermissionUpdatedProperties], // [EventListResponseEventFileEditedProperties], - // [EventListResponseEventStorageWriteProperties], // [EventListResponseEventInstallationUpdatedProperties], // [EventListResponseEventMessageUpdatedProperties], // [EventListResponseEventMessageRemovedProperties], // [EventListResponseEventMessagePartUpdatedProperties], + // [EventListResponseEventStorageWriteProperties], // [EventListResponseEventSessionUpdatedProperties], // [EventListResponseEventSessionDeletedProperties], // [EventListResponseEventSessionIdleProperties], @@ -95,12 +95,12 @@ func (r *EventListResponse) UnmarshalJSON(data []byte) (err error) { // Possible runtime types of the union are // [EventListResponseEventLspClientDiagnostics], // [EventListResponseEventPermissionUpdated], [EventListResponseEventFileEdited], -// [EventListResponseEventStorageWrite], // [EventListResponseEventInstallationUpdated], // [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved], // [EventListResponseEventMessagePartUpdated], -// [EventListResponseEventSessionUpdated], [EventListResponseEventSessionDeleted], -// [EventListResponseEventSessionIdle], [EventListResponseEventSessionError], +// [EventListResponseEventStorageWrite], [EventListResponseEventSessionUpdated], +// [EventListResponseEventSessionDeleted], [EventListResponseEventSessionIdle], +// [EventListResponseEventSessionError], // [EventListResponseEventFileWatcherUpdated]. func (r EventListResponse) AsUnion() EventListResponseUnion { return r.union @@ -108,12 +108,12 @@ func (r EventListResponse) AsUnion() EventListResponseUnion { // Union satisfied by [EventListResponseEventLspClientDiagnostics], // [EventListResponseEventPermissionUpdated], [EventListResponseEventFileEdited], -// [EventListResponseEventStorageWrite], // [EventListResponseEventInstallationUpdated], // [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved], // [EventListResponseEventMessagePartUpdated], -// [EventListResponseEventSessionUpdated], [EventListResponseEventSessionDeleted], -// [EventListResponseEventSessionIdle], [EventListResponseEventSessionError] or +// [EventListResponseEventStorageWrite], [EventListResponseEventSessionUpdated], +// [EventListResponseEventSessionDeleted], [EventListResponseEventSessionIdle], +// [EventListResponseEventSessionError] or // [EventListResponseEventFileWatcherUpdated]. type EventListResponseUnion interface { implementsEventListResponse() @@ -138,11 +138,6 @@ func init() { Type: reflect.TypeOf(EventListResponseEventFileEdited{}), DiscriminatorValue: "file.edited", }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(EventListResponseEventStorageWrite{}), - DiscriminatorValue: "storage.write", - }, apijson.UnionVariant{ TypeFilter: gjson.JSON, Type: reflect.TypeOf(EventListResponseEventInstallationUpdated{}), @@ -163,6 +158,11 @@ func init() { Type: reflect.TypeOf(EventListResponseEventMessagePartUpdated{}), DiscriminatorValue: "message.part.updated", }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(EventListResponseEventStorageWrite{}), + DiscriminatorValue: "storage.write", + }, apijson.UnionVariant{ TypeFilter: gjson.JSON, Type: reflect.TypeOf(EventListResponseEventSessionUpdated{}), @@ -402,68 +402,6 @@ func (r EventListResponseEventFileEditedType) IsKnown() bool { return false } -type EventListResponseEventStorageWrite struct { - Properties EventListResponseEventStorageWriteProperties `json:"properties,required"` - Type EventListResponseEventStorageWriteType `json:"type,required"` - JSON eventListResponseEventStorageWriteJSON `json:"-"` -} - -// eventListResponseEventStorageWriteJSON contains the JSON metadata for the struct -// [EventListResponseEventStorageWrite] -type eventListResponseEventStorageWriteJSON struct { - Properties apijson.Field - Type apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *EventListResponseEventStorageWrite) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r eventListResponseEventStorageWriteJSON) RawJSON() string { - return r.raw -} - -func (r EventListResponseEventStorageWrite) implementsEventListResponse() {} - -type EventListResponseEventStorageWriteProperties struct { - Key string `json:"key,required"` - Content interface{} `json:"content"` - JSON eventListResponseEventStorageWritePropertiesJSON `json:"-"` -} - -// eventListResponseEventStorageWritePropertiesJSON contains the JSON metadata for -// the struct [EventListResponseEventStorageWriteProperties] -type eventListResponseEventStorageWritePropertiesJSON struct { - Key apijson.Field - Content apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *EventListResponseEventStorageWriteProperties) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r eventListResponseEventStorageWritePropertiesJSON) RawJSON() string { - return r.raw -} - -type EventListResponseEventStorageWriteType string - -const ( - EventListResponseEventStorageWriteTypeStorageWrite EventListResponseEventStorageWriteType = "storage.write" -) - -func (r EventListResponseEventStorageWriteType) IsKnown() bool { - switch r { - case EventListResponseEventStorageWriteTypeStorageWrite: - return true - } - return false -} - type EventListResponseEventInstallationUpdated struct { Properties EventListResponseEventInstallationUpdatedProperties `json:"properties,required"` Type EventListResponseEventInstallationUpdatedType `json:"type,required"` @@ -673,7 +611,7 @@ func (r EventListResponseEventMessagePartUpdated) implementsEventListResponse() type EventListResponseEventMessagePartUpdatedProperties struct { MessageID string `json:"messageID,required"` - Part MessagePart `json:"part,required"` + Part AssistantMessagePart `json:"part,required"` SessionID string `json:"sessionID,required"` JSON eventListResponseEventMessagePartUpdatedPropertiesJSON `json:"-"` } @@ -710,6 +648,68 @@ func (r EventListResponseEventMessagePartUpdatedType) IsKnown() bool { return false } +type EventListResponseEventStorageWrite struct { + Properties EventListResponseEventStorageWriteProperties `json:"properties,required"` + Type EventListResponseEventStorageWriteType `json:"type,required"` + JSON eventListResponseEventStorageWriteJSON `json:"-"` +} + +// eventListResponseEventStorageWriteJSON contains the JSON metadata for the struct +// [EventListResponseEventStorageWrite] +type eventListResponseEventStorageWriteJSON struct { + Properties apijson.Field + Type apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *EventListResponseEventStorageWrite) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r eventListResponseEventStorageWriteJSON) RawJSON() string { + return r.raw +} + +func (r EventListResponseEventStorageWrite) implementsEventListResponse() {} + +type EventListResponseEventStorageWriteProperties struct { + Key string `json:"key,required"` + Content interface{} `json:"content"` + JSON eventListResponseEventStorageWritePropertiesJSON `json:"-"` +} + +// eventListResponseEventStorageWritePropertiesJSON contains the JSON metadata for +// the struct [EventListResponseEventStorageWriteProperties] +type eventListResponseEventStorageWritePropertiesJSON struct { + Key apijson.Field + Content apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *EventListResponseEventStorageWriteProperties) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r eventListResponseEventStorageWritePropertiesJSON) RawJSON() string { + return r.raw +} + +type EventListResponseEventStorageWriteType string + +const ( + EventListResponseEventStorageWriteTypeStorageWrite EventListResponseEventStorageWriteType = "storage.write" +) + +func (r EventListResponseEventStorageWriteType) IsKnown() bool { + switch r { + case EventListResponseEventStorageWriteTypeStorageWrite: + return true + } + return false +} + type EventListResponseEventSessionUpdated struct { Properties EventListResponseEventSessionUpdatedProperties `json:"properties,required"` Type EventListResponseEventSessionUpdatedType `json:"type,required"` @@ -916,14 +916,16 @@ func (r eventListResponseEventSessionErrorJSON) RawJSON() string { func (r EventListResponseEventSessionError) implementsEventListResponse() {} type EventListResponseEventSessionErrorProperties struct { - Error EventListResponseEventSessionErrorPropertiesError `json:"error"` - JSON eventListResponseEventSessionErrorPropertiesJSON `json:"-"` + Error EventListResponseEventSessionErrorPropertiesError `json:"error"` + SessionID string `json:"sessionID"` + JSON eventListResponseEventSessionErrorPropertiesJSON `json:"-"` } // eventListResponseEventSessionErrorPropertiesJSON contains the JSON metadata for // the struct [EventListResponseEventSessionErrorProperties] type eventListResponseEventSessionErrorPropertiesJSON struct { Error apijson.Field + SessionID apijson.Field raw string ExtraFields map[string]apijson.Field } @@ -972,13 +974,15 @@ func (r *EventListResponseEventSessionErrorPropertiesError) UnmarshalJSON(data [ // // Possible runtime types of the union are [shared.ProviderAuthError], // [shared.UnknownError], -// [EventListResponseEventSessionErrorPropertiesErrorMessageOutputLengthError]. +// [EventListResponseEventSessionErrorPropertiesErrorMessageOutputLengthError], +// [shared.MessageAbortedError]. func (r EventListResponseEventSessionErrorPropertiesError) AsUnion() EventListResponseEventSessionErrorPropertiesErrorUnion { return r.union } -// Union satisfied by [shared.ProviderAuthError], [shared.UnknownError] or -// [EventListResponseEventSessionErrorPropertiesErrorMessageOutputLengthError]. +// Union satisfied by [shared.ProviderAuthError], [shared.UnknownError], +// [EventListResponseEventSessionErrorPropertiesErrorMessageOutputLengthError] or +// [shared.MessageAbortedError]. type EventListResponseEventSessionErrorPropertiesErrorUnion interface { ImplementsEventListResponseEventSessionErrorPropertiesError() } @@ -1002,6 +1006,11 @@ func init() { Type: reflect.TypeOf(EventListResponseEventSessionErrorPropertiesErrorMessageOutputLengthError{}), DiscriminatorValue: "MessageOutputLengthError", }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(shared.MessageAbortedError{}), + DiscriminatorValue: "MessageAbortedError", + }, ) } @@ -1052,11 +1061,12 @@ const ( EventListResponseEventSessionErrorPropertiesErrorNameProviderAuthError EventListResponseEventSessionErrorPropertiesErrorName = "ProviderAuthError" EventListResponseEventSessionErrorPropertiesErrorNameUnknownError EventListResponseEventSessionErrorPropertiesErrorName = "UnknownError" EventListResponseEventSessionErrorPropertiesErrorNameMessageOutputLengthError EventListResponseEventSessionErrorPropertiesErrorName = "MessageOutputLengthError" + EventListResponseEventSessionErrorPropertiesErrorNameMessageAbortedError EventListResponseEventSessionErrorPropertiesErrorName = "MessageAbortedError" ) func (r EventListResponseEventSessionErrorPropertiesErrorName) IsKnown() bool { switch r { - case EventListResponseEventSessionErrorPropertiesErrorNameProviderAuthError, EventListResponseEventSessionErrorPropertiesErrorNameUnknownError, EventListResponseEventSessionErrorPropertiesErrorNameMessageOutputLengthError: + case EventListResponseEventSessionErrorPropertiesErrorNameProviderAuthError, EventListResponseEventSessionErrorPropertiesErrorNameUnknownError, EventListResponseEventSessionErrorPropertiesErrorNameMessageOutputLengthError, EventListResponseEventSessionErrorPropertiesErrorNameMessageAbortedError: return true } return false @@ -1159,11 +1169,11 @@ const ( EventListResponseTypeLspClientDiagnostics EventListResponseType = "lsp.client.diagnostics" EventListResponseTypePermissionUpdated EventListResponseType = "permission.updated" EventListResponseTypeFileEdited EventListResponseType = "file.edited" - EventListResponseTypeStorageWrite EventListResponseType = "storage.write" EventListResponseTypeInstallationUpdated EventListResponseType = "installation.updated" EventListResponseTypeMessageUpdated EventListResponseType = "message.updated" EventListResponseTypeMessageRemoved EventListResponseType = "message.removed" EventListResponseTypeMessagePartUpdated EventListResponseType = "message.part.updated" + EventListResponseTypeStorageWrite EventListResponseType = "storage.write" EventListResponseTypeSessionUpdated EventListResponseType = "session.updated" EventListResponseTypeSessionDeleted EventListResponseType = "session.deleted" EventListResponseTypeSessionIdle EventListResponseType = "session.idle" @@ -1173,7 +1183,7 @@ const ( func (r EventListResponseType) IsKnown() bool { switch r { - case EventListResponseTypeLspClientDiagnostics, EventListResponseTypePermissionUpdated, EventListResponseTypeFileEdited, EventListResponseTypeStorageWrite, EventListResponseTypeInstallationUpdated, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeFileWatcherUpdated: + case EventListResponseTypeLspClientDiagnostics, EventListResponseTypePermissionUpdated, EventListResponseTypeFileEdited, EventListResponseTypeInstallationUpdated, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeStorageWrite, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeFileWatcherUpdated: return true } return false diff --git a/packages/tui/sdk/file.go b/packages/tui/sdk/file.go index a9d6f018..0a8a4b2b 100644 --- a/packages/tui/sdk/file.go +++ b/packages/tui/sdk/file.go @@ -42,13 +42,55 @@ func (r *FileService) Read(ctx context.Context, query FileReadParams, opts ...op } // Get file status -func (r *FileService) Status(ctx context.Context, opts ...option.RequestOption) (res *[]FileStatusResponse, err error) { +func (r *FileService) Status(ctx context.Context, opts ...option.RequestOption) (res *[]File, err error) { opts = append(r.Options[:], opts...) path := "file/status" err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...) return } +type File struct { + Added int64 `json:"added,required"` + Path string `json:"path,required"` + Removed int64 `json:"removed,required"` + Status FileStatus `json:"status,required"` + JSON fileJSON `json:"-"` +} + +// fileJSON contains the JSON metadata for the struct [File] +type fileJSON struct { + Added apijson.Field + Path apijson.Field + Removed apijson.Field + Status apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *File) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r fileJSON) RawJSON() string { + return r.raw +} + +type FileStatus string + +const ( + FileStatusAdded FileStatus = "added" + FileStatusDeleted FileStatus = "deleted" + FileStatusModified FileStatus = "modified" +) + +func (r FileStatus) IsKnown() bool { + switch r { + case FileStatusAdded, FileStatusDeleted, FileStatusModified: + return true + } + return false +} + type FileReadResponse struct { Content string `json:"content,required"` Type FileReadResponseType `json:"type,required"` @@ -87,49 +129,6 @@ func (r FileReadResponseType) IsKnown() bool { return false } -type FileStatusResponse struct { - Added int64 `json:"added,required"` - File string `json:"file,required"` - Removed int64 `json:"removed,required"` - Status FileStatusResponseStatus `json:"status,required"` - JSON fileStatusResponseJSON `json:"-"` -} - -// fileStatusResponseJSON contains the JSON metadata for the struct -// [FileStatusResponse] -type fileStatusResponseJSON struct { - Added apijson.Field - File apijson.Field - Removed apijson.Field - Status apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *FileStatusResponse) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r fileStatusResponseJSON) RawJSON() string { - return r.raw -} - -type FileStatusResponseStatus string - -const ( - FileStatusResponseStatusAdded FileStatusResponseStatus = "added" - FileStatusResponseStatusDeleted FileStatusResponseStatus = "deleted" - FileStatusResponseStatusModified FileStatusResponseStatus = "modified" -) - -func (r FileStatusResponseStatus) IsKnown() bool { - switch r { - case FileStatusResponseStatusAdded, FileStatusResponseStatusDeleted, FileStatusResponseStatusModified: - return true - } - return false -} - type FileReadParams struct { Path param.Field[string] `query:"path,required"` } diff --git a/packages/tui/sdk/find.go b/packages/tui/sdk/find.go index bbd6b680..10f92fc0 100644 --- a/packages/tui/sdk/find.go +++ b/packages/tui/sdk/find.go @@ -42,7 +42,7 @@ func (r *FindService) Files(ctx context.Context, query FindFilesParams, opts ... } // Find workspace symbols -func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts ...option.RequestOption) (res *[]FindSymbolsResponse, err error) { +func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts ...option.RequestOption) (res *[]Symbol, err error) { opts = append(r.Options[:], opts...) path := "find/symbol" err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...) @@ -50,27 +50,24 @@ func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts } // Find text in files -func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]FindTextResponse, err error) { +func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]Match, err error) { opts = append(r.Options[:], opts...) path := "find" err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...) return } -type FindSymbolsResponse = interface{} - -type FindTextResponse struct { - AbsoluteOffset float64 `json:"absolute_offset,required"` - LineNumber float64 `json:"line_number,required"` - Lines FindTextResponseLines `json:"lines,required"` - Path FindTextResponsePath `json:"path,required"` - Submatches []FindTextResponseSubmatch `json:"submatches,required"` - JSON findTextResponseJSON `json:"-"` +type Match struct { + AbsoluteOffset float64 `json:"absolute_offset,required"` + LineNumber float64 `json:"line_number,required"` + Lines MatchLines `json:"lines,required"` + Path MatchPath `json:"path,required"` + Submatches []MatchSubmatch `json:"submatches,required"` + JSON matchJSON `json:"-"` } -// findTextResponseJSON contains the JSON metadata for the struct -// [FindTextResponse] -type findTextResponseJSON struct { +// matchJSON contains the JSON metadata for the struct [Match] +type matchJSON struct { AbsoluteOffset apijson.Field LineNumber apijson.Field Lines apijson.Field @@ -80,66 +77,63 @@ type findTextResponseJSON struct { ExtraFields map[string]apijson.Field } -func (r *FindTextResponse) UnmarshalJSON(data []byte) (err error) { +func (r *Match) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r findTextResponseJSON) RawJSON() string { +func (r matchJSON) RawJSON() string { return r.raw } -type FindTextResponseLines struct { - Text string `json:"text,required"` - JSON findTextResponseLinesJSON `json:"-"` +type MatchLines struct { + Text string `json:"text,required"` + JSON matchLinesJSON `json:"-"` } -// findTextResponseLinesJSON contains the JSON metadata for the struct -// [FindTextResponseLines] -type findTextResponseLinesJSON struct { +// matchLinesJSON contains the JSON metadata for the struct [MatchLines] +type matchLinesJSON struct { Text apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *FindTextResponseLines) UnmarshalJSON(data []byte) (err error) { +func (r *MatchLines) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r findTextResponseLinesJSON) RawJSON() string { +func (r matchLinesJSON) RawJSON() string { return r.raw } -type FindTextResponsePath struct { - Text string `json:"text,required"` - JSON findTextResponsePathJSON `json:"-"` +type MatchPath struct { + Text string `json:"text,required"` + JSON matchPathJSON `json:"-"` } -// findTextResponsePathJSON contains the JSON metadata for the struct -// [FindTextResponsePath] -type findTextResponsePathJSON struct { +// matchPathJSON contains the JSON metadata for the struct [MatchPath] +type matchPathJSON struct { Text apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *FindTextResponsePath) UnmarshalJSON(data []byte) (err error) { +func (r *MatchPath) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r findTextResponsePathJSON) RawJSON() string { +func (r matchPathJSON) RawJSON() string { return r.raw } -type FindTextResponseSubmatch struct { - End float64 `json:"end,required"` - Match FindTextResponseSubmatchesMatch `json:"match,required"` - Start float64 `json:"start,required"` - JSON findTextResponseSubmatchJSON `json:"-"` +type MatchSubmatch struct { + End float64 `json:"end,required"` + Match MatchSubmatchesMatch `json:"match,required"` + Start float64 `json:"start,required"` + JSON matchSubmatchJSON `json:"-"` } -// findTextResponseSubmatchJSON contains the JSON metadata for the struct -// [FindTextResponseSubmatch] -type findTextResponseSubmatchJSON struct { +// matchSubmatchJSON contains the JSON metadata for the struct [MatchSubmatch] +type matchSubmatchJSON struct { End apijson.Field Match apijson.Field Start apijson.Field @@ -147,32 +141,147 @@ type findTextResponseSubmatchJSON struct { ExtraFields map[string]apijson.Field } -func (r *FindTextResponseSubmatch) UnmarshalJSON(data []byte) (err error) { +func (r *MatchSubmatch) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r findTextResponseSubmatchJSON) RawJSON() string { +func (r matchSubmatchJSON) RawJSON() string { return r.raw } -type FindTextResponseSubmatchesMatch struct { - Text string `json:"text,required"` - JSON findTextResponseSubmatchesMatchJSON `json:"-"` +type MatchSubmatchesMatch struct { + Text string `json:"text,required"` + JSON matchSubmatchesMatchJSON `json:"-"` } -// findTextResponseSubmatchesMatchJSON contains the JSON metadata for the struct -// [FindTextResponseSubmatchesMatch] -type findTextResponseSubmatchesMatchJSON struct { +// matchSubmatchesMatchJSON contains the JSON metadata for the struct +// [MatchSubmatchesMatch] +type matchSubmatchesMatchJSON struct { Text apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *FindTextResponseSubmatchesMatch) UnmarshalJSON(data []byte) (err error) { +func (r *MatchSubmatchesMatch) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r findTextResponseSubmatchesMatchJSON) RawJSON() string { +func (r matchSubmatchesMatchJSON) RawJSON() string { + return r.raw +} + +type Symbol struct { + Kind float64 `json:"kind,required"` + Location SymbolLocation `json:"location,required"` + Name string `json:"name,required"` + JSON symbolJSON `json:"-"` +} + +// symbolJSON contains the JSON metadata for the struct [Symbol] +type symbolJSON struct { + Kind apijson.Field + Location apijson.Field + Name apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *Symbol) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r symbolJSON) RawJSON() string { + return r.raw +} + +type SymbolLocation struct { + Range SymbolLocationRange `json:"range,required"` + Uri string `json:"uri,required"` + JSON symbolLocationJSON `json:"-"` +} + +// symbolLocationJSON contains the JSON metadata for the struct [SymbolLocation] +type symbolLocationJSON struct { + Range apijson.Field + Uri apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *SymbolLocation) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r symbolLocationJSON) RawJSON() string { + return r.raw +} + +type SymbolLocationRange struct { + End SymbolLocationRangeEnd `json:"end,required"` + Start SymbolLocationRangeStart `json:"start,required"` + JSON symbolLocationRangeJSON `json:"-"` +} + +// symbolLocationRangeJSON contains the JSON metadata for the struct +// [SymbolLocationRange] +type symbolLocationRangeJSON struct { + End apijson.Field + Start apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *SymbolLocationRange) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r symbolLocationRangeJSON) RawJSON() string { + return r.raw +} + +type SymbolLocationRangeEnd struct { + Character float64 `json:"character,required"` + Line float64 `json:"line,required"` + JSON symbolLocationRangeEndJSON `json:"-"` +} + +// symbolLocationRangeEndJSON contains the JSON metadata for the struct +// [SymbolLocationRangeEnd] +type symbolLocationRangeEndJSON struct { + Character apijson.Field + Line apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *SymbolLocationRangeEnd) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r symbolLocationRangeEndJSON) RawJSON() string { + return r.raw +} + +type SymbolLocationRangeStart struct { + Character float64 `json:"character,required"` + Line float64 `json:"line,required"` + JSON symbolLocationRangeStartJSON `json:"-"` +} + +// symbolLocationRangeStartJSON contains the JSON metadata for the struct +// [SymbolLocationRangeStart] +type symbolLocationRangeStartJSON struct { + Character apijson.Field + Line apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *SymbolLocationRangeStart) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r symbolLocationRangeStartJSON) RawJSON() string { return r.raw } diff --git a/packages/tui/sdk/packages/ssestream/ssestream.go b/packages/tui/sdk/packages/ssestream/ssestream.go index 81adbd69..cc0afb7b 100644 --- a/packages/tui/sdk/packages/ssestream/ssestream.go +++ b/packages/tui/sdk/packages/ssestream/ssestream.go @@ -29,7 +29,7 @@ func NewDecoder(res *http.Response) Decoder { decoder = t(res.Body) } else { scn := bufio.NewScanner(res.Body) - scn.Buffer(nil, bufio.MaxScanTokenSize<<4) + scn.Buffer(nil, bufio.MaxScanTokenSize<<9) decoder = &eventStreamDecoder{rc: res.Body, scn: scn} } return decoder diff --git a/packages/tui/sdk/scripts/lint b/packages/tui/sdk/scripts/lint index fa7ba1f6..9f37abf2 100755 --- a/packages/tui/sdk/scripts/lint +++ b/packages/tui/sdk/scripts/lint @@ -5,4 +5,7 @@ set -e cd "$(dirname "$0")/.." echo "==> Running Go build" -go build ./... +go build . + +echo "==> Checking tests compile" +go test -run=^$ . diff --git a/packages/tui/sdk/session.go b/packages/tui/sdk/session.go index e8216a1f..fc55c691 100644 --- a/packages/tui/sdk/session.go +++ b/packages/tui/sdk/session.go @@ -77,7 +77,7 @@ func (r *SessionService) Abort(ctx context.Context, id string, opts ...option.Re } // Create and send a new message to a session -func (r *SessionService) Chat(ctx context.Context, id string, body SessionChatParams, opts ...option.RequestOption) (res *Message, err error) { +func (r *SessionService) Chat(ctx context.Context, id string, body SessionChatParams, opts ...option.RequestOption) (res *AssistantMessage, err error) { opts = append(r.Options[:], opts...) if id == "" { err = errors.New("missing required id parameter") @@ -148,17 +148,391 @@ func (r *SessionService) Unshare(ctx context.Context, id string, opts ...option. return } +type AssistantMessage struct { + ID string `json:"id,required"` + Cost float64 `json:"cost,required"` + ModelID string `json:"modelID,required"` + Parts []AssistantMessagePart `json:"parts,required"` + Path AssistantMessagePath `json:"path,required"` + ProviderID string `json:"providerID,required"` + Role AssistantMessageRole `json:"role,required"` + SessionID string `json:"sessionID,required"` + System []string `json:"system,required"` + Time AssistantMessageTime `json:"time,required"` + Tokens AssistantMessageTokens `json:"tokens,required"` + Error AssistantMessageError `json:"error"` + Summary bool `json:"summary"` + JSON assistantMessageJSON `json:"-"` +} + +// assistantMessageJSON contains the JSON metadata for the struct +// [AssistantMessage] +type assistantMessageJSON struct { + ID apijson.Field + Cost apijson.Field + ModelID apijson.Field + Parts apijson.Field + Path apijson.Field + ProviderID apijson.Field + Role apijson.Field + SessionID apijson.Field + System apijson.Field + Time apijson.Field + Tokens apijson.Field + Error apijson.Field + Summary apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessage) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessageJSON) RawJSON() string { + return r.raw +} + +func (r AssistantMessage) implementsMessage() {} + +type AssistantMessagePath struct { + Cwd string `json:"cwd,required"` + Root string `json:"root,required"` + JSON assistantMessagePathJSON `json:"-"` +} + +// assistantMessagePathJSON contains the JSON metadata for the struct +// [AssistantMessagePath] +type assistantMessagePathJSON struct { + Cwd apijson.Field + Root apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessagePath) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessagePathJSON) RawJSON() string { + return r.raw +} + +type AssistantMessageRole string + +const ( + AssistantMessageRoleAssistant AssistantMessageRole = "assistant" +) + +func (r AssistantMessageRole) IsKnown() bool { + switch r { + case AssistantMessageRoleAssistant: + return true + } + return false +} + +type AssistantMessageTime struct { + Created float64 `json:"created,required"` + Completed float64 `json:"completed"` + JSON assistantMessageTimeJSON `json:"-"` +} + +// assistantMessageTimeJSON contains the JSON metadata for the struct +// [AssistantMessageTime] +type assistantMessageTimeJSON struct { + Created apijson.Field + Completed apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessageTime) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessageTimeJSON) RawJSON() string { + return r.raw +} + +type AssistantMessageTokens struct { + Cache AssistantMessageTokensCache `json:"cache,required"` + Input float64 `json:"input,required"` + Output float64 `json:"output,required"` + Reasoning float64 `json:"reasoning,required"` + JSON assistantMessageTokensJSON `json:"-"` +} + +// assistantMessageTokensJSON contains the JSON metadata for the struct +// [AssistantMessageTokens] +type assistantMessageTokensJSON struct { + Cache apijson.Field + Input apijson.Field + Output apijson.Field + Reasoning apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessageTokens) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessageTokensJSON) RawJSON() string { + return r.raw +} + +type AssistantMessageTokensCache struct { + Read float64 `json:"read,required"` + Write float64 `json:"write,required"` + JSON assistantMessageTokensCacheJSON `json:"-"` +} + +// assistantMessageTokensCacheJSON contains the JSON metadata for the struct +// [AssistantMessageTokensCache] +type assistantMessageTokensCacheJSON struct { + Read apijson.Field + Write apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessageTokensCache) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessageTokensCacheJSON) RawJSON() string { + return r.raw +} + +type AssistantMessageError struct { + // This field can have the runtime type of [shared.ProviderAuthErrorData], + // [shared.UnknownErrorData], [interface{}]. + Data interface{} `json:"data,required"` + Name AssistantMessageErrorName `json:"name,required"` + JSON assistantMessageErrorJSON `json:"-"` + union AssistantMessageErrorUnion +} + +// assistantMessageErrorJSON contains the JSON metadata for the struct +// [AssistantMessageError] +type assistantMessageErrorJSON struct { + Data apijson.Field + Name apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r assistantMessageErrorJSON) RawJSON() string { + return r.raw +} + +func (r *AssistantMessageError) UnmarshalJSON(data []byte) (err error) { + *r = AssistantMessageError{} + err = apijson.UnmarshalRoot(data, &r.union) + if err != nil { + return err + } + return apijson.Port(r.union, &r) +} + +// AsUnion returns a [AssistantMessageErrorUnion] interface which you can cast to +// the specific types for more type safety. +// +// Possible runtime types of the union are [shared.ProviderAuthError], +// [shared.UnknownError], [AssistantMessageErrorMessageOutputLengthError], +// [shared.MessageAbortedError]. +func (r AssistantMessageError) AsUnion() AssistantMessageErrorUnion { + return r.union +} + +// Union satisfied by [shared.ProviderAuthError], [shared.UnknownError], +// [AssistantMessageErrorMessageOutputLengthError] or [shared.MessageAbortedError]. +type AssistantMessageErrorUnion interface { + ImplementsAssistantMessageError() +} + +func init() { + apijson.RegisterUnion( + reflect.TypeOf((*AssistantMessageErrorUnion)(nil)).Elem(), + "name", + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(shared.ProviderAuthError{}), + DiscriminatorValue: "ProviderAuthError", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(shared.UnknownError{}), + DiscriminatorValue: "UnknownError", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(AssistantMessageErrorMessageOutputLengthError{}), + DiscriminatorValue: "MessageOutputLengthError", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(shared.MessageAbortedError{}), + DiscriminatorValue: "MessageAbortedError", + }, + ) +} + +type AssistantMessageErrorMessageOutputLengthError struct { + Data interface{} `json:"data,required"` + Name AssistantMessageErrorMessageOutputLengthErrorName `json:"name,required"` + JSON assistantMessageErrorMessageOutputLengthErrorJSON `json:"-"` +} + +// assistantMessageErrorMessageOutputLengthErrorJSON contains the JSON metadata for +// the struct [AssistantMessageErrorMessageOutputLengthError] +type assistantMessageErrorMessageOutputLengthErrorJSON struct { + Data apijson.Field + Name apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *AssistantMessageErrorMessageOutputLengthError) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r assistantMessageErrorMessageOutputLengthErrorJSON) RawJSON() string { + return r.raw +} + +func (r AssistantMessageErrorMessageOutputLengthError) ImplementsAssistantMessageError() {} + +type AssistantMessageErrorMessageOutputLengthErrorName string + +const ( + AssistantMessageErrorMessageOutputLengthErrorNameMessageOutputLengthError AssistantMessageErrorMessageOutputLengthErrorName = "MessageOutputLengthError" +) + +func (r AssistantMessageErrorMessageOutputLengthErrorName) IsKnown() bool { + switch r { + case AssistantMessageErrorMessageOutputLengthErrorNameMessageOutputLengthError: + return true + } + return false +} + +type AssistantMessageErrorName string + +const ( + AssistantMessageErrorNameProviderAuthError AssistantMessageErrorName = "ProviderAuthError" + AssistantMessageErrorNameUnknownError AssistantMessageErrorName = "UnknownError" + AssistantMessageErrorNameMessageOutputLengthError AssistantMessageErrorName = "MessageOutputLengthError" + AssistantMessageErrorNameMessageAbortedError AssistantMessageErrorName = "MessageAbortedError" +) + +func (r AssistantMessageErrorName) IsKnown() bool { + switch r { + case AssistantMessageErrorNameProviderAuthError, AssistantMessageErrorNameUnknownError, AssistantMessageErrorNameMessageOutputLengthError, AssistantMessageErrorNameMessageAbortedError: + return true + } + return false +} + +type AssistantMessagePart struct { + Type AssistantMessagePartType `json:"type,required"` + ID string `json:"id"` + // This field can have the runtime type of [ToolPartState]. + State interface{} `json:"state"` + Text string `json:"text"` + Tool string `json:"tool"` + JSON assistantMessagePartJSON `json:"-"` + union AssistantMessagePartUnion +} + +// assistantMessagePartJSON contains the JSON metadata for the struct +// [AssistantMessagePart] +type assistantMessagePartJSON struct { + Type apijson.Field + ID apijson.Field + State apijson.Field + Text apijson.Field + Tool apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r assistantMessagePartJSON) RawJSON() string { + return r.raw +} + +func (r *AssistantMessagePart) UnmarshalJSON(data []byte) (err error) { + *r = AssistantMessagePart{} + err = apijson.UnmarshalRoot(data, &r.union) + if err != nil { + return err + } + return apijson.Port(r.union, &r) +} + +// AsUnion returns a [AssistantMessagePartUnion] interface which you can cast to +// the specific types for more type safety. +// +// Possible runtime types of the union are [TextPart], [ToolPart], [StepStartPart]. +func (r AssistantMessagePart) AsUnion() AssistantMessagePartUnion { + return r.union +} + +// Union satisfied by [TextPart], [ToolPart] or [StepStartPart]. +type AssistantMessagePartUnion interface { + implementsAssistantMessagePart() +} + +func init() { + apijson.RegisterUnion( + reflect.TypeOf((*AssistantMessagePartUnion)(nil)).Elem(), + "type", + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(TextPart{}), + DiscriminatorValue: "text", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(ToolPart{}), + DiscriminatorValue: "tool", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(StepStartPart{}), + DiscriminatorValue: "step-start", + }, + ) +} + +type AssistantMessagePartType string + +const ( + AssistantMessagePartTypeText AssistantMessagePartType = "text" + AssistantMessagePartTypeTool AssistantMessagePartType = "tool" + AssistantMessagePartTypeStepStart AssistantMessagePartType = "step-start" +) + +func (r AssistantMessagePartType) IsKnown() bool { + switch r { + case AssistantMessagePartTypeText, AssistantMessagePartTypeTool, AssistantMessagePartTypeStepStart: + return true + } + return false +} + type FilePart struct { - MediaType string `json:"mediaType,required"` - Type FilePartType `json:"type,required"` - URL string `json:"url,required"` - Filename string `json:"filename"` - JSON filePartJSON `json:"-"` + Mime string `json:"mime,required"` + Type FilePartType `json:"type,required"` + URL string `json:"url,required"` + Filename string `json:"filename"` + JSON filePartJSON `json:"-"` } // filePartJSON contains the JSON metadata for the struct [FilePart] type filePartJSON struct { - MediaType apijson.Field + Mime apijson.Field Type apijson.Field URL apijson.Field Filename apijson.Field @@ -174,7 +548,7 @@ func (r filePartJSON) RawJSON() string { return r.raw } -func (r FilePart) implementsMessagePart() {} +func (r FilePart) implementsUserMessagePart() {} type FilePartType string @@ -191,276 +565,69 @@ func (r FilePartType) IsKnown() bool { } type FilePartParam struct { - MediaType param.Field[string] `json:"mediaType,required"` - Type param.Field[FilePartType] `json:"type,required"` - URL param.Field[string] `json:"url,required"` - Filename param.Field[string] `json:"filename"` + Mime param.Field[string] `json:"mime,required"` + Type param.Field[FilePartType] `json:"type,required"` + URL param.Field[string] `json:"url,required"` + Filename param.Field[string] `json:"filename"` } func (r FilePartParam) MarshalJSON() (data []byte, err error) { return apijson.MarshalRoot(r) } -func (r FilePartParam) implementsMessagePartUnionParam() {} +func (r FilePartParam) implementsUserMessagePartUnionParam() {} type Message struct { - ID string `json:"id,required"` - Metadata MessageMetadata `json:"metadata,required"` - Parts []MessagePart `json:"parts,required"` - Role MessageRole `json:"role,required"` - JSON messageJSON `json:"-"` + ID string `json:"id,required"` + // This field can have the runtime type of [[]UserMessagePart], + // [[]AssistantMessagePart]. + Parts interface{} `json:"parts,required"` + Role MessageRole `json:"role,required"` + SessionID string `json:"sessionID,required"` + // This field can have the runtime type of [UserMessageTime], + // [AssistantMessageTime]. + Time interface{} `json:"time,required"` + Cost float64 `json:"cost"` + // This field can have the runtime type of [AssistantMessageError]. + Error interface{} `json:"error"` + ModelID string `json:"modelID"` + // This field can have the runtime type of [AssistantMessagePath]. + Path interface{} `json:"path"` + ProviderID string `json:"providerID"` + Summary bool `json:"summary"` + // This field can have the runtime type of [[]string]. + System interface{} `json:"system"` + // This field can have the runtime type of [AssistantMessageTokens]. + Tokens interface{} `json:"tokens"` + JSON messageJSON `json:"-"` + union MessageUnion } // messageJSON contains the JSON metadata for the struct [Message] type messageJSON struct { ID apijson.Field - Metadata apijson.Field Parts apijson.Field Role apijson.Field + SessionID apijson.Field + Time apijson.Field + Cost apijson.Field + Error apijson.Field + ModelID apijson.Field + Path apijson.Field + ProviderID apijson.Field + Summary apijson.Field + System apijson.Field + Tokens apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *Message) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - func (r messageJSON) RawJSON() string { return r.raw } -type MessageMetadata struct { - SessionID string `json:"sessionID,required"` - Time MessageMetadataTime `json:"time,required"` - Tool map[string]MessageMetadataTool `json:"tool,required"` - Assistant MessageMetadataAssistant `json:"assistant"` - Error MessageMetadataError `json:"error"` - Snapshot string `json:"snapshot"` - JSON messageMetadataJSON `json:"-"` -} - -// messageMetadataJSON contains the JSON metadata for the struct [MessageMetadata] -type messageMetadataJSON struct { - SessionID apijson.Field - Time apijson.Field - Tool apijson.Field - Assistant apijson.Field - Error apijson.Field - Snapshot apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadata) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataTime struct { - Created float64 `json:"created,required"` - Completed float64 `json:"completed"` - JSON messageMetadataTimeJSON `json:"-"` -} - -// messageMetadataTimeJSON contains the JSON metadata for the struct -// [MessageMetadataTime] -type messageMetadataTimeJSON struct { - Created apijson.Field - Completed apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataTime) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataTimeJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataTool struct { - Time MessageMetadataToolTime `json:"time,required"` - Title string `json:"title,required"` - Snapshot string `json:"snapshot"` - ExtraFields map[string]interface{} `json:"-,extras"` - JSON messageMetadataToolJSON `json:"-"` -} - -// messageMetadataToolJSON contains the JSON metadata for the struct -// [MessageMetadataTool] -type messageMetadataToolJSON struct { - Time apijson.Field - Title apijson.Field - Snapshot apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataTool) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataToolJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataToolTime struct { - End float64 `json:"end,required"` - Start float64 `json:"start,required"` - JSON messageMetadataToolTimeJSON `json:"-"` -} - -// messageMetadataToolTimeJSON contains the JSON metadata for the struct -// [MessageMetadataToolTime] -type messageMetadataToolTimeJSON struct { - End apijson.Field - Start apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataToolTime) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataToolTimeJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataAssistant struct { - Cost float64 `json:"cost,required"` - ModelID string `json:"modelID,required"` - Path MessageMetadataAssistantPath `json:"path,required"` - ProviderID string `json:"providerID,required"` - System []string `json:"system,required"` - Tokens MessageMetadataAssistantTokens `json:"tokens,required"` - Summary bool `json:"summary"` - JSON messageMetadataAssistantJSON `json:"-"` -} - -// messageMetadataAssistantJSON contains the JSON metadata for the struct -// [MessageMetadataAssistant] -type messageMetadataAssistantJSON struct { - Cost apijson.Field - ModelID apijson.Field - Path apijson.Field - ProviderID apijson.Field - System apijson.Field - Tokens apijson.Field - Summary apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataAssistant) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataAssistantJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataAssistantPath struct { - Cwd string `json:"cwd,required"` - Root string `json:"root,required"` - JSON messageMetadataAssistantPathJSON `json:"-"` -} - -// messageMetadataAssistantPathJSON contains the JSON metadata for the struct -// [MessageMetadataAssistantPath] -type messageMetadataAssistantPathJSON struct { - Cwd apijson.Field - Root apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataAssistantPath) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataAssistantPathJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataAssistantTokens struct { - Cache MessageMetadataAssistantTokensCache `json:"cache,required"` - Input float64 `json:"input,required"` - Output float64 `json:"output,required"` - Reasoning float64 `json:"reasoning,required"` - JSON messageMetadataAssistantTokensJSON `json:"-"` -} - -// messageMetadataAssistantTokensJSON contains the JSON metadata for the struct -// [MessageMetadataAssistantTokens] -type messageMetadataAssistantTokensJSON struct { - Cache apijson.Field - Input apijson.Field - Output apijson.Field - Reasoning apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataAssistantTokens) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataAssistantTokensJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataAssistantTokensCache struct { - Read float64 `json:"read,required"` - Write float64 `json:"write,required"` - JSON messageMetadataAssistantTokensCacheJSON `json:"-"` -} - -// messageMetadataAssistantTokensCacheJSON contains the JSON metadata for the -// struct [MessageMetadataAssistantTokensCache] -type messageMetadataAssistantTokensCacheJSON struct { - Read apijson.Field - Write apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataAssistantTokensCache) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataAssistantTokensCacheJSON) RawJSON() string { - return r.raw -} - -type MessageMetadataError struct { - // This field can have the runtime type of [shared.ProviderAuthErrorData], - // [shared.UnknownErrorData], [interface{}]. - Data interface{} `json:"data,required"` - Name MessageMetadataErrorName `json:"name,required"` - JSON messageMetadataErrorJSON `json:"-"` - union MessageMetadataErrorUnion -} - -// messageMetadataErrorJSON contains the JSON metadata for the struct -// [MessageMetadataError] -type messageMetadataErrorJSON struct { - Data apijson.Field - Name apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r messageMetadataErrorJSON) RawJSON() string { - return r.raw -} - -func (r *MessageMetadataError) UnmarshalJSON(data []byte) (err error) { - *r = MessageMetadataError{} +func (r *Message) UnmarshalJSON(data []byte) (err error) { + *r = Message{} err = apijson.UnmarshalRoot(data, &r.union) if err != nil { return err @@ -468,98 +635,36 @@ func (r *MessageMetadataError) UnmarshalJSON(data []byte) (err error) { return apijson.Port(r.union, &r) } -// AsUnion returns a [MessageMetadataErrorUnion] interface which you can cast to -// the specific types for more type safety. +// AsUnion returns a [MessageUnion] interface which you can cast to the specific +// types for more type safety. // -// Possible runtime types of the union are [shared.ProviderAuthError], -// [shared.UnknownError], [MessageMetadataErrorMessageOutputLengthError]. -func (r MessageMetadataError) AsUnion() MessageMetadataErrorUnion { +// Possible runtime types of the union are [UserMessage], [AssistantMessage]. +func (r Message) AsUnion() MessageUnion { return r.union } -// Union satisfied by [shared.ProviderAuthError], [shared.UnknownError] or -// [MessageMetadataErrorMessageOutputLengthError]. -type MessageMetadataErrorUnion interface { - ImplementsMessageMetadataError() +// Union satisfied by [UserMessage] or [AssistantMessage]. +type MessageUnion interface { + implementsMessage() } func init() { apijson.RegisterUnion( - reflect.TypeOf((*MessageMetadataErrorUnion)(nil)).Elem(), - "name", + reflect.TypeOf((*MessageUnion)(nil)).Elem(), + "role", apijson.UnionVariant{ TypeFilter: gjson.JSON, - Type: reflect.TypeOf(shared.ProviderAuthError{}), - DiscriminatorValue: "ProviderAuthError", + Type: reflect.TypeOf(UserMessage{}), + DiscriminatorValue: "user", }, apijson.UnionVariant{ TypeFilter: gjson.JSON, - Type: reflect.TypeOf(shared.UnknownError{}), - DiscriminatorValue: "UnknownError", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(MessageMetadataErrorMessageOutputLengthError{}), - DiscriminatorValue: "MessageOutputLengthError", + Type: reflect.TypeOf(AssistantMessage{}), + DiscriminatorValue: "assistant", }, ) } -type MessageMetadataErrorMessageOutputLengthError struct { - Data interface{} `json:"data,required"` - Name MessageMetadataErrorMessageOutputLengthErrorName `json:"name,required"` - JSON messageMetadataErrorMessageOutputLengthErrorJSON `json:"-"` -} - -// messageMetadataErrorMessageOutputLengthErrorJSON contains the JSON metadata for -// the struct [MessageMetadataErrorMessageOutputLengthError] -type messageMetadataErrorMessageOutputLengthErrorJSON struct { - Data apijson.Field - Name apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *MessageMetadataErrorMessageOutputLengthError) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r messageMetadataErrorMessageOutputLengthErrorJSON) RawJSON() string { - return r.raw -} - -func (r MessageMetadataErrorMessageOutputLengthError) ImplementsMessageMetadataError() {} - -type MessageMetadataErrorMessageOutputLengthErrorName string - -const ( - MessageMetadataErrorMessageOutputLengthErrorNameMessageOutputLengthError MessageMetadataErrorMessageOutputLengthErrorName = "MessageOutputLengthError" -) - -func (r MessageMetadataErrorMessageOutputLengthErrorName) IsKnown() bool { - switch r { - case MessageMetadataErrorMessageOutputLengthErrorNameMessageOutputLengthError: - return true - } - return false -} - -type MessageMetadataErrorName string - -const ( - MessageMetadataErrorNameProviderAuthError MessageMetadataErrorName = "ProviderAuthError" - MessageMetadataErrorNameUnknownError MessageMetadataErrorName = "UnknownError" - MessageMetadataErrorNameMessageOutputLengthError MessageMetadataErrorName = "MessageOutputLengthError" -) - -func (r MessageMetadataErrorName) IsKnown() bool { - switch r { - case MessageMetadataErrorNameProviderAuthError, MessageMetadataErrorNameUnknownError, MessageMetadataErrorNameMessageOutputLengthError: - return true - } - return false -} - type MessageRole string const ( @@ -575,197 +680,6 @@ func (r MessageRole) IsKnown() bool { return false } -type MessagePart struct { - Type MessagePartType `json:"type,required"` - Filename string `json:"filename"` - MediaType string `json:"mediaType"` - // This field can have the runtime type of [map[string]interface{}]. - ProviderMetadata interface{} `json:"providerMetadata"` - SourceID string `json:"sourceId"` - Text string `json:"text"` - Title string `json:"title"` - // This field can have the runtime type of [ToolInvocationPartToolInvocation]. - ToolInvocation interface{} `json:"toolInvocation"` - URL string `json:"url"` - JSON messagePartJSON `json:"-"` - union MessagePartUnion -} - -// messagePartJSON contains the JSON metadata for the struct [MessagePart] -type messagePartJSON struct { - Type apijson.Field - Filename apijson.Field - MediaType apijson.Field - ProviderMetadata apijson.Field - SourceID apijson.Field - Text apijson.Field - Title apijson.Field - ToolInvocation apijson.Field - URL apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r messagePartJSON) RawJSON() string { - return r.raw -} - -func (r *MessagePart) UnmarshalJSON(data []byte) (err error) { - *r = MessagePart{} - err = apijson.UnmarshalRoot(data, &r.union) - if err != nil { - return err - } - return apijson.Port(r.union, &r) -} - -// AsUnion returns a [MessagePartUnion] interface which you can cast to the -// specific types for more type safety. -// -// Possible runtime types of the union are [TextPart], [ReasoningPart], -// [ToolInvocationPart], [SourceURLPart], [FilePart], [StepStartPart]. -func (r MessagePart) AsUnion() MessagePartUnion { - return r.union -} - -// Union satisfied by [TextPart], [ReasoningPart], [ToolInvocationPart], -// [SourceURLPart], [FilePart] or [StepStartPart]. -type MessagePartUnion interface { - implementsMessagePart() -} - -func init() { - apijson.RegisterUnion( - reflect.TypeOf((*MessagePartUnion)(nil)).Elem(), - "type", - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(TextPart{}), - DiscriminatorValue: "text", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(ReasoningPart{}), - DiscriminatorValue: "reasoning", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(ToolInvocationPart{}), - DiscriminatorValue: "tool-invocation", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(SourceURLPart{}), - DiscriminatorValue: "source-url", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(FilePart{}), - DiscriminatorValue: "file", - }, - apijson.UnionVariant{ - TypeFilter: gjson.JSON, - Type: reflect.TypeOf(StepStartPart{}), - DiscriminatorValue: "step-start", - }, - ) -} - -type MessagePartType string - -const ( - MessagePartTypeText MessagePartType = "text" - MessagePartTypeReasoning MessagePartType = "reasoning" - MessagePartTypeToolInvocation MessagePartType = "tool-invocation" - MessagePartTypeSourceURL MessagePartType = "source-url" - MessagePartTypeFile MessagePartType = "file" - MessagePartTypeStepStart MessagePartType = "step-start" -) - -func (r MessagePartType) IsKnown() bool { - switch r { - case MessagePartTypeText, MessagePartTypeReasoning, MessagePartTypeToolInvocation, MessagePartTypeSourceURL, MessagePartTypeFile, MessagePartTypeStepStart: - return true - } - return false -} - -type MessagePartParam struct { - Type param.Field[MessagePartType] `json:"type,required"` - Filename param.Field[string] `json:"filename"` - MediaType param.Field[string] `json:"mediaType"` - ProviderMetadata param.Field[interface{}] `json:"providerMetadata"` - SourceID param.Field[string] `json:"sourceId"` - Text param.Field[string] `json:"text"` - Title param.Field[string] `json:"title"` - ToolInvocation param.Field[interface{}] `json:"toolInvocation"` - URL param.Field[string] `json:"url"` -} - -func (r MessagePartParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r MessagePartParam) implementsMessagePartUnionParam() {} - -// Satisfied by [TextPartParam], [ReasoningPartParam], [ToolInvocationPartParam], -// [SourceURLPartParam], [FilePartParam], [StepStartPartParam], [MessagePartParam]. -type MessagePartUnionParam interface { - implementsMessagePartUnionParam() -} - -type ReasoningPart struct { - Text string `json:"text,required"` - Type ReasoningPartType `json:"type,required"` - ProviderMetadata map[string]interface{} `json:"providerMetadata"` - JSON reasoningPartJSON `json:"-"` -} - -// reasoningPartJSON contains the JSON metadata for the struct [ReasoningPart] -type reasoningPartJSON struct { - Text apijson.Field - Type apijson.Field - ProviderMetadata apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *ReasoningPart) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r reasoningPartJSON) RawJSON() string { - return r.raw -} - -func (r ReasoningPart) implementsMessagePart() {} - -type ReasoningPartType string - -const ( - ReasoningPartTypeReasoning ReasoningPartType = "reasoning" -) - -func (r ReasoningPartType) IsKnown() bool { - switch r { - case ReasoningPartTypeReasoning: - return true - } - return false -} - -type ReasoningPartParam struct { - Text param.Field[string] `json:"text,required"` - Type param.Field[ReasoningPartType] `json:"type,required"` - ProviderMetadata param.Field[map[string]interface{}] `json:"providerMetadata"` -} - -func (r ReasoningPartParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r ReasoningPartParam) implementsMessagePartUnionParam() {} - type Session struct { ID string `json:"id,required"` Time SessionTime `json:"time,required"` @@ -864,64 +778,6 @@ func (r sessionShareJSON) RawJSON() string { return r.raw } -type SourceURLPart struct { - SourceID string `json:"sourceId,required"` - Type SourceURLPartType `json:"type,required"` - URL string `json:"url,required"` - ProviderMetadata map[string]interface{} `json:"providerMetadata"` - Title string `json:"title"` - JSON sourceURLPartJSON `json:"-"` -} - -// sourceURLPartJSON contains the JSON metadata for the struct [SourceURLPart] -type sourceURLPartJSON struct { - SourceID apijson.Field - Type apijson.Field - URL apijson.Field - ProviderMetadata apijson.Field - Title apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *SourceURLPart) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r sourceURLPartJSON) RawJSON() string { - return r.raw -} - -func (r SourceURLPart) implementsMessagePart() {} - -type SourceURLPartType string - -const ( - SourceURLPartTypeSourceURL SourceURLPartType = "source-url" -) - -func (r SourceURLPartType) IsKnown() bool { - switch r { - case SourceURLPartTypeSourceURL: - return true - } - return false -} - -type SourceURLPartParam struct { - SourceID param.Field[string] `json:"sourceId,required"` - Type param.Field[SourceURLPartType] `json:"type,required"` - URL param.Field[string] `json:"url,required"` - ProviderMetadata param.Field[map[string]interface{}] `json:"providerMetadata"` - Title param.Field[string] `json:"title"` -} - -func (r SourceURLPartParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r SourceURLPartParam) implementsMessagePartUnionParam() {} - type StepStartPart struct { Type StepStartPartType `json:"type,required"` JSON stepStartPartJSON `json:"-"` @@ -942,7 +798,7 @@ func (r stepStartPartJSON) RawJSON() string { return r.raw } -func (r StepStartPart) implementsMessagePart() {} +func (r StepStartPart) implementsAssistantMessagePart() {} type StepStartPartType string @@ -958,16 +814,6 @@ func (r StepStartPartType) IsKnown() bool { return false } -type StepStartPartParam struct { - Type param.Field[StepStartPartType] `json:"type,required"` -} - -func (r StepStartPartParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r StepStartPartParam) implementsMessagePartUnionParam() {} - type TextPart struct { Text string `json:"text,required"` Type TextPartType `json:"type,required"` @@ -990,7 +836,9 @@ func (r textPartJSON) RawJSON() string { return r.raw } -func (r TextPart) implementsMessagePart() {} +func (r TextPart) implementsAssistantMessagePart() {} + +func (r TextPart) implementsUserMessagePart() {} type TextPartType string @@ -1015,122 +863,71 @@ func (r TextPartParam) MarshalJSON() (data []byte, err error) { return apijson.MarshalRoot(r) } -func (r TextPartParam) implementsMessagePartUnionParam() {} +func (r TextPartParam) implementsUserMessagePartUnionParam() {} -type ToolCall struct { - State ToolCallState `json:"state,required"` - ToolCallID string `json:"toolCallId,required"` - ToolName string `json:"toolName,required"` - Args interface{} `json:"args"` - Step float64 `json:"step"` - JSON toolCallJSON `json:"-"` +type ToolPart struct { + ID string `json:"id,required"` + State ToolPartState `json:"state,required"` + Tool string `json:"tool,required"` + Type ToolPartType `json:"type,required"` + JSON toolPartJSON `json:"-"` } -// toolCallJSON contains the JSON metadata for the struct [ToolCall] -type toolCallJSON struct { +// toolPartJSON contains the JSON metadata for the struct [ToolPart] +type toolPartJSON struct { + ID apijson.Field State apijson.Field - ToolCallID apijson.Field - ToolName apijson.Field - Args apijson.Field - Step apijson.Field + Tool apijson.Field + Type apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *ToolCall) UnmarshalJSON(data []byte) (err error) { +func (r *ToolPart) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r toolCallJSON) RawJSON() string { +func (r toolPartJSON) RawJSON() string { return r.raw } -func (r ToolCall) implementsToolInvocationPartToolInvocation() {} +func (r ToolPart) implementsAssistantMessagePart() {} -type ToolCallState string - -const ( - ToolCallStateCall ToolCallState = "call" -) - -func (r ToolCallState) IsKnown() bool { - switch r { - case ToolCallStateCall: - return true - } - return false +type ToolPartState struct { + Status ToolPartStateStatus `json:"status,required"` + Error string `json:"error"` + // This field can have the runtime type of [interface{}], [map[string]interface{}]. + Input interface{} `json:"input"` + // This field can have the runtime type of [map[string]interface{}]. + Metadata interface{} `json:"metadata"` + Output string `json:"output"` + // This field can have the runtime type of [ToolStateRunningTime], + // [ToolStateCompletedTime], [ToolStateErrorTime]. + Time interface{} `json:"time"` + Title string `json:"title"` + JSON toolPartStateJSON `json:"-"` + union ToolPartStateUnion } -type ToolCallParam struct { - State param.Field[ToolCallState] `json:"state,required"` - ToolCallID param.Field[string] `json:"toolCallId,required"` - ToolName param.Field[string] `json:"toolName,required"` - Args param.Field[interface{}] `json:"args"` - Step param.Field[float64] `json:"step"` -} - -func (r ToolCallParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r ToolCallParam) implementsToolInvocationPartToolInvocationUnionParam() {} - -type ToolInvocationPart struct { - ToolInvocation ToolInvocationPartToolInvocation `json:"toolInvocation,required"` - Type ToolInvocationPartType `json:"type,required"` - JSON toolInvocationPartJSON `json:"-"` -} - -// toolInvocationPartJSON contains the JSON metadata for the struct -// [ToolInvocationPart] -type toolInvocationPartJSON struct { - ToolInvocation apijson.Field - Type apijson.Field - raw string - ExtraFields map[string]apijson.Field -} - -func (r *ToolInvocationPart) UnmarshalJSON(data []byte) (err error) { - return apijson.UnmarshalRoot(data, r) -} - -func (r toolInvocationPartJSON) RawJSON() string { - return r.raw -} - -func (r ToolInvocationPart) implementsMessagePart() {} - -type ToolInvocationPartToolInvocation struct { - State ToolInvocationPartToolInvocationState `json:"state,required"` - ToolCallID string `json:"toolCallId,required"` - ToolName string `json:"toolName,required"` - // This field can have the runtime type of [interface{}]. - Args interface{} `json:"args"` - Result string `json:"result"` - Step float64 `json:"step"` - JSON toolInvocationPartToolInvocationJSON `json:"-"` - union ToolInvocationPartToolInvocationUnion -} - -// toolInvocationPartToolInvocationJSON contains the JSON metadata for the struct -// [ToolInvocationPartToolInvocation] -type toolInvocationPartToolInvocationJSON struct { - State apijson.Field - ToolCallID apijson.Field - ToolName apijson.Field - Args apijson.Field - Result apijson.Field - Step apijson.Field +// toolPartStateJSON contains the JSON metadata for the struct [ToolPartState] +type toolPartStateJSON struct { + Status apijson.Field + Error apijson.Field + Input apijson.Field + Metadata apijson.Field + Output apijson.Field + Time apijson.Field + Title apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r toolInvocationPartToolInvocationJSON) RawJSON() string { +func (r toolPartStateJSON) RawJSON() string { return r.raw } -func (r *ToolInvocationPartToolInvocation) UnmarshalJSON(data []byte) (err error) { - *r = ToolInvocationPartToolInvocation{} +func (r *ToolPartState) UnmarshalJSON(data []byte) (err error) { + *r = ToolPartState{} err = apijson.UnmarshalRoot(data, &r.union) if err != nil { return err @@ -1138,228 +935,483 @@ func (r *ToolInvocationPartToolInvocation) UnmarshalJSON(data []byte) (err error return apijson.Port(r.union, &r) } -// AsUnion returns a [ToolInvocationPartToolInvocationUnion] interface which you -// can cast to the specific types for more type safety. +// AsUnion returns a [ToolPartStateUnion] interface which you can cast to the +// specific types for more type safety. // -// Possible runtime types of the union are [ToolCall], [ToolPartialCall], -// [ToolResult]. -func (r ToolInvocationPartToolInvocation) AsUnion() ToolInvocationPartToolInvocationUnion { +// Possible runtime types of the union are [ToolStatePending], [ToolStateRunning], +// [ToolStateCompleted], [ToolStateError]. +func (r ToolPartState) AsUnion() ToolPartStateUnion { return r.union } -// Union satisfied by [ToolCall], [ToolPartialCall] or [ToolResult]. -type ToolInvocationPartToolInvocationUnion interface { - implementsToolInvocationPartToolInvocation() +// Union satisfied by [ToolStatePending], [ToolStateRunning], [ToolStateCompleted] +// or [ToolStateError]. +type ToolPartStateUnion interface { + implementsToolPartState() } func init() { apijson.RegisterUnion( - reflect.TypeOf((*ToolInvocationPartToolInvocationUnion)(nil)).Elem(), - "state", + reflect.TypeOf((*ToolPartStateUnion)(nil)).Elem(), + "status", apijson.UnionVariant{ TypeFilter: gjson.JSON, - Type: reflect.TypeOf(ToolCall{}), - DiscriminatorValue: "call", + Type: reflect.TypeOf(ToolStatePending{}), + DiscriminatorValue: "pending", }, apijson.UnionVariant{ TypeFilter: gjson.JSON, - Type: reflect.TypeOf(ToolPartialCall{}), - DiscriminatorValue: "partial-call", + Type: reflect.TypeOf(ToolStateRunning{}), + DiscriminatorValue: "running", }, apijson.UnionVariant{ TypeFilter: gjson.JSON, - Type: reflect.TypeOf(ToolResult{}), - DiscriminatorValue: "result", + Type: reflect.TypeOf(ToolStateCompleted{}), + DiscriminatorValue: "completed", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(ToolStateError{}), + DiscriminatorValue: "error", }, ) } -type ToolInvocationPartToolInvocationState string +type ToolPartStateStatus string const ( - ToolInvocationPartToolInvocationStateCall ToolInvocationPartToolInvocationState = "call" - ToolInvocationPartToolInvocationStatePartialCall ToolInvocationPartToolInvocationState = "partial-call" - ToolInvocationPartToolInvocationStateResult ToolInvocationPartToolInvocationState = "result" + ToolPartStateStatusPending ToolPartStateStatus = "pending" + ToolPartStateStatusRunning ToolPartStateStatus = "running" + ToolPartStateStatusCompleted ToolPartStateStatus = "completed" + ToolPartStateStatusError ToolPartStateStatus = "error" ) -func (r ToolInvocationPartToolInvocationState) IsKnown() bool { +func (r ToolPartStateStatus) IsKnown() bool { switch r { - case ToolInvocationPartToolInvocationStateCall, ToolInvocationPartToolInvocationStatePartialCall, ToolInvocationPartToolInvocationStateResult: + case ToolPartStateStatusPending, ToolPartStateStatusRunning, ToolPartStateStatusCompleted, ToolPartStateStatusError: return true } return false } -type ToolInvocationPartType string +type ToolPartType string const ( - ToolInvocationPartTypeToolInvocation ToolInvocationPartType = "tool-invocation" + ToolPartTypeTool ToolPartType = "tool" ) -func (r ToolInvocationPartType) IsKnown() bool { +func (r ToolPartType) IsKnown() bool { switch r { - case ToolInvocationPartTypeToolInvocation: + case ToolPartTypeTool: return true } return false } -type ToolInvocationPartParam struct { - ToolInvocation param.Field[ToolInvocationPartToolInvocationUnionParam] `json:"toolInvocation,required"` - Type param.Field[ToolInvocationPartType] `json:"type,required"` +type ToolStateCompleted struct { + Input map[string]interface{} `json:"input,required"` + Metadata map[string]interface{} `json:"metadata,required"` + Output string `json:"output,required"` + Status ToolStateCompletedStatus `json:"status,required"` + Time ToolStateCompletedTime `json:"time,required"` + Title string `json:"title,required"` + JSON toolStateCompletedJSON `json:"-"` } -func (r ToolInvocationPartParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r ToolInvocationPartParam) implementsMessagePartUnionParam() {} - -type ToolInvocationPartToolInvocationParam struct { - State param.Field[ToolInvocationPartToolInvocationState] `json:"state,required"` - ToolCallID param.Field[string] `json:"toolCallId,required"` - ToolName param.Field[string] `json:"toolName,required"` - Args param.Field[interface{}] `json:"args"` - Result param.Field[string] `json:"result"` - Step param.Field[float64] `json:"step"` -} - -func (r ToolInvocationPartToolInvocationParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r ToolInvocationPartToolInvocationParam) implementsToolInvocationPartToolInvocationUnionParam() { -} - -// Satisfied by [ToolCallParam], [ToolPartialCallParam], [ToolResultParam], -// [ToolInvocationPartToolInvocationParam]. -type ToolInvocationPartToolInvocationUnionParam interface { - implementsToolInvocationPartToolInvocationUnionParam() -} - -type ToolPartialCall struct { - State ToolPartialCallState `json:"state,required"` - ToolCallID string `json:"toolCallId,required"` - ToolName string `json:"toolName,required"` - Args interface{} `json:"args"` - Step float64 `json:"step"` - JSON toolPartialCallJSON `json:"-"` -} - -// toolPartialCallJSON contains the JSON metadata for the struct [ToolPartialCall] -type toolPartialCallJSON struct { - State apijson.Field - ToolCallID apijson.Field - ToolName apijson.Field - Args apijson.Field - Step apijson.Field +// toolStateCompletedJSON contains the JSON metadata for the struct +// [ToolStateCompleted] +type toolStateCompletedJSON struct { + Input apijson.Field + Metadata apijson.Field + Output apijson.Field + Status apijson.Field + Time apijson.Field + Title apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *ToolPartialCall) UnmarshalJSON(data []byte) (err error) { +func (r *ToolStateCompleted) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r toolPartialCallJSON) RawJSON() string { +func (r toolStateCompletedJSON) RawJSON() string { return r.raw } -func (r ToolPartialCall) implementsToolInvocationPartToolInvocation() {} +func (r ToolStateCompleted) implementsToolPartState() {} -type ToolPartialCallState string +type ToolStateCompletedStatus string const ( - ToolPartialCallStatePartialCall ToolPartialCallState = "partial-call" + ToolStateCompletedStatusCompleted ToolStateCompletedStatus = "completed" ) -func (r ToolPartialCallState) IsKnown() bool { +func (r ToolStateCompletedStatus) IsKnown() bool { switch r { - case ToolPartialCallStatePartialCall: + case ToolStateCompletedStatusCompleted: return true } return false } -type ToolPartialCallParam struct { - State param.Field[ToolPartialCallState] `json:"state,required"` - ToolCallID param.Field[string] `json:"toolCallId,required"` - ToolName param.Field[string] `json:"toolName,required"` - Args param.Field[interface{}] `json:"args"` - Step param.Field[float64] `json:"step"` +type ToolStateCompletedTime struct { + End float64 `json:"end,required"` + Start float64 `json:"start,required"` + JSON toolStateCompletedTimeJSON `json:"-"` } -func (r ToolPartialCallParam) MarshalJSON() (data []byte, err error) { - return apijson.MarshalRoot(r) -} - -func (r ToolPartialCallParam) implementsToolInvocationPartToolInvocationUnionParam() {} - -type ToolResult struct { - Result string `json:"result,required"` - State ToolResultState `json:"state,required"` - ToolCallID string `json:"toolCallId,required"` - ToolName string `json:"toolName,required"` - Args interface{} `json:"args"` - Step float64 `json:"step"` - JSON toolResultJSON `json:"-"` -} - -// toolResultJSON contains the JSON metadata for the struct [ToolResult] -type toolResultJSON struct { - Result apijson.Field - State apijson.Field - ToolCallID apijson.Field - ToolName apijson.Field - Args apijson.Field - Step apijson.Field +// toolStateCompletedTimeJSON contains the JSON metadata for the struct +// [ToolStateCompletedTime] +type toolStateCompletedTimeJSON struct { + End apijson.Field + Start apijson.Field raw string ExtraFields map[string]apijson.Field } -func (r *ToolResult) UnmarshalJSON(data []byte) (err error) { +func (r *ToolStateCompletedTime) UnmarshalJSON(data []byte) (err error) { return apijson.UnmarshalRoot(data, r) } -func (r toolResultJSON) RawJSON() string { +func (r toolStateCompletedTimeJSON) RawJSON() string { return r.raw } -func (r ToolResult) implementsToolInvocationPartToolInvocation() {} +type ToolStateError struct { + Error string `json:"error,required"` + Input map[string]interface{} `json:"input,required"` + Status ToolStateErrorStatus `json:"status,required"` + Time ToolStateErrorTime `json:"time,required"` + JSON toolStateErrorJSON `json:"-"` +} -type ToolResultState string +// toolStateErrorJSON contains the JSON metadata for the struct [ToolStateError] +type toolStateErrorJSON struct { + Error apijson.Field + Input apijson.Field + Status apijson.Field + Time apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *ToolStateError) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r toolStateErrorJSON) RawJSON() string { + return r.raw +} + +func (r ToolStateError) implementsToolPartState() {} + +type ToolStateErrorStatus string const ( - ToolResultStateResult ToolResultState = "result" + ToolStateErrorStatusError ToolStateErrorStatus = "error" ) -func (r ToolResultState) IsKnown() bool { +func (r ToolStateErrorStatus) IsKnown() bool { switch r { - case ToolResultStateResult: + case ToolStateErrorStatusError: return true } return false } -type ToolResultParam struct { - Result param.Field[string] `json:"result,required"` - State param.Field[ToolResultState] `json:"state,required"` - ToolCallID param.Field[string] `json:"toolCallId,required"` - ToolName param.Field[string] `json:"toolName,required"` - Args param.Field[interface{}] `json:"args"` - Step param.Field[float64] `json:"step"` +type ToolStateErrorTime struct { + End float64 `json:"end,required"` + Start float64 `json:"start,required"` + JSON toolStateErrorTimeJSON `json:"-"` } -func (r ToolResultParam) MarshalJSON() (data []byte, err error) { +// toolStateErrorTimeJSON contains the JSON metadata for the struct +// [ToolStateErrorTime] +type toolStateErrorTimeJSON struct { + End apijson.Field + Start apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *ToolStateErrorTime) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r toolStateErrorTimeJSON) RawJSON() string { + return r.raw +} + +type ToolStatePending struct { + Status ToolStatePendingStatus `json:"status,required"` + JSON toolStatePendingJSON `json:"-"` +} + +// toolStatePendingJSON contains the JSON metadata for the struct +// [ToolStatePending] +type toolStatePendingJSON struct { + Status apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *ToolStatePending) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r toolStatePendingJSON) RawJSON() string { + return r.raw +} + +func (r ToolStatePending) implementsToolPartState() {} + +type ToolStatePendingStatus string + +const ( + ToolStatePendingStatusPending ToolStatePendingStatus = "pending" +) + +func (r ToolStatePendingStatus) IsKnown() bool { + switch r { + case ToolStatePendingStatusPending: + return true + } + return false +} + +type ToolStateRunning struct { + Status ToolStateRunningStatus `json:"status,required"` + Time ToolStateRunningTime `json:"time,required"` + Input interface{} `json:"input"` + Metadata map[string]interface{} `json:"metadata"` + Title string `json:"title"` + JSON toolStateRunningJSON `json:"-"` +} + +// toolStateRunningJSON contains the JSON metadata for the struct +// [ToolStateRunning] +type toolStateRunningJSON struct { + Status apijson.Field + Time apijson.Field + Input apijson.Field + Metadata apijson.Field + Title apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *ToolStateRunning) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r toolStateRunningJSON) RawJSON() string { + return r.raw +} + +func (r ToolStateRunning) implementsToolPartState() {} + +type ToolStateRunningStatus string + +const ( + ToolStateRunningStatusRunning ToolStateRunningStatus = "running" +) + +func (r ToolStateRunningStatus) IsKnown() bool { + switch r { + case ToolStateRunningStatusRunning: + return true + } + return false +} + +type ToolStateRunningTime struct { + Start float64 `json:"start,required"` + JSON toolStateRunningTimeJSON `json:"-"` +} + +// toolStateRunningTimeJSON contains the JSON metadata for the struct +// [ToolStateRunningTime] +type toolStateRunningTimeJSON struct { + Start apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *ToolStateRunningTime) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r toolStateRunningTimeJSON) RawJSON() string { + return r.raw +} + +type UserMessage struct { + ID string `json:"id,required"` + Parts []UserMessagePart `json:"parts,required"` + Role UserMessageRole `json:"role,required"` + SessionID string `json:"sessionID,required"` + Time UserMessageTime `json:"time,required"` + JSON userMessageJSON `json:"-"` +} + +// userMessageJSON contains the JSON metadata for the struct [UserMessage] +type userMessageJSON struct { + ID apijson.Field + Parts apijson.Field + Role apijson.Field + SessionID apijson.Field + Time apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *UserMessage) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r userMessageJSON) RawJSON() string { + return r.raw +} + +func (r UserMessage) implementsMessage() {} + +type UserMessageRole string + +const ( + UserMessageRoleUser UserMessageRole = "user" +) + +func (r UserMessageRole) IsKnown() bool { + switch r { + case UserMessageRoleUser: + return true + } + return false +} + +type UserMessageTime struct { + Created float64 `json:"created,required"` + JSON userMessageTimeJSON `json:"-"` +} + +// userMessageTimeJSON contains the JSON metadata for the struct [UserMessageTime] +type userMessageTimeJSON struct { + Created apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *UserMessageTime) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r userMessageTimeJSON) RawJSON() string { + return r.raw +} + +type UserMessagePart struct { + Type UserMessagePartType `json:"type,required"` + Filename string `json:"filename"` + Mime string `json:"mime"` + Text string `json:"text"` + URL string `json:"url"` + JSON userMessagePartJSON `json:"-"` + union UserMessagePartUnion +} + +// userMessagePartJSON contains the JSON metadata for the struct [UserMessagePart] +type userMessagePartJSON struct { + Type apijson.Field + Filename apijson.Field + Mime apijson.Field + Text apijson.Field + URL apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r userMessagePartJSON) RawJSON() string { + return r.raw +} + +func (r *UserMessagePart) UnmarshalJSON(data []byte) (err error) { + *r = UserMessagePart{} + err = apijson.UnmarshalRoot(data, &r.union) + if err != nil { + return err + } + return apijson.Port(r.union, &r) +} + +// AsUnion returns a [UserMessagePartUnion] interface which you can cast to the +// specific types for more type safety. +// +// Possible runtime types of the union are [TextPart], [FilePart]. +func (r UserMessagePart) AsUnion() UserMessagePartUnion { + return r.union +} + +// Union satisfied by [TextPart] or [FilePart]. +type UserMessagePartUnion interface { + implementsUserMessagePart() +} + +func init() { + apijson.RegisterUnion( + reflect.TypeOf((*UserMessagePartUnion)(nil)).Elem(), + "type", + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(TextPart{}), + DiscriminatorValue: "text", + }, + apijson.UnionVariant{ + TypeFilter: gjson.JSON, + Type: reflect.TypeOf(FilePart{}), + DiscriminatorValue: "file", + }, + ) +} + +type UserMessagePartType string + +const ( + UserMessagePartTypeText UserMessagePartType = "text" + UserMessagePartTypeFile UserMessagePartType = "file" +) + +func (r UserMessagePartType) IsKnown() bool { + switch r { + case UserMessagePartTypeText, UserMessagePartTypeFile: + return true + } + return false +} + +type UserMessagePartParam struct { + Type param.Field[UserMessagePartType] `json:"type,required"` + Filename param.Field[string] `json:"filename"` + Mime param.Field[string] `json:"mime"` + Text param.Field[string] `json:"text"` + URL param.Field[string] `json:"url"` +} + +func (r UserMessagePartParam) MarshalJSON() (data []byte, err error) { return apijson.MarshalRoot(r) } -func (r ToolResultParam) implementsToolInvocationPartToolInvocationUnionParam() {} +func (r UserMessagePartParam) implementsUserMessagePartUnionParam() {} + +// Satisfied by [TextPartParam], [FilePartParam], [UserMessagePartParam]. +type UserMessagePartUnionParam interface { + implementsUserMessagePartUnionParam() +} type SessionChatParams struct { - ModelID param.Field[string] `json:"modelID,required"` - Parts param.Field[[]MessagePartUnionParam] `json:"parts,required"` - ProviderID param.Field[string] `json:"providerID,required"` + ModelID param.Field[string] `json:"modelID,required"` + Parts param.Field[[]UserMessagePartUnionParam] `json:"parts,required"` + ProviderID param.Field[string] `json:"providerID,required"` } func (r SessionChatParams) MarshalJSON() (data []byte, err error) { diff --git a/packages/tui/sdk/session_test.go b/packages/tui/sdk/session_test.go index da9fb825..15137e62 100644 --- a/packages/tui/sdk/session_test.go +++ b/packages/tui/sdk/session_test.go @@ -118,7 +118,7 @@ func TestSessionChat(t *testing.T) { "id", opencode.SessionChatParams{ ModelID: opencode.F("modelID"), - Parts: opencode.F([]opencode.MessagePartUnionParam{opencode.TextPartParam{ + Parts: opencode.F([]opencode.UserMessagePartUnionParam{opencode.TextPartParam{ Text: opencode.F("text"), Type: opencode.F(opencode.TextPartTypeText), }}), diff --git a/packages/tui/sdk/shared/shared.go b/packages/tui/sdk/shared/shared.go index 121f64a5..58baf3d9 100644 --- a/packages/tui/sdk/shared/shared.go +++ b/packages/tui/sdk/shared/shared.go @@ -6,6 +6,47 @@ import ( "github.com/sst/opencode-sdk-go/internal/apijson" ) +type MessageAbortedError struct { + Data interface{} `json:"data,required"` + Name MessageAbortedErrorName `json:"name,required"` + JSON messageAbortedErrorJSON `json:"-"` +} + +// messageAbortedErrorJSON contains the JSON metadata for the struct +// [MessageAbortedError] +type messageAbortedErrorJSON struct { + Data apijson.Field + Name apijson.Field + raw string + ExtraFields map[string]apijson.Field +} + +func (r *MessageAbortedError) UnmarshalJSON(data []byte) (err error) { + return apijson.UnmarshalRoot(data, r) +} + +func (r messageAbortedErrorJSON) RawJSON() string { + return r.raw +} + +func (r MessageAbortedError) ImplementsEventListResponseEventSessionErrorPropertiesError() {} + +func (r MessageAbortedError) ImplementsAssistantMessageError() {} + +type MessageAbortedErrorName string + +const ( + MessageAbortedErrorNameMessageAbortedError MessageAbortedErrorName = "MessageAbortedError" +) + +func (r MessageAbortedErrorName) IsKnown() bool { + switch r { + case MessageAbortedErrorNameMessageAbortedError: + return true + } + return false +} + type ProviderAuthError struct { Data ProviderAuthErrorData `json:"data,required"` Name ProviderAuthErrorName `json:"name,required"` @@ -31,7 +72,7 @@ func (r providerAuthErrorJSON) RawJSON() string { func (r ProviderAuthError) ImplementsEventListResponseEventSessionErrorPropertiesError() {} -func (r ProviderAuthError) ImplementsMessageMetadataError() {} +func (r ProviderAuthError) ImplementsAssistantMessageError() {} type ProviderAuthErrorData struct { Message string `json:"message,required"` @@ -94,7 +135,7 @@ func (r unknownErrorJSON) RawJSON() string { func (r UnknownError) ImplementsEventListResponseEventSessionErrorPropertiesError() {} -func (r UnknownError) ImplementsMessageMetadataError() {} +func (r UnknownError) ImplementsAssistantMessageError() {} type UnknownErrorData struct { Message string `json:"message,required"` diff --git a/packages/web/astro.config.mjs b/packages/web/astro.config.mjs index 0c3a5ecc..38a339c7 100644 --- a/packages/web/astro.config.mjs +++ b/packages/web/astro.config.mjs @@ -7,6 +7,7 @@ import theme from "toolbeam-docs-theme" import config from "./config.mjs" import { rehypeHeadingIds } from "@astrojs/markdown-remark" import rehypeAutolinkHeadings from "rehype-autolink-headings" +import { spawnSync } from "child_process" const github = "https://github.com/sst/opencode" @@ -20,18 +21,23 @@ export default defineConfig({ devToolbar: { enabled: false, }, - markdown: { - rehypePlugins: [ - rehypeHeadingIds, - [rehypeAutolinkHeadings, { behavior: "wrap" }], - ], + server: { + host: "0.0.0.0", }, + markdown: { + rehypePlugins: [rehypeHeadingIds, [rehypeAutolinkHeadings, { behavior: "wrap" }]], + }, + build: {}, integrations: [ + configSchema(), solidJs(), starlight({ title: "opencode", expressiveCode: { themes: ["github-light", "github-dark"] }, - social: [{ icon: "github", label: "GitHub", href: config.github }], + social: [ + { icon: "github", label: "GitHub", href: config.github }, + { icon: "discord", label: "Dscord", href: config.discord }, + ], head: [ { tag: "link", @@ -62,6 +68,7 @@ export default defineConfig({ "docs/themes", "docs/keybinds", "docs/mcp-servers", + "docs/troubleshooting", ], components: { Hero: "./src/components/Hero.astro", @@ -75,4 +82,19 @@ export default defineConfig({ ], }), ], + redirects: { + "/discord": "https://discord.com/invite/opencode", + }, }) + +function configSchema() { + return { + name: "configSchema", + hooks: { + "astro:build:done": async () => { + console.log("generating config schema") + spawnSync("../opencode/script/schema.ts", ["./dist/config.json"]) + }, + }, + } +} diff --git a/packages/web/config.mjs b/packages/web/config.mjs index b6ec26e3..5e4c571d 100644 --- a/packages/web/config.mjs +++ b/packages/web/config.mjs @@ -1,7 +1,12 @@ +const stage = process.env.SST_STAGE || "dev" + export default { - url: "https://opencode.ai", + url: stage === "production" + ? "https://opencode.ai" + : `https://${stage}.opencode.ai`, socialCard: "https://social-cards.sst.dev", github: "https://github.com/sst/opencode", + discord: "https://discord.gg/opencode", headerLinks: [ { name: "Home", url: "/" }, { name: "Docs", url: "/docs/" }, diff --git a/packages/web/package.json b/packages/web/package.json index c1722b2b..bdd6467c 100644 --- a/packages/web/package.json +++ b/packages/web/package.json @@ -4,6 +4,7 @@ "version": "0.0.1", "scripts": { "dev": "astro dev", + "dev:remote": "sst shell --stage=dev --target=Web astro dev", "start": "astro dev", "build": "astro build", "preview": "astro preview", diff --git a/packages/web/public/theme.json b/packages/web/public/theme.json index 0b1b95f0..b3e97f7c 100644 --- a/packages/web/public/theme.json +++ b/packages/web/public/theme.json @@ -88,14 +88,7 @@ "syntaxOperator": { "$ref": "#/definitions/colorValue" }, "syntaxPunctuation": { "$ref": "#/definitions/colorValue" } }, - "required": [ - "primary", - "secondary", - "accent", - "text", - "textMuted", - "background" - ], + "required": ["primary", "secondary", "accent", "text", "textMuted", "background"], "additionalProperties": false } }, diff --git a/packages/web/src/components/CodeBlock.tsx b/packages/web/src/components/CodeBlock.tsx index 6a684689..3702044b 100644 --- a/packages/web/src/components/CodeBlock.tsx +++ b/packages/web/src/components/CodeBlock.tsx @@ -1,8 +1,4 @@ -import { - type JSX, - splitProps, - createResource, -} from "solid-js" +import { type JSX, splitProps, createResource } from "solid-js" import { codeToHtml } from "shiki" import styles from "./codeblock.module.css" import { transformerNotationDiff } from "@shikijs/transformers" @@ -30,7 +26,7 @@ function CodeBlock(props: CodeBlockProps) { }, ) - return
+ return
} export default CodeBlock diff --git a/packages/web/src/components/MarkdownView.tsx b/packages/web/src/components/MarkdownView.tsx deleted file mode 100644 index 7a63bc0c..00000000 --- a/packages/web/src/components/MarkdownView.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { type JSX, splitProps, createResource } from "solid-js" -import { marked } from "marked" -import markedShiki from "marked-shiki" -import { codeToHtml } from "shiki" -import { transformerNotationDiff } from "@shikijs/transformers" -import styles from "./markdownview.module.css" - -interface MarkdownViewProps extends JSX.HTMLAttributes { - markdown: string -} - -const markedWithShiki = marked.use( - markedShiki({ - highlight(code, lang) { - return codeToHtml(code, { - lang: lang || "text", - themes: { - light: "github-light", - dark: "github-dark", - }, - transformers: [transformerNotationDiff()], - }) - }, - }), -) - -function MarkdownView(props: MarkdownViewProps) { - const [local, rest] = splitProps(props, ["markdown"]) - const [html] = createResource( - () => local.markdown, - async (markdown) => { - return markedWithShiki.parse(markdown) - }, - ) - - return
-} - -export default MarkdownView diff --git a/packages/web/src/components/Share.tsx b/packages/web/src/components/Share.tsx index ed889790..a084ec83 100644 --- a/packages/web/src/components/Share.tsx +++ b/packages/web/src/components/Share.tsx @@ -1,83 +1,24 @@ -import { type JSX } from "solid-js" import { For, Show, - Match, - Switch, onMount, Suspense, onCleanup, - splitProps, createMemo, - createEffect, createSignal, SuspenseList, } from "solid-js" -import map from "lang-map" import { DateTime } from "luxon" import { createStore, reconcile } from "solid-js/store" -import type { Diagnostic } from "vscode-languageserver-types" -import { - IconOpenAI, - IconGemini, - IconOpencode, - IconAnthropic, -} from "./icons/custom" -import { - IconHashtag, - IconSparkles, - IconGlobeAlt, - IconDocument, - IconQueueList, - IconUserCircle, - IconCheckCircle, - IconChevronDown, - IconCommandLine, - IconChevronRight, - IconDocumentPlus, - IconPencilSquare, - IconRectangleStack, - IconMagnifyingGlass, - IconWrenchScrewdriver, - IconDocumentMagnifyingGlass, - IconArrowDown, -} from "./icons" -import DiffView from "./DiffView" -import CodeBlock from "./CodeBlock" -import MarkdownView from "./MarkdownView" +import { IconArrowDown } from "./icons" +import { IconOpencode } from "./icons/custom" import styles from "./share.module.css" +import type { MessageV2 } from "opencode/session/message-v2" import type { Message } from "opencode/session/message" import type { Session } from "opencode/session/index" +import { Part, ProviderIcon } from "./share/part" -const MIN_DURATION = 2 - -type Status = - | "disconnected" - | "connecting" - | "connected" - | "error" - | "reconnecting" - -type TodoStatus = "pending" | "in_progress" | "completed" - -interface Todo { - id: string - content: string - status: TodoStatus - priority: "low" | "medium" | "high" -} - -function sortTodosByStatus(todos: Todo[]) { - const statusPriority: Record = { - in_progress: 0, - pending: 1, - completed: 2, - } - - return todos - .slice() - .sort((a, b) => statusPriority[a.status] - statusPriority[b.status]) -} +type Status = "disconnected" | "connecting" | "connected" | "error" | "reconnecting" function scrollToAnchor(id: string) { const el = document.getElementById(id) @@ -86,146 +27,6 @@ function scrollToAnchor(id: string) { el.scrollIntoView({ behavior: "smooth" }) } -function stripWorkingDirectory(filePath?: string, workingDir?: string) { - if (filePath === undefined || workingDir === undefined) return filePath - - const prefix = workingDir.endsWith("/") ? workingDir : workingDir + "/" - - if (filePath === workingDir) { - return "" - } - - if (filePath.startsWith(prefix)) { - return filePath.slice(prefix.length) - } - - return filePath -} - -function getShikiLang(filename: string) { - const ext = filename.split(".").pop()?.toLowerCase() ?? "" - - // map.languages(ext) returns an array of matching Linguist language names (e.g. ['TypeScript']) - const langs = map.languages(ext) - const type = langs?.[0]?.toLowerCase() - - // Overrride any specific language mappings - const overrides: Record = { - conf: "shellscript", - } - - return type ? (overrides[type] ?? type) : "plaintext" -} - -function formatDuration(ms: number): string { - const ONE_SECOND = 1000 - const ONE_MINUTE = 60 * ONE_SECOND - - if (ms >= ONE_MINUTE) { - const minutes = Math.floor(ms / ONE_MINUTE) - return minutes === 1 ? `1min` : `${minutes}mins` - } - - if (ms >= ONE_SECOND) { - const seconds = Math.floor(ms / ONE_SECOND) - return `${seconds}s` - } - - return `${ms}ms` -} - -// Converts nested objects/arrays into [path, value] pairs. -// E.g. {a:{b:{c:1}}, d:[{e:2}, 3]} => [["a.b.c",1], ["d[0].e",2], ["d[1]",3]] -function flattenToolArgs(obj: any, prefix: string = ""): Array<[string, any]> { - const entries: Array<[string, any]> = [] - - for (const [key, value] of Object.entries(obj)) { - const path = prefix ? `${prefix}.${key}` : key - - if (value !== null && typeof value === "object") { - if (Array.isArray(value)) { - value.forEach((item, index) => { - const arrayPath = `${path}[${index}]` - if (item !== null && typeof item === "object") { - entries.push(...flattenToolArgs(item, arrayPath)) - } else { - entries.push([arrayPath, item]) - } - }) - } else { - entries.push(...flattenToolArgs(value, path)) - } - } else { - entries.push([path, value]) - } - } - - return entries -} - -function formatErrorString(error: string): JSX.Element { - const errorMarker = "Error: " - const startsWithError = error.startsWith(errorMarker) - - return startsWithError ? ( -
-      
-        Error
-      
-      {error.slice(errorMarker.length)}
-    
- ) : ( -
-      {error}
-    
- ) -} - -function getDiagnostics( - diagnosticsByFile: Record, - currentFile: string, -): JSX.Element[] { - // Return a flat array of error diagnostics, in the format: - // "Error [65:20] Property 'x' does not exist on type 'Y'" - const result: JSX.Element[] = [] - - if ( - diagnosticsByFile === undefined || - diagnosticsByFile[currentFile] === undefined - ) - return result - - for (const diags of Object.values(diagnosticsByFile)) { - for (const d of diags) { - // Only keep diagnostics explicitly marked as Error (severity === 1) - if (d.severity !== 1) continue - - const line = d.range.start.line + 1 // 1-based - const column = d.range.start.character + 1 // 1-based - - result.push( -
-          
-            Error
-          
-          
-            [{line}:{column}]
-          
-          {d.message}
-        
, - ) - } - } - - return result -} - -function stripEnclosingTag(text: string): string { - const wrappedRe = /^\s*<([A-Za-z]\w*)>\s*([\s\S]*?)\s*<\/\1>\s*$/ - const match = text.match(wrappedRe) - return match ? match[2] : text -} - function getStatusText(status: [Status, string?]): string { switch (status[0]) { case "connected": @@ -243,317 +44,11 @@ function getStatusText(status: [Status, string?]): string { } } -function checkOverflow(getEl: () => HTMLElement | undefined, watch?: () => any) { - const [needsToggle, setNeedsToggle] = createSignal(false) - - function measure() { - const el = getEl() - if (!el) return - setNeedsToggle(el.scrollHeight > el.clientHeight + 1) - } - - onMount(() => { - let raf = 0 - - function probe() { - const el = getEl() - if (el && el.offsetParent !== null && el.getBoundingClientRect().height) { - measure() - } - else { - raf = requestAnimationFrame(probe) - } - } - raf = requestAnimationFrame(probe) - - const ro = new ResizeObserver(measure) - const el = getEl() - if (el) ro.observe(el) - - onCleanup(() => { - cancelAnimationFrame(raf) - ro.disconnect() - }) - }) - - if (watch) createEffect(measure) - - return needsToggle -} - -function ProviderIcon(props: { provider: string; size?: number }) { - const size = props.size || 16 - return ( - }> - - - - - - - - - - - ) -} - -interface ResultsButtonProps extends JSX.HTMLAttributes { - showCopy?: string - hideCopy?: string - results: boolean -} -function ResultsButton(props: ResultsButtonProps) { - const [local, rest] = splitProps(props, ["results", "showCopy", "hideCopy"]) - return ( - - ) -} - -interface TextPartProps extends JSX.HTMLAttributes { - text: string - expand?: boolean -} -function TextPart(props: TextPartProps) { - let preEl: HTMLPreElement | undefined - - const [local, rest] = splitProps(props, ["text", "expand"]) - const [expanded, setExpanded] = createSignal(false) - const overflowed = checkOverflow(() => preEl, () => local.expand) - - return ( -
-
{local.text}
- {((!local.expand && overflowed()) || expanded()) && ( - - )} -
- ) -} - -interface ErrorPartProps extends JSX.HTMLAttributes { - expand?: boolean -} -function ErrorPart(props: ErrorPartProps) { - let preEl: HTMLDivElement | undefined - - const [local, rest] = splitProps(props, ["expand", "children"]) - const [expanded, setExpanded] = createSignal(false) - const overflowed = checkOverflow(() => preEl, () => local.expand) - - return ( -
-
- {local.children} -
- {((!local.expand && overflowed()) || expanded()) && ( - - )} -
- ) -} - -interface MarkdownPartProps extends JSX.HTMLAttributes { - text: string - expand?: boolean - highlight?: boolean -} -function MarkdownPart(props: MarkdownPartProps) { - let divEl: HTMLDivElement | undefined - - const [local, rest] = splitProps(props, ["text", "expand", "highlight"]) - const [expanded, setExpanded] = createSignal(false) - const overflowed = checkOverflow(() => divEl, () => local.expand) - - return ( -
- (divEl = el)} - /> - {((!local.expand && overflowed()) || expanded()) && ( - - )} -
- ) -} - -interface TerminalPartProps extends JSX.HTMLAttributes { - command: string - error?: string - result?: string - desc?: string - expand?: boolean -} -function TerminalPart(props: TerminalPartProps) { - const [local, rest] = splitProps(props, [ - "command", - "error", - "result", - "desc", - "expand", - ]) - let preEl: HTMLDivElement | undefined - - const [expanded, setExpanded] = createSignal(false) - const overflowed = checkOverflow( - () => { - if (!preEl) return - return preEl.getElementsByTagName("pre")[0] - }, - () => local.expand - ) - - return ( -
-
-
- {local.desc} -
-
- - - - - - - - - -
-
- {((!local.expand && overflowed()) || expanded()) && ( - - )} -
- ) -} - -function ToolFooter(props: { time: number }) { - return props.time > MIN_DURATION ? ( - - {formatDuration(props.time)} - - ) : ( -
- ) -} - -interface AnchorProps extends JSX.HTMLAttributes { - id: string -} -function AnchorIcon(props: AnchorProps) { - const [local, rest] = splitProps(props, ["id", "children"]) - const [copied, setCopied] = createSignal(false) - - return ( - - ) -} - export default function Share(props: { id: string api: string info: Session.Info - messages: Record + messages: Record }) { let lastScrollY = 0 let hasScrolledToAnchor = false @@ -571,14 +66,10 @@ export default function Share(props: { const [store, setStore] = createStore<{ info?: Session.Info - messages: Record + messages: Record }>({ info: props.info, messages: props.messages }) - const messages = createMemo(() => - Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)), - ) - const [connectionStatus, setConnectionStatus] = createSignal< - [Status, string?] - >(["disconnected", "Disconnected"]) + const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id))) + const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"]) onMount(() => { const apiUrl = props.api @@ -653,10 +144,7 @@ export default function Share(props: { // Try to reconnect after 2 seconds clearTimeout(reconnectTimer) - reconnectTimer = window.setTimeout( - setupWebSocket, - 2000, - ) as unknown as number + reconnectTimer = window.setTimeout(setupWebSocket, 2000) as unknown as number } } @@ -754,7 +242,7 @@ export default function Share(props: { rootDir: undefined as string | undefined, created: undefined as number | undefined, completed: undefined as number | undefined, - messages: [] as Message.Info[], + messages: [] as MessageV2.Info[], models: {} as Record, cost: 0, tokens: { @@ -766,46 +254,41 @@ export default function Share(props: { result.created = props.info.time.created - for (let i = 0; i < messages().length; i++) { - const msg = messages()[i] - - const assistant = msg.metadata?.assistant + const msgs = messages() + for (let i = 0; i < msgs.length; i++) { + const msg = "metadata" in msgs[i] ? fromV1(msgs[i] as Message.Info) : (msgs[i] as MessageV2.Info) result.messages.push(msg) - if (assistant) { - result.cost += assistant.cost - result.tokens.input += assistant.tokens.input - result.tokens.output += assistant.tokens.output - result.tokens.reasoning += assistant.tokens.reasoning + if (msg.role === "assistant") { + result.cost += msg.cost + result.tokens.input += msg.tokens.input + result.tokens.output += msg.tokens.output + result.tokens.reasoning += msg.tokens.reasoning - result.models[`${assistant.providerID} ${assistant.modelID}`] = [ - assistant.providerID, - assistant.modelID, - ] + result.models[`${msg.providerID} ${msg.modelID}`] = [msg.providerID, msg.modelID] - if (assistant.path?.root) { - result.rootDir = assistant.path.root + if (msg.path.root) { + result.rootDir = msg.path.root } - if (msg.metadata?.time.completed) { - result.completed = msg.metadata?.time.completed + if (msg.time.completed) { + result.completed = msg.time.completed } } } + console.log(result.messages) return result }) return ( -
-
-
-

{store.info?.title}

-
-
-
    -
  • -
    +
    +
    +

    {store.info?.title}

    +
    +
      +
    • +
      @@ -815,11 +298,11 @@ export default function Share(props: { {Object.values(data().models).length > 0 ? ( {([provider, model]) => ( -
    • -
      - +
    • +
      +
      - {model} + {model}
    • )} @@ -830,1086 +313,52 @@ export default function Share(props: { )}
    -
    - {data().created ? ( - - {DateTime.fromMillis(data().created || 0).toLocaleString( - DateTime.DATETIME_MED, - )} - - ) : ( - - Started at — - - )} +
    + {DateTime.fromMillis(data().created || 0).toLocaleString(DateTime.DATETIME_MED)}
    - 0} - fallback={

    Waiting for messages...

    } - > + 0} fallback={

    Waiting for messages...

    }>
    {(msg, msgIndex) => ( - + { + if (x.type === "step-start" && index > 0) return false + if (x.type === "tool" && x.tool === "todoread") return false + if (x.type === "text" && !x.text) return false + if (x.type === "tool" && (x.state.status === "pending" || x.state.status === "running")) + return false + return true + })} + > {(part, partIndex) => { - if ( - (part.type === "step-start" && - (partIndex() > 0 || !msg.metadata?.assistant)) || - (msg.role === "assistant" && - part.type === "tool-invocation" && - part.toolInvocation.toolName === "todoread") + const last = createMemo( + () => data().messages.length === msgIndex() + 1 && msg.parts.length === partIndex() + 1, ) - return null - - const anchor = createMemo( - () => `${msg.id}-${partIndex()}`, - ) - const [showResults, setShowResults] = - createSignal(false) - const isLastPart = createMemo( - () => - data().messages.length === msgIndex() + 1 && - msg.parts.length === partIndex() + 1, - ) - const toolData = createMemo(() => { - if ( - msg.role !== "assistant" || - part.type !== "tool-invocation" - ) - return {} - - const metadata = - msg.metadata?.tool[part.toolInvocation.toolCallId] - const args = part.toolInvocation.args - const result = - part.toolInvocation.state === "result" && - part.toolInvocation.result - const duration = DateTime.fromMillis( - metadata?.time.end || 0, - ) - .diff( - DateTime.fromMillis(metadata?.time.start || 0), - ) - .toMillis() - - return { metadata, args, result, duration } - }) onMount(() => { const hash = window.location.hash.slice(1) // Wait till all parts are loaded if ( - hash !== "" - && !hasScrolledToAnchor - && msg.parts.length === partIndex() + 1 - && data().messages.length === msgIndex() + 1 + hash !== "" && + !hasScrolledToAnchor && + msg.parts.length === partIndex() + 1 && + data().messages.length === msgIndex() + 1 ) { hasScrolledToAnchor = true scrollToAnchor(hash) } }) - return ( - - {/* User text */} - - {(part) => ( -
    -
    - - - -
    -
    -
    - -
    -
    - )} -
    - {/* AI text */} - - {(part) => ( -
    -
    - - - -
    -
    -
    - - - - {DateTime.fromMillis( - data().completed || 0, - ).toLocaleString(DateTime.DATETIME_MED)} - - -
    -
    - )} -
    - {/* AI model */} - - {(assistant) => { - return ( -
    -
    - - - -
    -
    -
    -
    -
    - - {assistant().providerID} - -
    - - {assistant().modelID} - -
    -
    -
    - ) - }} -
    - - {/* Grep tool */} - - {(_part) => { - const matches = () => - toolData()?.metadata?.matches - const splitArgs = () => { - const { pattern, ...rest } = toolData()?.args - return { pattern, rest } - } - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Grep - - “{splitArgs().pattern}” - -
    - 0 - } - > -
    - - {([name, value]) => ( - <> -
    -
    {name}
    -
    {value}
    - - )} -
    -
    -
    - - 0}> -
    - - setShowResults((e) => !e) - } - /> - - - -
    -
    - -
    - -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Glob tool */} - - {(_part) => { - const count = () => toolData()?.metadata?.count - const pattern = () => toolData()?.args.pattern - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Glob - “{pattern()}” -
    - - 0}> -
    - - setShowResults((e) => !e) - } - /> - - - -
    -
    - -
    - -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* LS tool */} - - {(_part) => { - const path = createMemo(() => - toolData()?.args?.path !== data().rootDir - ? stripWorkingDirectory( - toolData()?.args?.path, - data().rootDir, - ) - : toolData()?.args?.path, - ) - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - LS - - {path()} - -
    - - -
    - - setShowResults((e) => !e) - } - /> - - - -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Read tool */} - - {(_part) => { - const filePath = createMemo(() => - stripWorkingDirectory( - toolData()?.args?.filePath, - data().rootDir, - ), - ) - const hasError = () => - toolData()?.metadata?.error - const preview = () => - toolData()?.metadata?.preview - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Read - - {filePath()} - -
    - - -
    - - {formatErrorString( - toolData()?.result, - )} - -
    -
    - {/* Always try to show CodeBlock if preview is available (even if empty string) */} - -
    - - setShowResults((e) => !e) - } - /> - -
    - -
    -
    -
    -
    - {/* Fallback to TextPart if preview is not a string (e.g. undefined) AND result exists */} - -
    - - setShowResults((e) => !e) - } - /> - - - -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Write tool */} - - {(_part) => { - const filePath = createMemo(() => - stripWorkingDirectory( - toolData()?.args?.filePath, - data().rootDir, - ), - ) - const hasError = () => - toolData()?.metadata?.error - const content = () => toolData()?.args?.content - const diagnostics = createMemo(() => - getDiagnostics( - toolData()?.metadata?.diagnostics, - toolData()?.args.filePath, - ), - ) - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Write - - {filePath()} - -
    - 0}> - {diagnostics()} - - - -
    - - {formatErrorString( - toolData()?.result, - )} - -
    -
    - -
    - - setShowResults((e) => !e) - } - /> - -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Edit tool */} - - {(_part) => { - const diff = () => toolData()?.metadata?.diff - const message = () => - toolData()?.metadata?.message - const hasError = () => - toolData()?.metadata?.error - const filePath = createMemo(() => - stripWorkingDirectory( - toolData()?.args.filePath, - data().rootDir, - ), - ) - const diagnostics = createMemo(() => - getDiagnostics( - toolData()?.metadata?.diagnostics, - toolData()?.args.filePath, - ), - ) - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Edit - - {filePath()} - -
    - - -
    - - {formatErrorString(message())} - -
    -
    - -
    - -
    -
    -
    - 0}> - {diagnostics()} - -
    - -
    -
    - ) - }} -
    - {/* Bash tool */} - - {(_part) => { - const command = () => - toolData()?.metadata?.title - const desc = () => - toolData()?.metadata?.description - const result = () => - toolData()?.metadata?.stdout - const error = () => toolData()?.metadata?.stderr - - return ( -
    -
    - - - -
    -
    -
    - {command() && ( -
    - -
    - )} - -
    -
    - ) - }} -
    - {/* Todo write */} - - {(_part) => { - const todos = createMemo(() => - sortTodosByStatus( - toolData()?.args?.todos ?? [], - ), - ) - const starting = () => - todos().every((t) => t.status === "pending") - const finished = () => - todos().every((t) => t.status === "completed") - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - - - - Creating plan - - - Completing plan - - - -
    - 0}> -
      - - {(todo) => ( -
    • - - {todo.content} -
    • - )} -
      -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Fetch tool */} - - {(_part) => { - const url = () => toolData()?.args.url - const format = () => toolData()?.args.format - const hasError = () => - toolData()?.metadata?.error - - return ( -
    -
    - - - -
    -
    -
    -
    -
    - Fetch - {url()} -
    - - -
    - - {formatErrorString( - toolData()?.result, - )} - -
    -
    - -
    - - setShowResults((e) => !e) - } - /> - -
    - -
    -
    -
    -
    -
    -
    - -
    -
    - ) - }} -
    - {/* Tool call */} - - {(part) => { - return ( -
    -
    - - - -
    -
    -
    -
    -
    - {part().toolInvocation.toolName} -
    -
    - - {(arg) => ( - <> -
    -
    {arg[0]}
    -
    {arg[1]}
    - - )} -
    -
    - - -
    - - setShowResults((e) => !e) - } - /> - - - -
    -
    - - - -
    -
    - -
    -
    - ) - }} -
    - {/* Fallback */} - -
    -
    - - - } - > - - - - - - - - - -
    -
    -
    -
    -
    - - {part.type} - -
    - -
    -
    -
    -
    -
    - ) + return }}
    @@ -1934,19 +383,11 @@ export default function Share(props: {
  • Input Tokens - {data().tokens.input ? ( - {data().tokens.input} - ) : ( - - )} + {data().tokens.input ? {data().tokens.input} : }
  • Output Tokens - {data().tokens.output ? ( - {data().tokens.output} - ) : ( - - )} + {data().tokens.output ? {data().tokens.output} : }
  • Reasoning Tokens @@ -1972,10 +413,7 @@ export default function Share(props: { "overflow-y": "auto", }} > - 0} - fallback={

    Waiting for messages...

    } - > + 0} fallback={

    Waiting for messages...

    }>
      {(msg) => ( @@ -2003,9 +441,7 @@ export default function Share(props: {
) } + +export function fromV1(v1: Message.Info): MessageV2.Info { + if (v1.role === "assistant") { + const result: MessageV2.Assistant = { + id: v1.id, + sessionID: v1.metadata.sessionID, + role: "assistant", + time: { + created: v1.metadata.time.created, + completed: v1.metadata.time.completed, + }, + cost: v1.metadata.assistant!.cost, + path: v1.metadata.assistant!.path, + summary: v1.metadata.assistant!.summary, + tokens: v1.metadata.assistant!.tokens, + modelID: v1.metadata.assistant!.modelID, + providerID: v1.metadata.assistant!.providerID, + system: v1.metadata.assistant!.system, + error: v1.metadata.error, + parts: v1.parts.flatMap((part): MessageV2.AssistantPart[] => { + if (part.type === "text") { + return [ + { + type: "text", + text: part.text, + }, + ] + } + if (part.type === "step-start") { + return [ + { + type: "step-start", + }, + ] + } + if (part.type === "tool-invocation") { + return [ + { + type: "tool", + id: part.toolInvocation.toolCallId, + tool: part.toolInvocation.toolName, + state: (() => { + if (part.toolInvocation.state === "partial-call") { + return { + status: "pending", + } + } + + const { title, time, ...metadata } = v1.metadata.tool[part.toolInvocation.toolCallId] + if (part.toolInvocation.state === "call") { + return { + status: "running", + input: part.toolInvocation.args, + time: { + start: time.start, + }, + } + } + + if (part.toolInvocation.state === "result") { + return { + status: "completed", + input: part.toolInvocation.args, + output: part.toolInvocation.result, + title, + time, + metadata, + } + } + throw new Error("unknown tool invocation state") + })(), + }, + ] + } + return [] + }), + } + return result + } + + if (v1.role === "user") { + const result: MessageV2.User = { + id: v1.id, + sessionID: v1.metadata.sessionID, + role: "user", + time: { + created: v1.metadata.time.created, + }, + parts: v1.parts.flatMap((part): MessageV2.UserPart[] => { + if (part.type === "text") { + return [ + { + type: "text", + text: part.text, + }, + ] + } + if (part.type === "file") { + return [ + { + type: "file", + mime: part.mediaType, + filename: part.filename, + url: part.url, + }, + ] + } + return [] + }), + } + return result + } + + throw new Error("unknown message type") +} diff --git a/packages/web/src/components/codeblock.module.css b/packages/web/src/components/codeblock.module.css index ddd88ef1..53120120 100644 --- a/packages/web/src/components/codeblock.module.css +++ b/packages/web/src/components/codeblock.module.css @@ -8,4 +8,3 @@ } } } - diff --git a/packages/web/src/components/diffview.module.css b/packages/web/src/components/diffview.module.css deleted file mode 100644 index a748c5d0..00000000 --- a/packages/web/src/components/diffview.module.css +++ /dev/null @@ -1,121 +0,0 @@ -.diff { - display: flex; - flex-direction: column; - border: 1px solid var(--sl-color-divider); - background-color: var(--sl-color-bg-surface); - border-radius: 0.25rem; -} - -.desktopView { - display: block; -} - -.mobileView { - display: none; -} - -.mobileBlock { - display: flex; - flex-direction: column; -} - -.row { - display: grid; - grid-template-columns: 1fr 1fr; - align-items: stretch; -} - -.beforeColumn, -.afterColumn { - display: flex; - flex-direction: column; - overflow-x: visible; - min-width: 0; - align-items: stretch; -} - -.beforeColumn { - border-right: 1px solid var(--sl-color-divider); -} - -.diff > .row:first-child [data-section="cell"]:first-child { - padding-top: 0.5rem; -} - -.diff > .row:last-child [data-section="cell"]:last-child { - padding-bottom: 0.5rem; -} - -[data-section="cell"] { - position: relative; - flex: 1; - display: flex; - flex-direction: column; - - width: 100%; - padding: 0.1875rem 0.5rem 0.1875rem 2.2ch; - margin: 0; - - &[data-display-mobile="true"] { - display: none; - } - - pre { - --shiki-dark-bg: var(--sl-color-bg-surface) !important; - background-color: var(--sl-color-bg-surface) !important; - - white-space: pre-wrap; - word-break: break-word; - - code > span:empty::before { - content: "\00a0"; - white-space: pre; - display: inline-block; - width: 0; - } - } -} - -[data-diff-type="removed"] { - background-color: var(--sl-color-red-low); - - pre { - --shiki-dark-bg: var(--sl-color-red-low) !important; - background-color: var(--sl-color-red-low) !important; - } - - &::before { - content: "-"; - position: absolute; - left: 0.5ch; - user-select: none; - color: var(--sl-color-red-high); - } -} - -[data-diff-type="added"] { - background-color: var(--sl-color-green-low); - - pre { - --shiki-dark-bg: var(--sl-color-green-low) !important; - background-color: var(--sl-color-green-low) !important; - } - - &::before { - content: "+"; - position: absolute; - left: 0.6ch; - user-select: none; - color: var(--sl-color-green-high); - } -} - -@media (max-width: 40rem) { - .desktopView { - display: none; - } - - .mobileView { - display: block; - } -} diff --git a/packages/web/src/components/icons/custom.tsx b/packages/web/src/components/icons/custom.tsx index b4e32d0c..95f64c19 100644 --- a/packages/web/src/components/icons/custom.tsx +++ b/packages/web/src/components/icons/custom.tsx @@ -39,8 +39,22 @@ export function IconGemini(props: JSX.SvgSVGAttributes) { export function IconOpencode(props: JSX.SvgSVGAttributes) { return ( - + ) } + +// https://icones.js.org/collection/ri?s=meta&icon=ri:meta-fill +export function IconMeta(props: JSX.SvgSVGAttributes) { + return ( + + + + ) +} diff --git a/packages/web/src/components/icons/index.tsx b/packages/web/src/components/icons/index.tsx index a788d8f4..62445611 100644 --- a/packages/web/src/components/icons/index.tsx +++ b/packages/web/src/components/icons/index.tsx @@ -3,12 +3,7 @@ import { type JSX } from "solid-js" export function IconAcademicCap(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconAdjustmentsHorizontal( - props: JSX.SvgSVGAttributes, -) { +export function IconAdjustmentsHorizontal(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconAdjustmentsVertical( - props: JSX.SvgSVGAttributes, -) { +export function IconAdjustmentsVertical(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArchiveBoxArrowDown( - props: JSX.SvgSVGAttributes, -) { +export function IconArchiveBoxArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArchiveBoxXMark( - props: JSX.SvgSVGAttributes, -) { +export function IconArchiveBoxXMark(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconArrowDownCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowDownCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconArrowDownOnSquareStack( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowDownOnSquareStack(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowDownOnSquare( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowDownOnSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconArrowDownTray(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconArrowLeftCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowLeftCircle(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowLeftOnRectangle( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowLeftOnRectangle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconArrowLongDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowLongLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowLongRight(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowLongUp(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconArrowPathRoundedSquare( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowPathRoundedSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconArrowRightCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowRightCircle(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowRightOnRectangle( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowRightOnRectangle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconArrowSmallDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowSmallLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconArrowSmallRight( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowSmallRight(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconArrowTopRightOnSquare( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowTopRightOnSquare(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowTrendingDown( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowTrendingDown(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowTrendingUp( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowTrendingUp(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconArrowUpLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconArrowUpOnSquareStack( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowUpOnSquareStack(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowUpOnSquare( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowUpOnSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconArrowUpTray(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowUp(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowUturnDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconArrowUturnLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconArrowUturnRight( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowUturnRight(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconArrowsPointingIn( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowsPointingIn(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowsPointingOut( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowsPointingOut(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconArrowsRightLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconArrowsRightLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconAtSymbol(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBackspace(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBackward(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBanknotes(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBars2(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconBars3BottomLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconBars3BottomLeft(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconBars3BottomRight( - props: JSX.SvgSVGAttributes, -) { +export function IconBars3BottomRight(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconBars3CenterLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconBars3CenterLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconBars4(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBarsArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBarsArrowUp(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBattery0(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBattery100(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBattery50(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBeaker(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBellAlert(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBellSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBellSnooze(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBell(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBoltSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBolt(props: JSX.SvgSVGAttributes) { return ( - + ) { export function IconBoltSolid(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBookOpen(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBookmarkSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBookmarkSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBookmark(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBriefcase(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconBugAnt(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconBuildingLibrary( - props: JSX.SvgSVGAttributes, -) { +export function IconBuildingLibrary(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconBuildingOffice2( - props: JSX.SvgSVGAttributes, -) { +export function IconBuildingOffice2(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconBuildingStorefront( - props: JSX.SvgSVGAttributes, -) { +export function IconBuildingStorefront(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconCalculator(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCalendarDays(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCalendar(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCamera(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChartBarSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChartBar(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChartPie(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconChatBubbleBottomCenterText( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleBottomCenterText(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChatBubbleBottomCenter( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleBottomCenter(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChatBubbleLeftEllipsis( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleLeftEllipsis(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChatBubbleLeftRight( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleLeftRight(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconChatBubbleOvalLeftEllipsis( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleOvalLeftEllipsis(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChatBubbleOvalLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconChatBubbleOvalLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconCheckCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCheck(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconChevronDoubleDown( - props: JSX.SvgSVGAttributes, -) { +export function IconChevronDoubleDown(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChevronDoubleLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconChevronDoubleLeft(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChevronDoubleRight( - props: JSX.SvgSVGAttributes, -) { +export function IconChevronDoubleRight(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconChevronDoubleUp( - props: JSX.SvgSVGAttributes, -) { +export function IconChevronDoubleUp(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconChevronLeft(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChevronRight(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChevronUpDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconChevronUp(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCircleStack(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconClipboardDocumentCheck( - props: JSX.SvgSVGAttributes, -) { +export function IconClipboardDocumentCheck(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconClipboardDocumentList( - props: JSX.SvgSVGAttributes, -) { +export function IconClipboardDocumentList(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconClipboardDocument( - props: JSX.SvgSVGAttributes, -) { +export function IconClipboardDocument(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconClock(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCloudArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCloudArrowUp(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCloud(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconCodeBracketSquare( - props: JSX.SvgSVGAttributes, -) { +export function IconCodeBracketSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconCog6Tooth(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCog8Tooth(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCog(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCommandLine(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconComputerDesktop( - props: JSX.SvgSVGAttributes, -) { +export function IconComputerDesktop(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconCreditCard(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconCubeTransparent( - props: JSX.SvgSVGAttributes, -) { +export function IconCubeTransparent(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconCurrencyBangladeshi( - props: JSX.SvgSVGAttributes, -) { +export function IconCurrencyBangladeshi(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconCurrencyEuro(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCurrencyPound(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCurrencyRupee(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconCurrencyYen(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconCursorArrowRays( - props: JSX.SvgSVGAttributes, -) { +export function IconCursorArrowRays(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconCursorArrowRipple( - props: JSX.SvgSVGAttributes, -) { +export function IconCursorArrowRipple(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconDevicePhoneMobile( - props: JSX.SvgSVGAttributes, -) { +export function IconDevicePhoneMobile(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconDocumentArrowDown( - props: JSX.SvgSVGAttributes, -) { +export function IconDocumentArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconDocumentArrowUp( - props: JSX.SvgSVGAttributes, -) { +export function IconDocumentArrowUp(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconDocumentChartBar( - props: JSX.SvgSVGAttributes, -) { +export function IconDocumentChartBar(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { ) } -export function IconDocumentDuplicate( - props: JSX.SvgSVGAttributes, -) { +export function IconDocumentDuplicate(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconDocumentMagnifyingGlass( - props: JSX.SvgSVGAttributes, -) { +export function IconDocumentMagnifyingGlass(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconDocumentPlus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconDocumentText(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconDocument(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconEllipsisHorizontalCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconEllipsisHorizontalCircle(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconEllipsisHorizontal( - props: JSX.SvgSVGAttributes, -) { +export function IconEllipsisHorizontal(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconEllipsisVertical( - props: JSX.SvgSVGAttributes, -) { +export function IconEllipsisVertical(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconEnvelope(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconEnvelopeSolid(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconExclamationCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconExclamationCircle(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconExclamationTriangle( - props: JSX.SvgSVGAttributes, -) { +export function IconExclamationTriangle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconEyeSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconEye(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFaceFrown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFaceSmile(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFilm(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFingerPrint(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFire(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFlag(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconFolderArrowDown( - props: JSX.SvgSVGAttributes, -) { +export function IconFolderArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconFolderOpen(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFolderPlus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFolder(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconForward(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconFunnel(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconGif(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconGiftTop(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconGift(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconGlobeAlt(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconGlobeAmericas(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconGlobeAsiaAustralia( - props: JSX.SvgSVGAttributes, -) { +export function IconGlobeAsiaAustralia(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconGlobeEuropeAfrica( - props: JSX.SvgSVGAttributes, -) { +export function IconGlobeEuropeAfrica(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconHandThumbDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconHandThumbUp(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconHashtag(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconHeart(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconHomeModern(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconHome(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconIdentification(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconInboxArrowDown(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconInboxStack(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconInbox(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconInformationCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconInformationCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconLanguage(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLifebuoy(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLightBulb(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLink(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconListBullet(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLockClosed(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLockOpen(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconMagnifyingGlassCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconMagnifyingGlassCircle(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconMagnifyingGlassMinus( - props: JSX.SvgSVGAttributes, -) { +export function IconMagnifyingGlassMinus(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconMagnifyingGlassPlus( - props: JSX.SvgSVGAttributes, -) { +export function IconMagnifyingGlassPlus(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconMagnifyingGlass( - props: JSX.SvgSVGAttributes, -) { +export function IconMagnifyingGlass(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconMap(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMegaphone(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMicrophone(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMinusCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMinusSmall(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMinus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMoon(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMusicalNote(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconNewspaper(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconNoSymbol(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPaintBrush(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPaperAirplane(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPaperClip(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPauseCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPause(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPencilSquare(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPencil(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconPhoneArrowDownLeft( - props: JSX.SvgSVGAttributes, -) { +export function IconPhoneArrowDownLeft(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconPhoneArrowUpRight( - props: JSX.SvgSVGAttributes, -) { +export function IconPhoneArrowUpRight(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconPhone(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPhoto(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlayCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlayPause(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlay(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlusCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlusSmall(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPlus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconPower(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconPresentationChartBar( - props: JSX.SvgSVGAttributes, -) { +export function IconPresentationChartBar(props: JSX.SvgSVGAttributes) { return ( - + ) } -export function IconPresentationChartLine( - props: JSX.SvgSVGAttributes, -) { +export function IconPresentationChartLine(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconPuzzlePiece(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconQrCode(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconQuestionMarkCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconQuestionMarkCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconRadio(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconReceiptPercent(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconReceiptRefund(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconRectangleGroup(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconRectangleStack(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconRocketLaunch(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconRss(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconScale(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconScissors(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconServerStack(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconServer(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconShare(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconShieldCheck(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconShieldExclamation( - props: JSX.SvgSVGAttributes, -) { +export function IconShieldExclamation(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconShoppingCart(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSignalSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSignal(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSparkles(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSpeakerWave(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSpeakerXMark(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSquare2Stack(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSquare3Stack3d(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSquares2x2(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSquaresPlus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconStar(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconStopCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconStop(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSun(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSwatch(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTableCells(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTag(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTicket(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTrash(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTrophy(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTruck(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconTv(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUserCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUserGroup(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUserMinus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUserPlus(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUser(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconUsers(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconVariable(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconVideoCameraSlash( - props: JSX.SvgSVGAttributes, -) { +export function IconVideoCameraSlash(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconViewColumns(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconViewfinderCircle( - props: JSX.SvgSVGAttributes, -) { +export function IconViewfinderCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconWifi(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconWindow(props: JSX.SvgSVGAttributes) { return ( - + ) { ) } -export function IconWrenchScrewdriver( - props: JSX.SvgSVGAttributes, -) { +export function IconWrenchScrewdriver(props: JSX.SvgSVGAttributes) { return ( - + ) { return ( - + ) { } export function IconXCircle(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconXMark(props: JSX.SvgSVGAttributes) { return ( - + ) { // index export function IconCommand(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconLetter(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconMultiSelect(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSettings(props: JSX.SvgSVGAttributes) { return ( - + ) { } export function IconSingleSelect(props: JSX.SvgSVGAttributes) { return ( - + *:last-child { - margin-bottom: 0; - } - - pre { - --shiki-dark-bg: var(--sl-color-bg-surface) !important; - background-color: var(--sl-color-bg-surface) !important; - padding: 0.5rem 0.75rem; - line-height: 1.6; - font-size: 0.75rem; - white-space: pre-wrap; - word-break: break-word; - - span { - white-space: break-spaces; - } - } - - code { - font-weight: 500; - - &:not(pre code) { - &::before { - content: "`"; - font-weight: 700; - } - &::after { - content: "`"; - font-weight: 700; - } - } - } - - table { - border-collapse: collapse; - width: 100%; - } - - th, - td { - border: 1px solid var(--sl-color-border); - padding: 0.5rem 0.75rem; - text-align: left; - } - - th { - border-bottom: 1px solid var(--sl-color-border); - } - - /* Remove outer borders */ - table tr:first-child th, - table tr:first-child td { - border-top: none; - } - - table tr:last-child td { - border-bottom: none; - } - - table th:first-child, - table td:first-child { - border-left: none; - } - - table th:last-child, - table td:last-child { - border-right: none; - } -} diff --git a/packages/web/src/components/share.module.css b/packages/web/src/components/share.module.css index c339d2b8..9930e6b5 100644 --- a/packages/web/src/components/share.module.css +++ b/packages/web/src/components/share.module.css @@ -15,118 +15,106 @@ --lg-tool-width: 56rem; --term-icon: url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2060%2016'%20preserveAspectRatio%3D'xMidYMid%20meet'%3E%3Ccircle%20cx%3D'8'%20cy%3D'8'%20r%3D'8'%2F%3E%3Ccircle%20cx%3D'30'%20cy%3D'8'%20r%3D'8'%2F%3E%3Ccircle%20cx%3D'52'%20cy%3D'8'%20r%3D'8'%2F%3E%3C%2Fsvg%3E"); -} -[data-element-button-text] { - cursor: pointer; - appearance: none; - background-color: transparent; - border: none; - padding: 0; - color: var(--sl-color-text-secondary); - - &:hover { - color: var(--sl-color-text); - } - - &[data-element-button-more] { + [data-component="header"] { display: flex; - align-items: center; - gap: 0.125rem; - - span[data-button-icon] { - line-height: 1; - opacity: 0.85; - svg { - display: block; - } - } - } -} - -[data-element-label] { - text-transform: uppercase; - letter-spacing: -0.5px; - color: var(--sl-color-text-dimmed); -} - -.header { - display: flex; - flex-direction: column; - gap: 1rem; - - @media (max-width: 30rem) { + flex-direction: column; gap: 1rem; - } - [data-section="title"] { - h1 { - font-size: 2.75rem; - font-weight: 500; - line-height: 1.2; - letter-spacing: -0.05em; - display: -webkit-box; - -webkit-box-orient: vertical; - -webkit-line-clamp: 3; - overflow: hidden; - - @media (max-width: 30rem) { - font-size: 1.75rem; - line-height: 1.25; - -webkit-line-clamp: 3; - } + @media (max-width: 30rem) { + gap: 1rem; } } - [data-section="row"] { + [data-component="header-title"] { + font-size: 2.75rem; + font-weight: 500; + line-height: 1.2; + letter-spacing: -0.05em; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; + overflow: hidden; + + @media (max-width: 30rem) { + font-size: 1.75rem; + line-height: 1.25; + -webkit-line-clamp: 3; + } + } + + [data-component="header-details"] { display: flex; flex-direction: column; gap: 0.5rem; } - [data-section="stats"] { + [data-component="header-stats"] { list-style-type: none; padding: 0; margin: 0; display: flex; gap: 0.5rem 0.875rem; flex-wrap: wrap; + max-width: var(--lg-tool-width); - li { + [data-slot="item"] { display: flex; align-items: center; - gap: 0.5rem; + gap: 0.3125rem; font-size: 0.875rem; span[data-placeholder] { color: var(--sl-color-text-dimmed); } } + + [data-slot="icon"] { + flex: 0 0 auto; + color: var(--sl-color-text-dimmed); + opacity: 0.85; + + svg { + display: block; + } + } + + [data-slot="model"] { + color: var(--sl-color-text); + } } - [data-section="stats"] { - li { - gap: 0.3125rem; + [data-component="header-time"] { + color: var(--sl-color-text-dimmed); + font-size: 0.875rem; + } - [data-stat-icon] { - flex: 0 0 auto; - color: var(--sl-color-text-dimmed); + [data-component="text-button"] { + cursor: pointer; + appearance: none; + background-color: transparent; + border: none; + padding: 0; + color: var(--sl-color-text-secondary); + + &:hover { + color: var(--sl-color-text); + } + + &[data-element-button-more] { + display: flex; + align-items: center; + gap: 0.125rem; + + span[data-button-icon] { + line-height: 1; opacity: 0.85; + svg { display: block; } } - - span[data-stat-model] { - color: var(--sl-color-text); - } - } - } - - [data-section="time"] { - span { - color: var(--sl-color-text-dimmed); - font-size: 0.875rem; } } } @@ -170,10 +158,12 @@ svg:nth-child(3) { display: none; } + &:hover { svg:nth-child(1) { display: none; } + svg:nth-child(2) { display: block; } @@ -213,12 +203,14 @@ opacity: 1; visibility: visible; } + a, a:hover { svg:nth-child(1), svg:nth-child(2) { display: none; } + svg:nth-child(3) { display: block; } @@ -264,7 +256,7 @@ } b { - color: var(--sl-color-text); + color: var(--sl-color-text); word-break: break-all; font-weight: 500; } @@ -348,8 +340,7 @@ } [data-part-type="tool-grep"] { - &:not(:has([data-part-tool-args])) - > [data-section="content"] > [data-part-tool-body] { + &:not(:has([data-part-tool-args])) > [data-section="content"] > [data-part-tool-body] { gap: 0.5rem; } } @@ -374,6 +365,7 @@ } } } + [data-part-type="summary"] { & > [data-section="decoration"] { span:first-child { @@ -388,15 +380,19 @@ &[data-status="connected"] { background-color: var(--sl-color-green); } + &[data-status="connecting"] { background-color: var(--sl-color-orange); } + &[data-status="disconnected"] { background-color: var(--sl-color-divider); } + &[data-status="reconnecting"] { background-color: var(--sl-color-orange); } + &[data-status="error"] { background-color: var(--sl-color-red); } @@ -493,14 +489,20 @@ } } - &[data-background="none"] { background-color: transparent; } - &[data-background="blue"] { background-color: var(--sl-color-blue-low); } + &[data-background="none"] { + background-color: transparent; + } + + &[data-background="blue"] { + background-color: var(--sl-color-blue-low); + } &[data-expanded="true"] { pre { display: block; } } + &[data-expanded="false"] { pre { display: -webkit-box; @@ -536,20 +538,25 @@ span { margin-right: 0.25rem; + &:last-child { margin-right: 0; } } + span[data-color="red"] { color: var(--sl-color-red); } + span[data-color="dimmed"] { color: var(--sl-color-text-dimmed); } + span[data-marker="label"] { text-transform: uppercase; letter-spacing: -0.5px; } + span[data-separator] { margin-right: 0.375rem; } @@ -561,6 +568,7 @@ display: block; } } + &[data-expanded="false"] { [data-section="content"] { display: -webkit-box; @@ -575,7 +583,6 @@ padding: 2px 0; font-size: 0.75rem; } - } .message-terminal { @@ -611,7 +618,7 @@ } &::before { - content: ''; + content: ""; position: absolute; pointer-events: none; top: 8px; @@ -651,6 +658,7 @@ display: block; } } + &[data-expanded="false"] { pre { display: -webkit-box; @@ -693,6 +701,7 @@ display: block; } } + &[data-expanded="false"] { [data-element-markdown] { display: -webkit-box; @@ -750,10 +759,14 @@ &[data-status="pending"] { color: var(--sl-color-text); } + &[data-status="in_progress"] { color: var(--sl-color-text); - & > span { border-color: var(--sl-color-orange); } + & > span { + border-color: var(--sl-color-orange); + } + & > span::before { content: ""; position: absolute; @@ -764,10 +777,14 @@ box-shadow: inset 1rem 1rem var(--sl-color-orange-low); } } + &[data-status="completed"] { color: var(--sl-color-text-secondary); - & > span { border-color: var(--sl-color-green-low); } + & > span { + border-color: var(--sl-color-green-low); + } + & > span::before { content: ""; position: absolute; @@ -798,7 +815,9 @@ display: flex; align-items: center; justify-content: center; - transition: all 0.15s ease, opacity 0.5s ease; + transition: + all 0.15s ease, + opacity 0.5s ease; z-index: 100; appearance: none; opacity: 1; diff --git a/packages/web/src/components/share/common.tsx b/packages/web/src/components/share/common.tsx new file mode 100644 index 00000000..9f5221de --- /dev/null +++ b/packages/web/src/components/share/common.tsx @@ -0,0 +1,60 @@ +import { createSignal, onCleanup, splitProps } from "solid-js" +import type { JSX } from "solid-js/jsx-runtime" +import { IconCheckCircle, IconHashtag } from "../icons" + +interface AnchorProps extends JSX.HTMLAttributes { + id: string +} +export function AnchorIcon(props: AnchorProps) { + const [local, rest] = splitProps(props, ["id", "children"]) + const [copied, setCopied] = createSignal(false) + + return ( + + ) +} + +export function createOverflow() { + const [overflow, setOverflow] = createSignal(false) + return { + get status() { + return overflow() + }, + ref(el: HTMLElement) { + const ro = new ResizeObserver(() => { + if (el.scrollHeight > el.clientHeight + 1) { + setOverflow(true) + } + return + }) + ro.observe(el) + + onCleanup(() => { + ro.disconnect() + }) + }, + } +} diff --git a/packages/web/src/components/share/content-code.module.css b/packages/web/src/components/share/content-code.module.css new file mode 100644 index 00000000..9fa10567 --- /dev/null +++ b/packages/web/src/components/share/content-code.module.css @@ -0,0 +1,26 @@ +.root { + max-width: var(--md-tool-width); + border: 1px solid var(--sl-color-divider); + background-color: var(--sl-color-bg-surface); + border-radius: 0.25rem; + padding: 0.5rem calc(0.5rem + 3px); + + &[data-flush="true"] { + border: none; + background-color: transparent; + padding: 0; + } + + pre { + --shiki-dark-bg: var(--sl-color-bg-surface) !important; + background-color: var(--sl-color-bg-surface) !important; + line-height: 1.6; + font-size: 0.75rem; + white-space: pre-wrap; + word-break: break-word; + + span { + white-space: break-spaces; + } + } +} diff --git a/packages/web/src/components/share/content-code.tsx b/packages/web/src/components/share/content-code.tsx new file mode 100644 index 00000000..72352d1e --- /dev/null +++ b/packages/web/src/components/share/content-code.tsx @@ -0,0 +1,32 @@ +import { codeToHtml } from "shiki" +import { createResource, Suspense } from "solid-js" +import { transformerNotationDiff } from "@shikijs/transformers" +import style from "./content-code.module.css" + +interface Props { + code: string + lang?: string + flush?: boolean +} +export function ContentCode(props: Props) { + const [html] = createResource( + () => [props.code, props.lang], + async ([code, lang]) => { + // TODO: For testing delays + // await new Promise((resolve) => setTimeout(resolve, 3000)) + return (await codeToHtml(code || "", { + lang: lang || "text", + themes: { + light: "github-light", + dark: "github-dark", + }, + transformers: [transformerNotationDiff()], + })) as string + }, + ) + return ( + +
+ + ) +} diff --git a/packages/web/src/components/share/content-diff.module.css b/packages/web/src/components/share/content-diff.module.css new file mode 100644 index 00000000..718ae369 --- /dev/null +++ b/packages/web/src/components/share/content-diff.module.css @@ -0,0 +1,125 @@ +.root { + display: flex; + flex-direction: column; + border: 1px solid var(--sl-color-divider); + background-color: var(--sl-color-bg-surface); + border-radius: 0.25rem; + + [data-component="desktop"] { + display: block; + } + + [data-component="mobile"] { + display: none; + } + + [data-component="diff-block"] { + display: flex; + flex-direction: column; + } + + [data-component="diff-row"] { + display: grid; + grid-template-columns: 1fr 1fr; + align-items: stretch; + + [data-slot="before"], + [data-slot="after"] { + position: relative; + display: flex; + flex-direction: column; + overflow-x: visible; + min-width: 0; + align-items: stretch; + padding: 0 1rem; + + &[data-diff-type="removed"] { + background-color: var(--sl-color-red-low); + + pre { + --shiki-dark-bg: var(--sl-color-red-low) !important; + background-color: var(--sl-color-red-low) !important; + } + + &::before { + content: "-"; + position: absolute; + left: 0.5ch; + top: 1px; + user-select: none; + color: var(--sl-color-red-high); + } + } + + &[data-diff-type="added"] { + background-color: var(--sl-color-green-low); + + pre { + --shiki-dark-bg: var(--sl-color-green-low) !important; + background-color: var(--sl-color-green-low) !important; + } + + &::before { + content: "+"; + position: absolute; + user-select: none; + color: var(--sl-color-green-high); + left: 0.5ch; + top: 1px; + } + } + } + + [data-slot="before"] { + border-right: 1px solid var(--sl-color-divider); + } + } + + .diff > .row:first-child [data-section="cell"]:first-child { + padding-top: 0.5rem; + } + + .diff > .row:last-child [data-section="cell"]:last-child { + padding-bottom: 0.5rem; + } + + [data-section="cell"] { + position: relative; + flex: 1; + display: flex; + flex-direction: column; + + width: 100%; + padding: 0.1875rem 0.5rem 0.1875rem 2.2ch; + margin: 0; + + &[data-display-mobile="true"] { + display: none; + } + + pre { + --shiki-dark-bg: var(--sl-color-bg-surface) !important; + background-color: var(--sl-color-bg-surface) !important; + + white-space: pre-wrap; + word-break: break-word; + + code > span:empty::before { + content: "\00a0"; + white-space: pre; + display: inline-block; + width: 0; + } + } + } + + @media (max-width: 40rem) { + [data-slot="desktop"] { + display: none; + } + + [data-slot="mobile"] { + display: block; + } + } +} diff --git a/packages/web/src/components/DiffView.tsx b/packages/web/src/components/share/content-diff.tsx similarity index 67% rename from packages/web/src/components/DiffView.tsx rename to packages/web/src/components/share/content-diff.tsx index 66dd7f0f..894145c3 100644 --- a/packages/web/src/components/DiffView.tsx +++ b/packages/web/src/components/share/content-diff.tsx @@ -1,7 +1,7 @@ import { type Component, createMemo } from "solid-js" import { parsePatch } from "diff" -import CodeBlock from "./CodeBlock" -import styles from "./diffview.module.css" +import { ContentCode } from "./content-code" +import styles from "./content-diff.module.css" type DiffRow = { left: string @@ -9,14 +9,12 @@ type DiffRow = { type: "added" | "removed" | "unchanged" | "modified" } -interface DiffViewProps { +interface Props { diff: string lang?: string - class?: string } -const DiffView: Component = (props) => { - +export function ContentDiff(props: Props) { const rows = createMemo(() => { const diffRows: DiffRow[] = [] @@ -33,20 +31,20 @@ const DiffView: Component = (props) => { const content = line.slice(1) const prefix = line[0] - if (prefix === '-') { + if (prefix === "-") { // Look ahead for consecutive additions to pair with removals const removals: string[] = [content] let j = i + 1 // Collect all consecutive removals - while (j < lines.length && lines[j][0] === '-') { + while (j < lines.length && lines[j][0] === "-") { removals.push(lines[j].slice(1)) j++ } // Collect all consecutive additions that follow const additions: string[] = [] - while (j < lines.length && lines[j][0] === '+') { + while (j < lines.length && lines[j][0] === "+") { additions.push(lines[j].slice(1)) j++ } @@ -62,39 +60,39 @@ const DiffView: Component = (props) => { diffRows.push({ left: removals[k], right: additions[k], - type: "modified" + type: "modified", }) } else if (hasLeft) { // Pure removal diffRows.push({ left: removals[k], right: "", - type: "removed" + type: "removed", }) } else if (hasRight) { // Pure addition - only create if we actually have content diffRows.push({ left: "", right: additions[k], - type: "added" + type: "added", }) } } i = j - } else if (prefix === '+') { + } else if (prefix === "+") { // Standalone addition (not paired with removal) diffRows.push({ left: "", right: content, - type: "added" + type: "added", }) i++ - } else if (prefix === ' ') { + } else if (prefix === " ") { diffRows.push({ left: content, right: content, - type: "unchanged" + type: "unchanged", }) i++ } else { @@ -112,7 +110,7 @@ const DiffView: Component = (props) => { }) const mobileRows = createMemo(() => { - const mobileBlocks: { type: 'removed' | 'added' | 'unchanged', lines: string[] }[] = [] + const mobileBlocks: { type: "removed" | "added" | "unchanged"; lines: string[] }[] = [] const currentRows = rows() let i = 0 @@ -121,15 +119,15 @@ const DiffView: Component = (props) => { const addedLines: string[] = [] // Collect consecutive modified/removed/added rows - while (i < currentRows.length && - (currentRows[i].type === 'modified' || - currentRows[i].type === 'removed' || - currentRows[i].type === 'added')) { + while ( + i < currentRows.length && + (currentRows[i].type === "modified" || currentRows[i].type === "removed" || currentRows[i].type === "added") + ) { const row = currentRows[i] - if (row.left && (row.type === 'removed' || row.type === 'modified')) { + if (row.left && (row.type === "removed" || row.type === "modified")) { removedLines.push(row.left) } - if (row.right && (row.type === 'added' || row.type === 'modified')) { + if (row.right && (row.type === "added" || row.type === "modified")) { addedLines.push(row.right) } i++ @@ -137,17 +135,17 @@ const DiffView: Component = (props) => { // Add grouped blocks if (removedLines.length > 0) { - mobileBlocks.push({ type: 'removed', lines: removedLines }) + mobileBlocks.push({ type: "removed", lines: removedLines }) } if (addedLines.length > 0) { - mobileBlocks.push({ type: 'added', lines: addedLines }) + mobileBlocks.push({ type: "added", lines: addedLines }) } // Add unchanged rows as-is - if (i < currentRows.length && currentRows[i].type === 'unchanged') { + if (i < currentRows.length && currentRows[i].type === "unchanged") { mobileBlocks.push({ - type: 'unchanged', - lines: [currentRows[i].left] + type: "unchanged", + lines: [currentRows[i].left], }) i++ } @@ -157,40 +155,29 @@ const DiffView: Component = (props) => { }) return ( -
-
+
+
{rows().map((r) => ( -
-
- +
+
+
-
- +
+
))}
-
+
{mobileRows().map((block) => ( -
+
{block.lines.map((line) => ( - ))}
@@ -200,8 +187,6 @@ const DiffView: Component = (props) => { ) } -export default DiffView - // const testDiff = `--- combined_before.txt 2025-06-24 16:38:08 // +++ combined_after.txt 2025-06-24 16:38:12 // @@ -1,21 +1,25 @@ @@ -210,12 +195,12 @@ export default DiffView // -old content // +added line // +new content -// +// // -removed empty line below // +added empty line above -// +// // - tab indented -// -trailing spaces +// -trailing spaces // -very long line that will definitely wrap in most editors and cause potential alignment issues when displayed in a two column diff view // -unicode content: 🚀 ✨ 中文 // -mixed content with tabs and spaces @@ -226,14 +211,14 @@ export default DiffView // +different unicode: 🎉 💻 日本語 // +normalized content with consistent spacing // +newline to content -// +// // -content to remove -// -whitespace only: +// -whitespace only: // -multiple // -consecutive // -deletions // -single deletion -// + +// + // +single addition // +first addition // +second addition diff --git a/packages/web/src/components/share/content-error.module.css b/packages/web/src/components/share/content-error.module.css new file mode 100644 index 00000000..70645d6b --- /dev/null +++ b/packages/web/src/components/share/content-error.module.css @@ -0,0 +1,66 @@ +.root { + background-color: var(--sl-color-bg-surface); + padding: 0.5rem calc(0.5rem + 3px); + border-radius: 0.25rem; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 1rem; + align-self: flex-start; + max-width: var(--md-tool-width); + + [data-section="content"] { + pre { + margin-bottom: 0.5rem; + line-height: 1.5; + font-size: 0.75rem; + white-space: pre-wrap; + word-break: break-word; + + &:last-child { + margin-bottom: 0; + } + + span { + margin-right: 0.25rem; + &:last-child { + margin-right: 0; + } + } + span[data-color="red"] { + color: var(--sl-color-red); + } + span[data-color="dimmed"] { + color: var(--sl-color-text-dimmed); + } + span[data-marker="label"] { + text-transform: uppercase; + letter-spacing: -0.5px; + } + span[data-separator] { + margin-right: 0.375rem; + } + } + } + + &[data-expanded="true"] { + [data-section="content"] { + display: block; + } + } + &[data-expanded="false"] { + [data-section="content"] { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 7; + overflow: hidden; + } + } + + button { + flex: 0 0 auto; + padding: 2px 0; + font-size: 0.75rem; + } + +} diff --git a/packages/web/src/components/share/content-error.tsx b/packages/web/src/components/share/content-error.tsx new file mode 100644 index 00000000..b6d7023b --- /dev/null +++ b/packages/web/src/components/share/content-error.tsx @@ -0,0 +1,31 @@ +import style from "./content-error.module.css" +import { type JSX, createSignal } from "solid-js" +import { createOverflow } from "./common" + +interface Props extends JSX.HTMLAttributes { + expand?: boolean +} +export function ContentError(props: Props) { + const [expanded, setExpanded] = createSignal(false) + const overflow = createOverflow() + + return ( +
+
+ {props.children} +
+ {((!props.expand && overflow.status) || expanded()) && ( + + )} +
+ ) +} diff --git a/packages/web/src/components/share/content-markdown.module.css b/packages/web/src/components/share/content-markdown.module.css new file mode 100644 index 00000000..da1aa112 --- /dev/null +++ b/packages/web/src/components/share/content-markdown.module.css @@ -0,0 +1,140 @@ +.root { + border: 1px solid var(--sl-color-blue-high); + padding: 0.5rem calc(0.5rem + 3px); + border-radius: 0.25rem; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 1rem; + align-self: flex-start; + max-width: var(--md-tool-width); + + &[data-highlight="true"] { + background-color: var(--sl-color-blue-low); + } + + [data-slot="expand-button"] { + flex: 0 0 auto; + padding: 2px 0; + font-size: 0.75rem; + } + + [data-slot="markdown"] { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; + overflow: hidden; + + [data-expanded] & { + display: block; + } + + font-size: 0.875rem; + line-height: 1.5; + + p, + blockquote, + ul, + ol, + dl, + table, + pre { + margin-bottom: 1rem; + } + + strong { + font-weight: 600; + } + + ol { + list-style-position: inside; + padding-left: 0.75rem; + } + + ul { + padding-left: 1.5rem; + } + + h1, + h2, + h3, + h4, + h5, + h6 { + font-size: 0.875rem; + font-weight: 600; + margin-bottom: 0.5rem; + } + + & > *:last-child { + margin-bottom: 0; + } + + pre { + --shiki-dark-bg: var(--sl-color-bg-surface) !important; + background-color: var(--sl-color-bg-surface) !important; + padding: 0.5rem 0.75rem; + line-height: 1.6; + font-size: 0.75rem; + white-space: pre-wrap; + word-break: break-word; + + span { + white-space: break-spaces; + } + } + + code { + font-weight: 500; + + &:not(pre code) { + &::before { + content: "`"; + font-weight: 700; + } + + &::after { + content: "`"; + font-weight: 700; + } + } + } + + table { + border-collapse: collapse; + width: 100%; + } + + th, + td { + border: 1px solid var(--sl-color-border); + padding: 0.5rem 0.75rem; + text-align: left; + } + + th { + border-bottom: 1px solid var(--sl-color-border); + } + + /* Remove outer borders */ + table tr:first-child th, + table tr:first-child td { + border-top: none; + } + + table tr:last-child td { + border-bottom: none; + } + + table th:first-child, + table td:first-child { + border-left: none; + } + + table th:last-child, + table td:last-child { + border-right: none; + } + } +} diff --git a/packages/web/src/components/share/content-markdown.tsx b/packages/web/src/components/share/content-markdown.tsx new file mode 100644 index 00000000..f7927129 --- /dev/null +++ b/packages/web/src/components/share/content-markdown.tsx @@ -0,0 +1,65 @@ +import style from "./content-markdown.module.css" +import { createResource, createSignal } from "solid-js" +import { createOverflow } from "./common" +import { transformerNotationDiff } from "@shikijs/transformers" +import { marked } from "marked" +import markedShiki from "marked-shiki" +import { codeToHtml } from "shiki" + +const markedWithShiki = marked.use( + markedShiki({ + highlight(code, lang) { + return codeToHtml(code, { + lang: lang || "text", + themes: { + light: "github-light", + dark: "github-dark", + }, + transformers: [transformerNotationDiff()], + }) + }, + }), +) + +interface Props { + text: string + expand?: boolean + highlight?: boolean +} +export function ContentMarkdown(props: Props) { + const [html] = createResource( + () => strip(props.text), + async (markdown) => { + return markedWithShiki.parse(markdown) + }, + ) + const [expanded, setExpanded] = createSignal(false) + const overflow = createOverflow() + + return ( +
+
+ + {!props.expand && overflow.status && ( + + )} +
+ ) +} + +function strip(text: string): string { + const wrappedRe = /^\s*<([A-Za-z]\w*)>\s*([\s\S]*?)\s*<\/\1>\s*$/ + const match = text.match(wrappedRe) + return match ? match[2] : text +} diff --git a/packages/web/src/components/share/content-text.module.css b/packages/web/src/components/share/content-text.module.css new file mode 100644 index 00000000..f8d0b0b9 --- /dev/null +++ b/packages/web/src/components/share/content-text.module.css @@ -0,0 +1,57 @@ +.root { + color: var(--sl-color-text); + background-color: var(--sl-color-bg-surface); + padding: 0.5rem calc(0.5rem + 3px); + border-radius: 0.25rem; + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 1rem; + align-self: flex-start; + max-width: var(--md-tool-width); + font-size: 0.875rem; + + &[data-compact] { + font-size: 0.75rem; + color: var(--sl-color-text-dimmed); + } + + [data-slot="text"] { + line-height: 1.5; + white-space: pre-wrap; + overflow-wrap: anywhere; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; + overflow: hidden; + + [data-expanded] & { + display: block; + } + } + + [data-slot="expand-button"] { + flex: 0 0 auto; + padding: 2px 0; + font-size: 0.75rem; + } + + &[data-theme="invert"] { + background-color: var(--sl-color-blue-high); + color: var(--sl-color-text-invert); + + [data-slot="expand-button"] { + opacity: 0.85; + color: var(--sl-color-text-invert); + + &:hover { + opacity: 1; + } + } + } + + &[data-theme="blue"] { + background-color: var(--sl-color-blue-low); + } +} diff --git a/packages/web/src/components/share/content-text.tsx b/packages/web/src/components/share/content-text.tsx new file mode 100644 index 00000000..c52e0dfc --- /dev/null +++ b/packages/web/src/components/share/content-text.tsx @@ -0,0 +1,35 @@ +import style from "./content-text.module.css" +import { createSignal } from "solid-js" +import { createOverflow } from "./common" + +interface Props { + text: string + expand?: boolean + compact?: boolean +} +export function ContentText(props: Props) { + const [expanded, setExpanded] = createSignal(false) + const overflow = createOverflow() + + return ( +
+
+        {props.text}
+      
+ {((!props.expand && overflow.status) || expanded()) && ( + + )} +
+ ) +} diff --git a/packages/web/src/components/share/part.module.css b/packages/web/src/components/share/part.module.css new file mode 100644 index 00000000..9145cddf --- /dev/null +++ b/packages/web/src/components/share/part.module.css @@ -0,0 +1,375 @@ +.root { + display: flex; + gap: 0.625rem; + + [data-component="decoration"] { + flex: 0 0 auto; + display: flex; + flex-direction: column; + gap: 0.625rem; + align-items: center; + justify-content: flex-start; + + [data-slot="anchor"] { + position: relative; + + a:first-child { + display: block; + flex: 0 0 auto; + width: 18px; + opacity: 0.65; + + svg { + color: var(--sl-color-text-secondary); + display: block; + + &:nth-child(3) { + color: var(--sl-color-green-high); + } + } + + svg:nth-child(2), + svg:nth-child(3) { + display: none; + } + + &:hover { + svg:nth-child(1) { + display: none; + } + + svg:nth-child(2) { + display: block; + } + } + } + + [data-copied] & { + a, + a:hover { + svg:nth-child(1), + svg:nth-child(2) { + display: none; + } + + svg:nth-child(3) { + display: block; + } + } + } + } + + [data-slot="bar"] { + width: 3px; + height: 100%; + border-radius: 1px; + background-color: var(--sl-color-hairline); + } + + [data-slot="tooltip"] { + position: absolute; + top: 50%; + left: calc(100% + 12px); + transform: translate(0, -50%); + line-height: 1.1; + padding: 0.375em 0.5em calc(0.375em + 2px); + background: var(--sl-color-white); + color: var(--sl-color-text-invert); + font-size: 0.6875rem; + border-radius: 7px; + white-space: nowrap; + + z-index: 1; + opacity: 0; + visibility: hidden; + + &::after { + content: ""; + position: absolute; + top: 50%; + left: -15px; + transform: translateY(-50%); + border: 8px solid transparent; + border-right-color: var(--sl-color-white); + } + + [data-copied] & { + opacity: 1; + visibility: visible; + } + } + } + + [data-component="content"] { + display: flex; + flex-direction: column; + gap: 1rem; + flex-grow: 1; + } + + [data-component="spacer"] { + height: 0rem; + } + + [data-component="content-footer"] { + align-self: flex-start; + font-size: 0.75rem; + color: var(--sl-color-text-dimmed); + } + + [data-component="step-start"] { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.375rem; + padding-bottom: 1rem; + + [data-slot="provider"] { + line-height: 18px; + font-size: 0.875rem; + text-transform: uppercase; + letter-spacing: -0.5px; + color: var(--sl-color-text-secondary); + } + + [data-slot="model"] { + line-height: 1.5; + } + } + + [data-component="button-text"] { + cursor: pointer; + appearance: none; + background-color: transparent; + border: none; + padding: 0; + color: var(--sl-color-text-secondary); + font-size: 0.75rem; + + &:hover { + color: var(--sl-color-text); + } + + &[data-more] { + display: flex; + align-items: center; + gap: 0.125rem; + + span[data-slot="icon"] { + line-height: 1; + opacity: 0.85; + + svg { + display: block; + } + } + } + } + + [data-component="tool"] { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.375rem; + padding-bottom: 1rem; + } + + [data-component="tool-title"] { + line-height: 18px; + font-size: 0.875rem; + color: var(--sl-color-text-secondary); + max-width: var(--md-tool-width); + display: flex; + align-items: flex-start; + gap: 0.375rem; + + [data-slot="name"] { + text-transform: uppercase; + letter-spacing: -0.5px; + } + + [data-slot="target"] { + color: var(--sl-color-text); + word-break: break-all; + font-weight: 500; + } + } + + [data-component="tool-result"] { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; + } + + [data-component="todos"] { + list-style-type: none; + padding: 0; + margin: 0; + width: 100%; + max-width: var(--sm-tool-width); + border: 1px solid var(--sl-color-divider); + border-radius: 0.25rem; + + [data-slot="item"] { + margin: 0; + position: relative; + padding-left: 1.5rem; + font-size: 0.75rem; + padding: 0.375rem 0.625rem 0.375rem 1.75rem; + border-bottom: 1px solid var(--sl-color-divider); + line-height: 1.5; + word-break: break-word; + + &:last-child { + border-bottom: none; + } + + & > span { + position: absolute; + display: inline-block; + left: 0.5rem; + top: calc(0.5rem + 1px); + width: 0.75rem; + height: 0.75rem; + border: 1px solid var(--sl-color-divider); + border-radius: 0.15rem; + + &::before { + } + } + + &[data-status="pending"] { + color: var(--sl-color-text); + } + + &[data-status="in_progress"] { + color: var(--sl-color-text); + + & > span { + border-color: var(--sl-color-orange); + } + + & > span::before { + content: ""; + position: absolute; + top: 2px; + left: 2px; + width: calc(0.75rem - 2px - 4px); + height: calc(0.75rem - 2px - 4px); + box-shadow: inset 1rem 1rem var(--sl-color-orange-low); + } + } + + &[data-status="completed"] { + color: var(--sl-color-text-secondary); + + & > span { + border-color: var(--sl-color-green-low); + } + + & > span::before { + content: ""; + position: absolute; + top: 2px; + left: 2px; + width: calc(0.75rem - 2px - 4px); + height: calc(0.75rem - 2px - 4px); + box-shadow: inset 1rem 1rem var(--sl-color-green); + + transform-origin: bottom left; + clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%); + } + } + } + } + + [data-component="terminal"] { + width: 100%; + max-width: var(--sm-tool-width); + + [data-slot="body"] { + display: flex; + flex-direction: column; + border: 1px solid var(--sl-color-divider); + border-radius: 0.25rem; + overflow: hidden; + } + + [data-slot="header"] { + position: relative; + border-bottom: 1px solid var(--sl-color-divider); + width: 100%; + height: 1.625rem; + text-align: center; + padding: 0 3.25rem; + + > span { + max-width: min(100%, 140ch); + display: inline-block; + white-space: nowrap; + overflow: hidden; + line-height: 1.625rem; + font-size: 0.75rem; + text-overflow: ellipsis; + color: var(--sl-color-text-dimmed); + } + + &::before { + content: ""; + position: absolute; + pointer-events: none; + top: 8px; + left: 10px; + width: 2rem; + height: 0.5rem; + line-height: 0; + background-color: var(--sl-color-hairline); + mask-image: var(--term-icon); + mask-repeat: no-repeat; + } + } + + [data-slot="content"] { + display: flex; + flex-direction: column; + padding: 0.5rem calc(0.5rem + 3px); + + pre { + --shiki-dark-bg: var(--sl-color-bg) !important; + background-color: var(--sl-color-bg) !important; + line-height: 1.6; + font-size: 0.75rem; + white-space: pre-wrap; + word-break: break-word; + } + } + } + + [data-component="tool-args"] { + display: inline-grid; + align-items: center; + grid-template-columns: max-content max-content minmax(0, 1fr); + max-width: var(--md-tool-width); + gap: 0.25rem 0.375rem; + + & > div:nth-child(3n + 1) { + width: 8px; + height: 2px; + border-radius: 1px; + background: var(--sl-color-divider); + } + + & > div:nth-child(3n + 2), + & > div:nth-child(3n + 3) { + font-size: 0.75rem; + line-height: 1.5; + } + + & > div:nth-child(3n + 3) { + padding-left: 0.125rem; + word-break: break-word; + color: var(--sl-color-text-secondary); + } + } +} diff --git a/packages/web/src/components/share/part.tsx b/packages/web/src/components/share/part.tsx new file mode 100644 index 00000000..4d95fa52 --- /dev/null +++ b/packages/web/src/components/share/part.tsx @@ -0,0 +1,733 @@ +import map from "lang-map" +import { DateTime } from "luxon" +import { + For, + Show, + Match, + Switch, + type JSX, + createMemo, + createSignal, + type ParentProps +} from "solid-js" +import { + IconHashtag, + IconSparkles, + IconGlobeAlt, + IconDocument, + IconQueueList, + IconUserCircle, + IconCommandLine, + IconCheckCircle, + IconChevronDown, + IconChevronRight, + IconDocumentPlus, + IconPencilSquare, + IconRectangleStack, + IconMagnifyingGlass, + IconDocumentMagnifyingGlass, +} from "../icons" +import { IconMeta, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom" +import { ContentCode } from "./content-code" +import { ContentDiff } from "./content-diff" +import { ContentText } from "./content-text" +import { ContentError } from "./content-error" +import { ContentMarkdown } from "./content-markdown" +import type { MessageV2 } from "opencode/session/message-v2" +import type { Diagnostic } from "vscode-languageserver-types" + +import styles from "./part.module.css" + +export interface PartProps { + index: number + message: MessageV2.Info + part: MessageV2.AssistantPart | MessageV2.UserPart + last: boolean +} + +export function Part(props: PartProps) { + const [copied, setCopied] = createSignal(false) + const id = createMemo(() => props.message.id + "-" + props.index) + + return ( +
+ +
+ {props.message.role === "user" && props.part.type === "text" && ( + <> + + + + )} + {props.message.role === "assistant" && props.part.type === "text" && ( + <> + + {props.last && props.message.role === "assistant" && props.message.time.completed && ( +
+ {DateTime.fromMillis(props.message.time.completed).toLocaleString(DateTime.DATETIME_MED)} +
+ )} + + + )} + {props.message.role === "user" && props.part.type === "file" && ( +
+ Read + + {props.part.filename} + +
+ )} + {props.part.type === "step-start" && props.message.role === "assistant" && ( +
+
{props.message.providerID}
+
{props.message.modelID}
+
+ )} + {props.part.type === "tool" && + props.part.state.status === "error" && ( +
+ + {formatErrorString(props.part.state.error)} + +
+ )} + {props.part.type === "tool" && + props.part.state.status === "completed" && + props.message.role === "assistant" && ( +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ )} +
+
+ ) +} + +type ToolProps = { + id: MessageV2.ToolPart["id"] + tool: MessageV2.ToolPart["tool"] + state: MessageV2.ToolStateCompleted + message: MessageV2.Assistant + isLastPart?: boolean +} + +interface Todo { + id: string + content: string + status: "pending" | "in_progress" | "completed" + priority: "low" | "medium" | "high" +} + +function stripWorkingDirectory(filePath?: string, workingDir?: string) { + if (filePath === undefined || workingDir === undefined) return filePath + + const prefix = workingDir.endsWith("/") ? workingDir : workingDir + "/" + + if (filePath === workingDir) { + return "" + } + + if (filePath.startsWith(prefix)) { + return filePath.slice(prefix.length) + } + + return filePath +} + +function getShikiLang(filename: string) { + const ext = filename.split(".").pop()?.toLowerCase() ?? "" + const langs = map.languages(ext) + const type = langs?.[0]?.toLowerCase() + + const overrides: Record = { + conf: "shellscript", + } + + return type ? (overrides[type] ?? type) : "plaintext" +} + +function getDiagnostics(diagnosticsByFile: Record, currentFile: string): JSX.Element[] { + const result: JSX.Element[] = [] + + if (diagnosticsByFile === undefined || diagnosticsByFile[currentFile] === undefined) return result + + for (const diags of Object.values(diagnosticsByFile)) { + for (const d of diags) { + if (d.severity !== 1) continue + + const line = d.range.start.line + 1 + const column = d.range.start.character + 1 + + result.push( +
+          
+            Error
+          
+          
+            [{line}:{column}]
+          
+          {d.message}
+        
, + ) + } + } + + return result +} + +function formatErrorString(error: string): JSX.Element { + const errorMarker = "Error: " + const startsWithError = error.startsWith(errorMarker) + + return startsWithError ? ( +
+      
+        Error
+      
+      {error.slice(errorMarker.length)}
+    
+ ) : ( +
+      {error}
+    
+ ) +} + +export function TodoWriteTool(props: ToolProps) { + const priority: Record = { + in_progress: 0, + pending: 1, + completed: 2, + } + const todos = createMemo(() => + ((props.state.input?.todos ?? []) as Todo[]).slice().sort((a, b) => priority[a.status] - priority[b.status]), + ) + const starting = () => todos().every((t: Todo) => t.status === "pending") + const finished = () => todos().every((t: Todo) => t.status === "completed") + + return ( + <> +
+ + + Creating plan + Completing plan + + +
+ 0}> +
    + + {(todo) => ( +
  • + + {todo.content} +
  • + )} +
    +
+
+ + ) +} + +export function GrepTool(props: ToolProps) { + return ( + <> +
+ Grep + “{props.state.input.pattern}” +
+
+ + 0}> + + + + + + + + +
+ + ) +} + +export function ListTool(props: ToolProps) { + const path = createMemo(() => + props.state.input?.path !== props.message.path.cwd + ? stripWorkingDirectory(props.state.input?.path, props.message.path.cwd) + : props.state.input?.path, + ) + + return ( + <> +
+ LS + + {path()} + +
+
+ + + + + + + +
+ + ) +} + +export function WebFetchTool(props: ToolProps) { + return ( + <> +
+ Fetch + {props.state.input.url} +
+
+ + + {formatErrorString(props.state.output)} + + + + + + + +
+ + ) +} + +export function ReadTool(props: ToolProps) { + const filePath = createMemo(() => stripWorkingDirectory(props.state.input?.filePath, props.message.path.cwd)) + + return ( + <> +
+ Read + + {filePath()} + +
+
+ + + {formatErrorString(props.state.output)} + + + + + + + + + + + + +
+ + ) +} + +export function WriteTool(props: ToolProps) { + const filePath = createMemo(() => stripWorkingDirectory(props.state.input?.filePath, props.message.path.cwd)) + const diagnostics = createMemo(() => getDiagnostics(props.state.metadata?.diagnostics, props.state.input.filePath)) + + return ( + <> +
+ Write + + {filePath()} + +
+ 0}> +
{diagnostics()}
+
+
+ + + {formatErrorString(props.state.output)} + + + + + + + +
+ + ) +} + +export function EditTool(props: ToolProps) { + const filePath = createMemo(() => stripWorkingDirectory(props.state.input.filePath, props.message.path.cwd)) + const diagnostics = createMemo(() => getDiagnostics(props.state.metadata?.diagnostics, props.state.input.filePath)) + + return ( + <> +
+ Edit + + {filePath()} + +
+
+ + + {formatErrorString(props.state.metadata?.message || "")} + + +
+ +
+
+
+
+ 0}> +
{diagnostics()}
+
+ + ) +} + +export function BashTool(props: ToolProps) { + return ( + <> +
+
+
+ {props.state.metadata.description} +
+
+ + +
+
+
+ + ) +} + +export function GlobTool(props: ToolProps) { + return ( + <> +
+ Glob + “{props.state.input.pattern}” +
+ + 0}> +
+ + + +
+
+ + + +
+ + ) +} + +interface ResultsButtonProps extends ParentProps { + showCopy?: string + hideCopy?: string +} +function ResultsButton(props: ResultsButtonProps) { + const [show, setShow] = createSignal(false) + + return ( + <> + + {props.children} + + ) +} + +export function Spacer() { + return
+} + +function Footer(props: ParentProps<{ title: string }>) { + return ( +
+ {props.children} +
+ ) +} + +export function FallbackTool(props: ToolProps) { + return ( + <> +
+ {props.tool} +
+
+ + {(arg) => ( + <> +
+
{arg[0]}
+
{arg[1]}
+ + )} +
+
+ + +
+ + + +
+
+
+ + ) +} + +// Converts nested objects/arrays into [path, value] pairs. +// E.g. {a:{b:{c:1}}, d:[{e:2}, 3]} => [["a.b.c",1], ["d[0].e",2], ["d[1]",3]] +function flattenToolArgs(obj: any, prefix: string = ""): Array<[string, any]> { + const entries: Array<[string, any]> = [] + + for (const [key, value] of Object.entries(obj)) { + const path = prefix ? `${prefix}.${key}` : key + + if (value !== null && typeof value === "object") { + if (Array.isArray(value)) { + value.forEach((item, index) => { + const arrayPath = `${path}[${index}]` + if (item !== null && typeof item === "object") { + entries.push(...flattenToolArgs(item, arrayPath)) + } else { + entries.push([arrayPath, item]) + } + }) + } else { + entries.push(...flattenToolArgs(value, path)) + } + } else { + entries.push([path, value]) + } + } + + return entries +} + +function getProvider(model: string) { + const lowerModel = model.toLowerCase() + + if (/claude|anthropic/.test(lowerModel)) return "anthropic" + if (/gpt|o[1-4]|codex|openai/.test(lowerModel)) return "openai" + if (/gemini|palm|bard|google/.test(lowerModel)) return "gemini" + if (/llama|meta/.test(lowerModel)) return "meta" + + return "any" +} + +export function ProviderIcon(props: { model: string; size?: number }) { + const provider = getProvider(props.model) + const size = props.size || 16 + return ( + }> + + + + + + + + + + + + + + ) +} diff --git a/packages/web/src/content/docs/docs/cli.mdx b/packages/web/src/content/docs/docs/cli.mdx index 49d343be..57e59521 100644 --- a/packages/web/src/content/docs/docs/cli.mdx +++ b/packages/web/src/content/docs/docs/cli.mdx @@ -39,12 +39,12 @@ opencode run Explain the use of context in Go #### Flags -| Flag | Short | Description | -| ----------------- | ----- | --------------------- | -| `--continue` | `-c` | Continue the last session | -| `--session` | `-s` | Session ID to continue | -| `--share` | | Share the session | -| `--model` | `-m` | Model to use in the form of provider/model | +| Flag | Short | Description | +| ------------ | ----- | ------------------------------------------ | +| `--continue` | `-c` | Continue the last session | +| `--session` | `-s` | Session ID to continue | +| `--share` | | Share the session | +| `--model` | `-m` | Model to use in the form of provider/model | --- @@ -122,8 +122,8 @@ opencode upgrade v0.1.48 The opencode CLI takes the following flags. -| Flag | Short | Description | -| ----------------- | ----- | --------------------- | -| `--help` | `-h` | Display help | -| `--version` | | Print version number | -| `--print-logs` | | Print logs to stderr | +| Flag | Short | Description | +| -------------- | ----- | -------------------- | +| `--help` | `-h` | Display help | +| `--version` | | Print version number | +| `--print-logs` | | Print logs to stderr | diff --git a/packages/web/src/content/docs/docs/config.mdx b/packages/web/src/content/docs/docs/config.mdx index d88749c6..78552d41 100644 --- a/packages/web/src/content/docs/docs/config.mdx +++ b/packages/web/src/content/docs/docs/config.mdx @@ -39,7 +39,7 @@ You can configure the providers and models you want to use in your opencode conf ```json title="opencode.json" { "$schema": "https://opencode.ai/config.json", - "provider": { }, + "provider": {}, "model": "" } ``` @@ -70,7 +70,7 @@ You can customize your keybinds through the `keybinds` option. ```json title="opencode.json" { "$schema": "https://opencode.ai/config.json", - "keybinds": { } + "keybinds": {} } ``` @@ -85,7 +85,7 @@ You can configure MCP servers you want to use through the `mcp` option. ```json title="opencode.json" { "$schema": "https://opencode.ai/config.json", - "mcp": { } + "mcp": {} } ``` @@ -93,6 +93,28 @@ You can configure MCP servers you want to use through the `mcp` option. --- +### Logging + +You can configure the minimum log level through the `log_level` option. This controls which log messages are written to the log files. + +```json title="opencode.json" +{ + "$schema": "https://opencode.ai/config.json", + "log_level": "INFO" +} +``` + +Available log levels are: + +- `DEBUG` - All messages including debug information +- `INFO` - Informational messages and above (default) +- `WARN` - Warnings and errors only +- `ERROR` - Errors only + +The default log level is `INFO` in production and `DEBUG` in development mode. + +--- + ### Disabled providers You can disable providers that are loaded automatically through the `disabled_providers` option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available. @@ -105,6 +127,7 @@ You can disable providers that are loaded automatically through the `disabled_pr ``` The `disabled_providers` option accepts an array of provider IDs. When a provider is disabled: + - It won't be loaded even if environment variables are set - It won't be loaded even if API keys are configured through `opencode auth login` - The provider's models won't appear in the model selection list diff --git a/packages/web/src/content/docs/docs/index.mdx b/packages/web/src/content/docs/docs/index.mdx index b39ce452..0484e9b3 100644 --- a/packages/web/src/content/docs/docs/index.mdx +++ b/packages/web/src/content/docs/docs/index.mdx @@ -3,7 +3,7 @@ title: Intro description: Get started with opencode. --- -import { Tabs, TabItem } from '@astrojs/starlight/components'; +import { Tabs, TabItem } from "@astrojs/starlight/components" [**opencode**](/) is an AI coding agent built for the terminal. It features: @@ -22,24 +22,24 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; - ```bash - npm install -g opencode-ai - ``` + ```bash + npm install -g opencode-ai + ``` - ```bash - bun install -g opencode-ai - ``` + ```bash + bun install -g opencode-ai + ``` - ```bash - pnpm install -g opencode-ai - ``` + ```bash + pnpm install -g opencode-ai + ``` - ```bash - yarn global add opencode-ai - ``` + ```bash + yarn global add opencode-ai + ``` diff --git a/packages/web/src/content/docs/docs/rules.mdx b/packages/web/src/content/docs/docs/rules.mdx index b7818d71..3249cc3f 100644 --- a/packages/web/src/content/docs/docs/rules.mdx +++ b/packages/web/src/content/docs/docs/rules.mdx @@ -31,17 +31,20 @@ You can also just create this file manually. Here's an example of some things yo This is an SST v3 monorepo with TypeScript. The project uses bun workspaces for package management. ## Project Structure + - `packages/` - Contains all workspace packages (functions, core, web, etc.) - `infra/` - Infrastructure definitions split by service (storage.ts, api.ts, web.ts) - `sst.config.ts` - Main SST configuration with dynamic imports ## Code Standards + - Use TypeScript with strict mode enabled - Shared code goes in `packages/core/` with proper exports configuration - Functions go in `packages/functions/` - Infrastructure should be split into logical files in `infra/` ## Monorepo Conventions + - Import shared modules using workspace names: `@my-app/core/example` ``` @@ -78,23 +81,14 @@ If you have both global and project-specific rules, opencode will combine them t ## Custom Instructions -You can also specify custom instruction files using the `instructions` configuration in your `opencode.json` or global `~/.config/opencode/config.json`: +You can specify custom instruction files in your `opencode.json` or the global `~/.config/opencode/config.json`. This allows you and your team to reuse existing rules rather than having to duplicate them to AGENTS.md. + +Example: ```json title="opencode.json" { "$schema": "https://opencode.ai/config.json", - "instructions": [".cursor/rules/*.md"] -} -``` - -You can specify multiple files like `CONTRIBUTING.md` and `docs/guidelines.md`, and use glob patterns to match multiple files. - -For example, to reuse your existing Cursor rules: - -```json title="opencode.json" -{ - "$schema": "https://opencode.ai/config.json", - "instructions": [".cursor/rules/*.md"] + "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"] } ``` diff --git a/packages/web/src/content/docs/docs/themes.mdx b/packages/web/src/content/docs/docs/themes.mdx index da612284..3defceae 100644 --- a/packages/web/src/content/docs/docs/themes.mdx +++ b/packages/web/src/content/docs/docs/themes.mdx @@ -9,22 +9,34 @@ By default, opencode uses our own `opencode` theme. --- +## Terminal requirements + +For themes to display correctly with their full color palette, your terminal must support **truecolor** (24-bit color). Most modern terminals support this by default, but you may need to enable it: + +- **Check support**: Run `echo $COLORTERM` - it should output `truecolor` or `24bit` +- **Enable truecolor**: Set the environment variable `COLORTERM=truecolor` in your shell profile +- **Terminal compatibility**: Ensure your terminal emulator supports 24-bit color (most modern terminals like iTerm2, Alacritty, Kitty, Windows Terminal, and recent versions of GNOME Terminal do) + +Without truecolor support, themes may appear with reduced color accuracy or fall back to the nearest 256-color approximation. + +--- + ## Built-in themes opencode comes with several built-in themes. -| Name | Description | -| --- | --- | -| `system` | Adapts to your terminal's background color | -| `tokyonight` | Based on the Tokyonight theme | -| `everforest` | Based on the Everforest theme | -| `ayu` | Based on the Ayu dark theme | -| `catppuccin` | Based on the Catppuccin theme | -| `gruvbox` | Based on the Gruvbox theme | -| `kanagawa` | Based on the Kanagawa theme | -| `nord` | Based on the Nord theme | -| `matrix` | Hacker-style green on black theme | -| `one-dark` | Based on the Atom One Dark theme | +| Name | Description | +| ------------ | ------------------------------------------ | +| `system` | Adapts to your terminal's background color | +| `tokyonight` | Based on the Tokyonight theme | +| `everforest` | Based on the Everforest theme | +| `ayu` | Based on the Ayu dark theme | +| `catppuccin` | Based on the Catppuccin theme | +| `gruvbox` | Based on the Gruvbox theme | +| `kanagawa` | Based on the Kanagawa theme | +| `nord` | Based on the Nord theme | +| `matrix` | Hacker-style green on black theme | +| `one-dark` | Based on the Atom One Dark theme | And more, we are constantly adding new themes. @@ -61,7 +73,7 @@ You can select a theme by bringing up the theme select with the `/theme` command ## Custom themes -opencode supports a flexible JSON-based theme system that allows users to create and customize themes easily. +opencode supports a flexible JSON-based theme system that allows users to create and customize themes easily. --- diff --git a/packages/web/src/content/docs/docs/troubleshooting.mdx b/packages/web/src/content/docs/docs/troubleshooting.mdx new file mode 100644 index 00000000..1640d634 --- /dev/null +++ b/packages/web/src/content/docs/docs/troubleshooting.mdx @@ -0,0 +1,74 @@ +--- +title: Troubleshooting +description: Common issues and how to resolve them. +--- + +## Logs + +opencode writes detailed logs that can help diagnose issues. Log files are stored in: + +- **macOS/Linux**: `~/.local/share/opencode/log/` +- **Windows**: `%APPDATA%\opencode\log\` + +Log files are named with timestamps (e.g., `2025-01-09T123456.log`) and the most recent 10 log files are kept. + +You can configure the log level in your [config file](/docs/config#logging) to get more detailed debug information. + +--- + +## Storage + +opencode stores session data and other application data on disk at: + +- **macOS/Linux**: `~/.local/share/opencode/` +- **Windows**: `%APPDATA%\opencode\` + +This directory contains: + +- `auth.json` - Authentication data (e.g., API keys, OAuth tokens) +- `log/` - Application logs +- `project/` - Project-specific data (e.g., session and message data) + +--- + +## Getting help + +If you're experiencing issues with opencode: + +### Report issues on GitHub + +The best way to report bugs or request features is through our GitHub repository: + +[**github.com/sst/opencode/issues**](https://github.com/sst/opencode/issues) + +Before creating a new issue, please search existing issues to see if your problem has already been reported. + +### Join our Discord + +For real-time help and community discussion, join our Discord server: + +[**opencode.ai/discord**](https://opencode.ai/discord) + +Our community and team are happy to help with questions and troubleshooting. + +--- + +## Common issues + +### opencode won't start + +1. Check the logs for error messages +2. Try running with `--print-logs` to see output in the terminal +3. Ensure you have the latest version with `opencode upgrade` + +### Authentication issues + +1. Try re-authenticating with `opencode auth login ` +2. Check that your API keys are valid +3. Ensure your network allows connections to the provider's API + +### Model not available + +1. Check that you've authenticated with the provider +2. Verify the model name in your config is correct +3. Some models may require specific access or subscriptions diff --git a/packages/web/src/pages/s/[id].astro b/packages/web/src/pages/s/[id].astro index a81d2e78..fadf0eb0 100644 --- a/packages/web/src/pages/s/[id].astro +++ b/packages/web/src/pages/s/[id].astro @@ -23,9 +23,8 @@ const models: Set = new Set(); const version = data.info.version ? `v${data.info.version}` : "v0.0.1"; Object.values(data.messages).forEach((d) => { - const assistant = d.metadata?.assistant; - if (assistant) { - models.add(assistant.modelID); + if (d.role === "assistant" && d.modelID) { + models.add(d.modelID); } }); @@ -39,8 +38,19 @@ const encodedTitle = encodeURIComponent( ) ); -const ogImage = `${config.socialCard}/opencode-share/${encodedTitle}.png?model=${Array.from(models).join(",")}&version=${version}&id=${id}`; +const modelsArray = Array.from(models); +let modelParam; +if (modelsArray.length === 1) { + modelParam = modelsArray[0]; +} +else if (modelsArray.length === 2) { + modelParam = encodeURIComponent(`${modelsArray[0]} & ${modelsArray[1]}`); +} +else { + modelParam = encodeURIComponent(`${modelsArray[0]} & ${modelsArray.length - 1} others`); +} +const ogImage = `${config.socialCard}/opencode-share/${encodedTitle}.png?model=${modelParam}&version=${version}&id=${id}`; --- ; + extensions: Record /** All languages keyed by file-extension */ - languages: Record; + languages: Record } /** @@ -14,14 +14,14 @@ declare module "lang-map" { * const { extensions, languages } = map(); * ``` */ - function map(): MapReturn; + function map(): MapReturn /** Static method: get extensions for a given language */ namespace map { - function extensions(language: string): string[]; + function extensions(language: string): string[] /** Static method: get languages for a given extension */ - function languages(extension: string): string[]; + function languages(extension: string): string[] } - export = map; + export = map } diff --git a/packages/web/sst-env.d.ts b/packages/web/sst-env.d.ts index b6a7e906..0397645b 100644 --- a/packages/web/sst-env.d.ts +++ b/packages/web/sst-env.d.ts @@ -6,4 +6,4 @@ /// import "sst" -export {} \ No newline at end of file +export {} diff --git a/scripts/stats.ts b/scripts/stats.ts index b30e57d9..2abe7e1c 100755 --- a/scripts/stats.ts +++ b/scripts/stats.ts @@ -26,13 +26,9 @@ async function fetchNpmDownloads(packageName: string): Promise { // Use a range from 2020 to current year + 5 years to ensure it works forever const currentYear = new Date().getFullYear() const endYear = currentYear + 5 - const response = await fetch( - `https://api.npmjs.org/downloads/range/2020-01-01:${endYear}-12-31/${packageName}`, - ) + const response = await fetch(`https://api.npmjs.org/downloads/range/2020-01-01:${endYear}-12-31/${packageName}`) if (!response.ok) { - console.warn( - `Failed to fetch npm downloads for ${packageName}: ${response.status}`, - ) + console.warn(`Failed to fetch npm downloads for ${packageName}: ${response.status}`) return 0 } const data: NpmDownloadsRange = await response.json() @@ -53,9 +49,7 @@ async function fetchReleases(): Promise { const response = await fetch(url) if (!response.ok) { - throw new Error( - `GitHub API error: ${response.status} ${response.statusText}`, - ) + throw new Error(`GitHub API error: ${response.status} ${response.statusText}`) } const batch: Release[] = await response.json() @@ -115,11 +109,7 @@ async function save(githubTotal: number, npmDownloads: number) { for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i].trim() - if ( - line.startsWith("|") && - !line.includes("Date") && - !line.includes("---") - ) { + if (line.startsWith("|") && !line.includes("Date") && !line.includes("---")) { const match = line.match( /\|\s*[\d-]+\s*\|\s*([\d,]+)\s*(?:\([^)]*\))?\s*\|\s*([\d,]+)\s*(?:\([^)]*\))?\s*\|\s*([\d,]+)\s*(?:\([^)]*\))?\s*\|/, ) @@ -147,11 +137,7 @@ async function save(githubTotal: number, npmDownloads: number) { ? ` (${githubChange.toLocaleString()})` : " (+0)" const npmChangeStr = - npmChange > 0 - ? ` (+${npmChange.toLocaleString()})` - : npmChange < 0 - ? ` (${npmChange.toLocaleString()})` - : " (+0)" + npmChange > 0 ? ` (+${npmChange.toLocaleString()})` : npmChange < 0 ? ` (${npmChange.toLocaleString()})` : " (+0)" const totalChangeStr = totalChange > 0 ? ` (+${totalChange.toLocaleString()})` @@ -182,9 +168,7 @@ const { total: githubTotal, stats } = calculate(releases) console.log("Fetching npm all-time downloads for opencode-ai...\n") const npmDownloads = await fetchNpmDownloads("opencode-ai") -console.log( - `Fetched npm all-time downloads: ${npmDownloads.toLocaleString()}\n`, -) +console.log(`Fetched npm all-time downloads: ${npmDownloads.toLocaleString()}\n`) await save(githubTotal, npmDownloads) @@ -202,24 +186,18 @@ console.log("-".repeat(60)) stats .sort((a, b) => b.downloads - a.downloads) .forEach((release) => { - console.log( - `${release.tag.padEnd(15)} ${release.downloads.toLocaleString().padStart(10)} downloads`, - ) + console.log(`${release.tag.padEnd(15)} ${release.downloads.toLocaleString().padStart(10)} downloads`) if (release.assets.length > 1) { release.assets .sort((a, b) => b.downloads - a.downloads) .forEach((asset) => { - console.log( - ` └─ ${asset.name.padEnd(25)} ${asset.downloads.toLocaleString().padStart(8)}`, - ) + console.log(` └─ ${asset.name.padEnd(25)} ${asset.downloads.toLocaleString().padStart(8)}`) }) } }) console.log("-".repeat(60)) -console.log( - `GitHub Total: ${githubTotal.toLocaleString()} downloads across ${releases.length} releases`, -) +console.log(`GitHub Total: ${githubTotal.toLocaleString()} downloads across ${releases.length} releases`) console.log(`npm Total: ${npmDownloads.toLocaleString()} downloads`) console.log(`Combined Total: ${totalDownloads.toLocaleString()} downloads`) diff --git a/sst-env.d.ts b/sst-env.d.ts index 627d74a5..45c07b66 100644 --- a/sst-env.d.ts +++ b/sst-env.d.ts @@ -5,20 +5,20 @@ declare module "sst" { export interface Resource { - "Api": { - "type": "sst.cloudflare.Worker" - "url": string + Api: { + type: "sst.cloudflare.Worker" + url: string } - "Bucket": { - "type": "sst.cloudflare.Bucket" + Bucket: { + type: "sst.cloudflare.Bucket" } - "Web": { - "type": "sst.cloudflare.Astro" - "url": string + Web: { + type: "sst.cloudflare.Astro" + url: string } } } /// import "sst" -export {} \ No newline at end of file +export {} diff --git a/stainless.yml b/stainless.yml index f8d654fb..9cc29c06 100644 --- a/stainless.yml +++ b/stainless.yml @@ -34,6 +34,7 @@ resources: models: unknownError: UnknownError providerAuthError: ProviderAuthError + messageAbortedError: MessageAbortedError event: methods: @@ -47,17 +48,24 @@ resources: app: models: app: App + logLevel: LogLevel methods: get: get /app init: post /app/init + log: post /log find: + models: + match: Match + symbol: Symbol methods: text: get /find files: get /find/file symbols: get /find/symbol file: + models: + file: File methods: read: get /file status: get /file/status @@ -78,16 +86,19 @@ resources: models: session: Session message: Message - toolCall: ToolCall - toolPartialCall: ToolPartialCall - toolResult: ToolResult textPart: TextPart - reasoningPart: ReasoningPart - toolInvocationPart: ToolInvocationPart - sourceUrlPart: SourceUrlPart filePart: FilePart + toolPart: ToolPart stepStartPart: StepStartPart - messagePart: MessagePart + assistantMessage: AssistantMessage + assistantMessagePart: AssistantMessagePart + userMessage: UserMessage + userMessagePart: UserMessagePart + toolStatePending: ToolStatePending + toolStateRunning: ToolStateRunning + toolStateCompleted: ToolStateCompleted + toolStateError: ToolStateError + methods: list: get /session create: post /session